Warning: Undefined array key "hide_archive_titles" in /home1/smartva9/public_html/smartvania/wp-content/themes/baton/includes/theme-functions.php on line 254

Category: Programming

Code Request

I was watching your videos on youtube about assembly, but I have many doubts… I have an exercise to do until next Sunday, and I don’t know how to do it!
The steps are:

A) Send the message: “Enter your registration number”;
B) Receive 9 numeric digits corresponding to a registration number;
C) If the registration is all zero, and the program (call the system with the exit operation)
D) Search in the registrations stored as constants in the program
D.1) If you find the registration, present the text:
“The registration number XXXXXXXXX corresponds to student YYYYYYYY.”
D.2) If you can not find the registration, please submit the text:
“Registration XXXXXXXXX was not found”
D.3) If the registration number corresponds to your registration number, present the text:
“It’s me! I’M YYYYY YYYYY YYYY and my register number is XXXXXXXXX ”
E) Go back to step “A”

The names must be stored using .asciiz and the registration numbers must be stored as a 32-bit integer, formatted as BCD, that is, every 4 bits, we have a decimal digit. The first number of the register number is always 1 and should not be stored. Registration example: 112345678 will be stored in hexadecimal as
12345678h (binary 0001_0010_0011_0100_0101_0110_0111_1000);

See below:

# Partially completed solution.
.data
message: .asciiz "Enter your registration number: "
found_message: .asciiz "The registration number XXXXXXXXX corresponds to student YYYYYYYY.\n"
not_found_message: .asciiz "Registration XXXXXXXXX was not found.\n"
my_number_found_message: .asciiz "It's me! I'M YYYYY YYYYY YYYY, and my register number is XXXXXXXXX.\n"
registration_names: .asciiz "XXXXXX", "YYYYYY"
registration_numbers: .word 0x0000000, 0x000000
my_number: .word 0x000000

.eqv ARRAY_SIZE 8 # 2 ints = 8 bytes
.text
main:
loop:
# Show prompt.
li $v0, 4
la $a0, message
syscall

# Get input.
li $v0, 5
syscall

# If all 0's, then end program.
move $a0, $v0
beqz $a0, main_exit

# Search (pass value to search in $a1).
move $a1, $a0
jal search_registration

b loop

main_exit:
li $v0, 10
syscall

# Expects user input in $a1.
search_registration:
# $t1 is loop index. $t2 is my number.
li $t1, 0
search_loop:
lw $a0, registration_numbers($t1)
beq, $a0, $a1, number_found
addi $t1, $t1, 4
beq $t1, ARRAY_SIZE, number_not_found
blt $t1, ARRAY_SIZE, search_loop

number_found:
lw $t2, my_number
beq $a0, $t2, my_number_found
li $v0, 4
la $a0, found_message
syscall

b search_registration_exit
my_number_found:
li $v0, 4
la $a0, my_number_found_message

syscall
b search_registration_exit
number_not_found:
li $v0, 4
la $a0, not_found_message
syscall
search_registration_exit:
jr $ra

Code Request

Sir, can you please make quadratic equation solver in assembly or just
square root function I’m having a problem in square root part please
help?
Raj

2016-03-25 08:14

See below:
#——————————————————————————————
# Subroutine: sqrt
# Usage: v0 = sqrt(a0)
# Description:
# Takes a positive signed integer in $a0 and returns its integer square root
# (i.e., the floor of its real square root) in $v0.
# Arguments: $a0 – A positive signed integer to take the square root of.
# Result: $v0 – The floor of the square root of the argument, as an integer.
# Side effects: The previous contents of register $t0 are trashed.
# Local variables:
# $v0 – Number r currently being tested to see if it is the square root.
# $t0 – Square of r.
# Stack usage: none
#——————————————————————————————
sqrt: addi $v0, $zero, 0 # r := 0
loop: mul $t0, $v0, $v0 # t0 := r*r
bgt $t0, $a0, end # if (r*r > n) goto end
addi $v0, $v0, 1 # r := r + 1
j loop # goto loop
end: addi $v0, $v0, -1 # r := r – 1
jr $ra # return with r-1 in $v0

-Amell

Java interview questions

The Toptal Engineering Blog has published a great post called
8 Essential Java Interview Questions” on there you can submit your Java interview questions, answers and hire freelancers,
and they were happy to share with us these questions. If you would like to like them on Facebook click on the link Toptal on Facebook
8 Essential Java Interview Questions
Click on the question to see the answer

The main distinction between fail-fast and fail-safe
iterators is whether or not the collection can be modified while it is being iterated.
Fail-safe iterators allow this; fail-fast iterators do not.


Of the three, LinkedList is generally going to give you the best performance. Here’s why:

ArrayList and
Vector each use an array to store the elements of the list.
As a result, when an element is inserted into (or removed from) the middle of the list, the elements that follow must all be shifted accordingly.
Vector is synchronized, so if a thread-safe implementation is
not needed, it is recommended to use ArrayList rather than Vector.


In Java, Strings are immutable
and are stored in the String pool. What this means is that, once a String is created, it stays in the pool in memory until being garbage collected.
Therefore, even after you’re done processing the string value (e.g., the password), it remains available in memory for an indeterminate period of time thereafter
(again, until being garbage collected) which you have no real control over. Therefore, anyone having access to a memory dump can potentially extract the sensitive data and exploit it.


A single ThreadLocal
instance can store different values for each thread independently. Each thread that accesses the get() or set() method of a
ThreadLocal instance is accessing its own, independently initialized copy of the variable. ThreadLocal i
nstances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or transaction ID).
The example below, from the ThreadLocal Javadoc,
generates unique identifiers local to each thread. A thread’s id is assigned the first time it invokes ThreadId.get() and remains unchanged on subsequent calls.

public class ThreadId {
			// Next thread ID to be assigned
			private static final AtomicInteger nextId = new AtomicInteger(0);
				// Thread local variable containing each thread's ID
			private static final ThreadLocal<Integer> threadId =
				new ThreadLocal<Integer>() {
					@Override protected Integer initialValue() {
						return nextId.getAndIncrement();
				}
			};

			// Returns the current thread's unique ID, assigning it if necessary
			public static int get() {
				return threadId.get();
			}
		}
		


In Java, each thread has its own stack, including its own copy of variables it can access.
When the thread is created, it copies the value of all accessible variables into its own stack. The volatile
keyword basically says to the JVM “Warning, this variable may be modified in another Thread”.

In all versions of Java, the volatile keyword guarantees global ordering on reads and writes
to a variable. This implies that every thread accessing a volatile field will read the variable’s current value instead of (potentially) using a cached value.

In Java 5 or later, volatile reads and writes establish a happens-before
relationship, much like acquiring and releasing a mutex.

Using volatile may be faster than a lock, but
it will not work in some situations. The range of situations in which volatile is
effective was expanded in Java 5; in particular, double-checked locking now works correctly.

One common example for using volatile is for a flag to terminate a thread. If you’ve started a thread, and you want to be able to safely interrupt it from a different thread, you can have the thread periodically check a flag (i.e., to stop it, set the flag to true). By making the flag volatile, you can ensure that the thread that is checking its value will see that it has been set to true without even having to use a synchronized block. For example:

public class Foo extends Thread {
		private volatile boolean close = false;
		public void run() {
			while(!close) {
				// do work
			}
		}
		public void close() {
			close = true;
			// interrupt here if needed
		}
	}
	


sleep() is a blocking operation that keeps a hold on the monitor / lock of the shared object for the specified number of milliseconds.

wait(), on the other hand, simply pauses the thread until either (a) the specified number of milliseconds have elapsed or
(b) it receives a desired notification from another thread (whichever is first), without keeping a hold on the monitor/lock of the shared object.

sleep() is most commonly used for polling, or to check for certain results, at a regular interval. wait() is generally used in
multithreaded applications, in conjunction with notify() / notifyAll(), to achieve synchronization and avoid race conditions.


Here is an example of a typical recursive function, computing the arithmetic series 1, 2, 3…N. Notice how the addition is performed after
the function call. For each recursive step, we add another frame to the stack.

public int sumFromOneToN(int n) {
	  if (n < 1) {
		return n;
	  }

	  return n + sumFromOneToN(n - 1);
	}
	

Tail recursion occurs when the recursive call is in the tail position within its enclosing context –
after the function calls itself, it performs no additional work. That is, once the base case is complete,
the solution is apparent. For example:

public int sumFromOneToN(int n, int a) {
	  if (n < 1) {
		return a;
	  }

	  return sumFromOneToN(n - 1, a + n);
	}
	

Here you can see that a plays the role of the accumulator – instead of computing the sum on
the way down the stack, we compute it on the way up, effectively making the return trip unnecessary,
since it stores no additional state and performs no further computation. Once we hit the base case, the work is done – below is that same function, “unrolled”.

public int sumFromOneToN(int n) {
	  int a = 0;

	  while(n > 0) {
		a += n--;
	  }
	  
	  return a;
	}
	

Many functional languages natively support tail call optimization, however the JVM does not. In order
to implement recursive functions in Java, we need to be aware of this limitation to avoid
StackOverflowErrors. In Java, iteration is almost universally preferred to recursion.


This can be done using Thread.UncaughtExceptionHandler.

Here’s a simple example:

// create our uncaught exception handler
	Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
		public void uncaughtException(Thread th, Throwable ex) {
			System.out.println("Uncaught exception: " + ex);
		}
	};

	// create another thread
	Thread otherThread = new Thread() {
		public void run() {
			System.out.println("Sleeping ...");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				System.out.println("Interrupted.");
			}
			System.out.println("Throwing exception ...");
			throw new RuntimeException();
		}
	};

	// set our uncaught exception handler as the one to be used when the new thread
	// throws an uncaught exception
	otherThread.setUncaughtExceptionHandler(handler);

	// start the other thread - our uncaught exception handler will be invoked when
	// the other thread throws an uncaught exception
	otherThread.start();
	

Java review First day: Beginner

Hi, I will be giving a class on java programming,

Today in our first lesson we are going to review/learn some printing statements, for loops and if statements.
First of all lets start by the software that we will be using for our class.
for IDEA:
IntelliJ
Download IntelliJ
Then we will have to download the java SDK:
Download Java SDK

To create a new project in IntelliJ, we click on, create new project ( the first time the project needs to be aligned with java sdk).
Then we create a package, and afterwards a java class usually with the same name of the package. It will be assigned a default constructor.

In order for the java program to run, there should be a main static method.

We will be using the scanner class today, that must be imported with:

import java.util.Scanner;

Below there is an example for the lesson of today:

Printing to the screen:
 

import java.util.Scanner;
public class Hello {
	
	public static void main(String[] args){
		System.out.println("hello Yanilda");
		System.out.print("Hey Yani");
		System.out.printf("Hi Yani");
		System.out.print("Hey Yani");
		
		for(int i=0; i<10;i++){
			System.out.println("hello Yanilda");
		}
		
		int aNumber, bNumber;
		System.out.println("enter input");
		Scanner scaner1 = new Scanner(System.in);
		Anumber=scaner1.nextInt();
		System.out.println("enter input");
		Bnumber=scaner1.nextInt();
		scaner1.close();
		int abSum=aNumber+bNumber;
		System.out.println("Sum is "+abSum);	
		
		if(abSum<10){
			System.out.println("Less than 10");
		}
		else if(abSum>10){
			System.out.println("Greater than 10");
		} 
		else{
			for(int i=0;i<5;i++){
			System.out.println(" Equal to 10");
			}
		}
	
	}
}

>>

hello Yanilda
Hey YaniHi YaniHey Yanihello Yanilda
hello Yanilda
hello Yanilda
hello Yanilda
hello Yanilda
hello Yanilda
hello Yanilda
hello Yanilda
hello Yanilda
hello Yanilda
enter input
5
enter input
5
Sum is 10
Equal to 10
Equal to 10
Equal to 10
Equal to 10
Equal to 10

Comments can be done by using:
// for one line

***** For beauty
It's always good to have documentation, name of the the program with extension, name of the author, the date and what the program does. under the import statements.

/**
* Hello.java
* Purpose: Uses if Statements and for loops, prints and gather input's user.
*
* @author Yanilda Peralta
* @version 1.0 6/05/2015
*/

Today Practice programs:
1- Create a program that asks user for name and then prints out the name + how are you?
2- Create Sum the numbers from 1 to 10 using for loops
3- Create program that takes an integer input from user and if the integer is positive prints "positive"x3, if it's negative it prints"negative"x4 and if it's zero, print neutral. Use For loops and if statements.

Indentation is needed for readability.
white space between the things that don't belong to a group.
Name convention.
Meaningful names will give you a description of the purpose of the the object/class/method/variable.
When naming variable in java, the camel style is the way to go, start with lowercase then change to Uppercase if it's a combination of words, e.g. myNumber. don't use under bars, but if wanting to use under bars, put all letters in capital, MY_NUMBER.
For Class names use Uppercase, MyClass.
For methods start with lowercase. myMethod.

For Homework submission email to:
java_homework@smartvania.com

Homework # 1 -
Create 3 different programs:
1- Ask the user for 3 inputs. Then you will decide which input is larger than the other.Then you print out the largest.
2-Reverse string in 2 different ways.
3-Do the Palindrome in 2 different ways.

How to reverse a list recursively in Racket


(define (yani-reverse L) [if (null? L) null [append (yani-reverse (rest L))(list [first L])]])

In plain racket, define is used to define functions and variables.
The syntax, comes (define id expr) or (define (head args) body++)
Above I defined a function called yani-reverse with L as argument which in this case is a list, parenthesizes and square brackets are interchangeable. I’m doing a if statement that will check if my L ( list) is not null, if it’s null it will return null, if else it will append the last element of the list into an a list with the first element.
First is the first element of the list and rest of the rest elements of the list.

Lets now call our function


(yani-reverse '(a b c d))

(yani-reverse '(1 2 3 4))

(yani-reverse '( ))

>
'(d c b a)
'(4 3 2 1)
'()