Programs & Examples On #Methods

A method is a block of code that performs a task and is associated with a class or an object. It is related to the non-object-oriented concepts of functions and procedures.

Android: How can I pass parameters to AsyncTask's onPreExecute()?

why, how and which parameters are passed to Asynctask<>, see detail here. I think it is the best explanation.

Google's Android Documentation Says that :

An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

AsyncTask's generic types :

The three types used by an asynchronous task are the following:

Params, the type of the parameters sent to the task upon execution. Progress, the type of the progress units published during the background computation. Result, the type of the result of the background computation. Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:

 private class MyTask extends AsyncTask<Void, Void, Void> { ... }

You Can further refer : http://developer.android.com/reference/android/os/AsyncTask.html

Or You Can clear whats the role of AsyncTask by refering Sankar-Ganesh's Blog

Well The structure of a typical AsyncTask class goes like :

private class MyTask extends AsyncTask<X, Y, Z>

    protected void onPreExecute(){ 

    } 

This method is executed before starting the new Thread. There is no input/output values, so just initialize variables or whatever you think you need to do.

protected Z doInBackground(X...x){

}

The most important method in the AsyncTask class. You have to place here all the stuff you want to do in the background, in a different thread from the main one. Here we have as an input value an array of objects from the type “X” (Do you see in the header? We have “...extends AsyncTask” These are the TYPES of the input parameters) and returns an object from the type “Z”.

protected void onProgressUpdate(Y y){

} This method is called using the method publishProgress(y) and it is usually used when you want to show any progress or information in the main screen, like a progress bar showing the progress of the operation you are doing in the background.

protected void onPostExecute(Z z){

} This method is called after the operation in the background is done. As an input parameter you will receive the output parameter of the doInBackground method.

What about the X, Y and Z types?

As you can deduce from the above structure:

X – The type of the input variables value you want to set to the background process. This can be an array of objects.

 Y – The type of the objects you are going to enter in the onProgressUpdate method.

 Z – The type of the result from the operations you have done in the background process.

How do we call this task from an outside class? Just with the following two lines:

MyTask myTask = new MyTask();

myTask.execute(x);

Where x is the input parameter of the type X.

Once we have our task running, we can find out its status from “outside”. Using the “getStatus()” method.

myTask.getStatus(); and we can receive the following status:

RUNNING - Indicates that the task is running.

PENDING - Indicates that the task has not been executed yet.

FINISHED - Indicates that onPostExecute(Z) has finished.

Hints about using AsyncTask

Do not call the methods onPreExecute, doInBackground and onPostExecute manually. This is automatically done by the system.

You cannot call an AsyncTask inside another AsyncTask or Thread. The call of the method execute must be done in the UI Thread.

The method onPostExecute is executed in the UI Thread (here you can call another AsyncTask!).

The input parameters of the task can be an Object array, this way you can put whatever objects and types you want.

Java: Sending Multiple Parameters to Method

The solution depends on the answer to the question - are all the parameters going to be the same type and if so will each be treated the same?

If the parameters are not the same type or more importantly are not going to be treated the same then you should use method overloading:

public class MyClass
{
  public void doSomething(int i) 
  {
    ...
  }

  public void doSomething(int i, String s) 
  {
    ...
  }

  public void doSomething(int i, String s, boolean b) 
  {
    ...
  }
}

If however each parameter is the same type and will be treated in the same way then you can use the variable args feature in Java:

public MyClass 
{
  public void doSomething(int... integers)
  {
    for (int i : integers) 
    {
      ...
    }
  }
}

Obviously when using variable args you can access each arg by its index but I would advise against this as in most cases it hints at a problem in your design. Likewise, if you find yourself doing type checks as you iterate over the arguments then your design needs a review.

How to display all methods of an object?

Most modern browser support console.dir(obj), which will return all the properties of an object that it inherited through its constructor. See Mozilla's documentation for more info and current browser support.

console.dir(Math)
=> MathConstructor
E: 2.718281828459045
LN2: 0.6931471805599453
...
tan: function tan() { [native code] }
__proto__: Object

Set and Get Methods in java?

Set and Get methods are a pattern of data encapsulation. Instead of accessing class member variables directly, you define get methods to access these variables, and set methods to modify them. By encapsulating them in this manner, you have control over the public interface, should you need to change the inner workings of the class in the future.

For example, for a member variable:

Integer x;

You might have methods:

Integer getX(){ return x; }
void setX(Integer x){ this.x = x; }

chiccodoro also mentioned an important point. If you only want to allow read access to the field for any foreign classes, you can do that by only providing a public get method and keeping the set private or not providing a set at all.

Java variable number or arguments for a method

Yes Java allows vargs in method parameter .

public class  Varargs
{
   public int add(int... numbers)
   { 
      int result = 1; 
      for(int number: numbers)
      {
         result= result+number;  
      }  return result; 
   }
}

Reflection: How to Invoke Method with parameters

I would use it like this, its way shorter and it won't give any problems

        dynamic result = null;
        if (methodInfo != null)
        {
            ParameterInfo[] parameters = methodInfo.GetParameters();
            object classInstance = Activator.CreateInstance(type, null);
            result = methodInfo.Invoke(classInstance, parameters.Length == 0 ? null : parametersArray);
        }

class method generates "TypeError: ... got multiple values for keyword argument ..."

just add 'staticmethod' decorator to function and problem is fixed

class foo(object):
    @staticmethod
    def foodo(thing=None, thong='not underwear'):
        print thing if thing else "nothing" 
        print 'a thong is',thong

TypeError: method() takes 1 positional argument but 2 were given

Pass cls parameter into @classmethod to resolve this problem.

@classmethod
def test(cls):
    return ''

C# cannot convert method to non delegate type

You can simplify your class code to this below and it will work as is but if you want to make your example work, add parenthesis at the end : string x = getTitle();

public class Pin
{
   public string Title { get; set;}
}

Cannot refer to a non-final variable inside an inner class defined in a different method

With anonymous classes, you are actually declaring a "nameless" nested class. For nested classes, the compiler generates a new standalone public class with a constructor that will take all the variables it uses as arguments (for "named" nested classes, this is always an instance of the original/enclosing class). This is done because the runtime environment has no notion of nested classes, so there needs to be a (automatic) conversion from a nested to a standalone class.

Take this code for example:

public class EnclosingClass {
    public void someMethod() {
        String shared = "hello"; 
        new Thread() {
            public void run() {
                // this is not valid, won't compile
                System.out.println(shared); // this instance expects shared to point to the reference where the String object "hello" lives in heap
            }
        }.start();

        // change the reference 'shared' points to, with a new value
        shared = "other hello"; 
        System.out.println(shared);
    }
}

That won't work, because this is what the compiler does under the hood:

public void someMethod() {
    String shared = "hello"; 
    new EnclosingClass$1(shared).start();

    // change the reference 'shared' points to, with a new value
    shared = "other hello"; 
    System.out.println(shared);
}

The original anonymous class is replaced by some standalone class that the compiler generates (code is not exact, but should give you a good idea):

public class EnclosingClass$1 extends Thread {
    String shared;
    public EnclosingClass$1(String shared) {
        this.shared = shared;
    }

    public void run() {
        System.out.println(shared);
    }
}

As you can see, the standalone class holds a reference to the shared object, remember that everything in java is pass-by-value, so even if the reference variable 'shared' in EnclosingClass gets changed, the instance it points to is not modified, and all other reference variables pointing to it (like the one in the anonymous class: Enclosing$1), will not be aware of this. This is the main reason the compiler forces you to declare this 'shared' variables as final, so that this type of behavior won't make it into your already running code.

Now, this is what happens when you use an instance variable inside an anonymous class (this is what you should do to solve your problem, move your logic to an "instance" method or a constructor of a class):

public class EnclosingClass {
    String shared = "hello";
    public void someMethod() {
        new Thread() {
            public void run() {
                System.out.println(shared); // this is perfectly valid
            }
        }.start();

        // change the reference 'shared' points to, with a new value
        shared = "other hello"; 
        System.out.println(shared);
    }
}

This compiles fine, because the compiler will modify the code, so that the new generated class Enclosing$1 will hold a reference to the instance of EnclosingClass where it was instantiated (this is only a representation, but should get you going):

public void someMethod() {
    new EnclosingClass$1(this).start();

    // change the reference 'shared' points to, with a new value
    shared = "other hello"; 
    System.out.println(shared);
}

public class EnclosingClass$1 extends Thread {
    EnclosingClass enclosing;
    public EnclosingClass$1(EnclosingClass enclosing) {
        this.enclosing = enclosing;
    }

    public void run() {
        System.out.println(enclosing.shared);
    }
}

Like this, when the reference variable 'shared' in EnclosingClass gets reassigned, and this happens before the call to Thread#run(), you'll see "other hello" printed twice, because now EnclosingClass$1#enclosing variable will keep a reference to the object of the class where it was declared, so changes to any attribute on that object will be visible to instances of EnclosingClass$1.

For more information on the subject, you can see this excelent blog post (not written by me): http://kevinboone.net/java_inner.html

How do I call a dynamically-named method in Javascript?

I wouldn't recommend using the window as some of the other answers suggest. Use this and scope accordingly.

this['yourDynamicFcnName'](arguments);

Another neat trick is calling within different scopes and using it for inheritance. Let's say you had nested the function and want access to the global window object. You could do this:

this['yourDynamicFcnName'].call(window, arguments);

Methods vs Constructors in Java

A "method" is a "subroutine" is a "procedure" is a "function" is a "subprogram" is a ... The same concept goes under many different names, but basically is a named segment of code that you can "call" from some other code. Generally the code is neatly packaged somehow, with a "header" of some sort which gives its name and parameters and a "body" set off by BEGIN & END or { & } or some such.

A "consrtructor" is a special form of method whose purpose is to initialize an instance of a class or structure.

In Java a method's header is <qualifiers> <return type> <method name> ( <parameter type 1> <parameter name 1>, <parameter type 2> <parameter name 2>, ...) <exceptions> and a method body is bracketed by {}.

And you can tell a constructor from other methods because the constructor has the class name for its <method name> and has no declared <return type>.

(In Java, of course, you create a new class instance with the new operator -- new <class name> ( <parameter list> ).)

What is a "method" in Python?

It's a function which is a member of a class:

class C:
    def my_method(self):
        print("I am a C")

c = C()
c.my_method()  # Prints("I am a C")

Simple as that!

(There are also some alternative kinds of method, allowing you to control the relationship between the class and the function. But I'm guessing from your question that you're not asking about that, but rather just the basics.)

C# : Passing a Generic Object

You're missing at least a couple of things:

  • Unless you're using reflection, the type arguments need to be known at compile-time, so you can't use

    PrintGeneric<test2.GetType()>
    

    ... although in this case you don't need to anyway

  • PrintGeneric doesn't know anything about T at the moment, so the compiler can't find a member called T

Options:

  • Put a property in the ITest interface, and change PrintGeneric to constrain T:

    public void PrintGeneric<T>(T test) where T : ITest
    {
        Console.WriteLine("Generic : " + test.PropertyFromInterface);
    }
    
  • Put a property in the ITest interface and remove the generics entirely:

    public void PrintGeneric(ITest test)
    {
        Console.WriteLine("Property : " + test.PropertyFromInterface);
    }
    
  • Use dynamic typing instead of generics if you're using C# 4

Pass Method as Parameter using C#

From OP's example:

 public static int Method1(string mystring)
 {
      return 1;
 }

 public static int Method2(string mystring)
 {
     return 2;
 }

You can try Action Delegate! And then call your method using

 public bool RunTheMethod(Action myMethodName)
 {
      myMethodName();   // note: the return value got discarded
      return true;
 }

RunTheMethod(() => Method1("MyString1"));

Or

public static object InvokeMethod(Delegate method, params object[] args)
{
     return method.DynamicInvoke(args);
}

Then simply call method

Console.WriteLine(InvokeMethod(new Func<string,int>(Method1), "MyString1"));

Console.WriteLine(InvokeMethod(new Func<string, int>(Method2), "MyString2"));

Java Inheritance - calling superclass method

Whenever you create child class object then that object has all the features of parent class. Here Super() is the facilty for accession parent.

If you write super() at that time parents's default constructor is called. same if you write super.

this keyword refers the current object same as super key word facilty for accessing parents.

Can I invoke an instance method on a Ruby module without including it?

Another way to do it if you "own" the module is to use module_function.

module UsefulThings
  def a
    puts "aaay"
  end
  module_function :a

  def b
    puts "beee"
  end
end

def test
  UsefulThings.a
  UsefulThings.b # Fails!  Not a module method
end

test

PHP class: Global variable as property in class

What I've experienced is that you can't assign your global variable to a class variable directly.

class myClass() {

    public $var = $GLOBALS['variable'];

    public function func() {
         var_dump($this->var);
    }
}

With the code right above, you get an error saying "Parse error: syntax error, unexpected '$GLOBALS'"

But if we do something like this,

class myClass() {

    public $var = array();

    public function __construct() {
        $this->var = $GLOBALS['variable'];
    }

    public function func() {
         var_dump($this->var);
    }

}

Our code will work fine.

Where we assign a global variable to a class variable must be inside a function. And I've used constructor function for this.

So, you can access your global variable inside the every function of a class just using $this->var;

Passing an Array as Arguments, not an Array, in PHP

For sake of completeness, as of PHP 5.1 this works, too:

<?php
function title($title, $name) {
    return sprintf("%s. %s\r\n", $title, $name);
}
$function = new ReflectionFunction('title');
$myArray = array('Dr', 'Phil');
echo $function->invokeArgs($myArray);  // prints "Dr. Phil"
?>

See: http://php.net/reflectionfunction.invokeargs

For methods you use ReflectionMethod::invokeArgs instead and pass the object as first parameter.

What does .class mean in Java?

It means, the Class reference type can hold any Class object which represents any type. If JVM loads a type, a class object representing that type will be present in JVM. we can get the metadata regarding the type from that class object which is used very much in reflection package.

Suppose you have a a class named "myPackage.MyClass". Assuming that is in classpath, the following statements are equivalent.

Class<?> myClassObject = MyClass.class; //compile time check

Class<?> myClassObject = Class.forname("myPackage.MyClass"); //only runtime check

This works in a similar fashion if the Class<?> reference is in method argument as well.

Please note that the class "Class" does not have a public constructor. So you cannot instantiate "Class" instances with "new" operator.

java, get set methods

To understand get and set, it's all related to how variables are passed between different classes.

The get method is used to obtain or retrieve a particular variable value from a class.

A set value is used to store the variables.

The whole point of the get and set is to retrieve and store the data values accordingly.

What I did in this old project was I had a User class with my get and set methods that I used in my Server class.

The User class's get set methods:

public int getuserID()
    {
        //getting the userID variable instance
        return userID;
    }
    public String getfirstName()
    {
        //getting the firstName variable instance
        return firstName;
    }
    public String getlastName()
    {
        //getting the lastName variable instance
        return lastName;
    }
    public int getage()
    {
        //getting the age variable instance
        return age;
    }

    public void setuserID(int userID)
    {
        //setting the userID variable value
        this.userID = userID;
    }
    public void setfirstName(String firstName)
    {
        //setting the firstName variable text
        this.firstName = firstName;
    }
    public void setlastName(String lastName)
    {
        //setting the lastName variable text
        this.lastName = lastName;
    }
    public void setage(int age)
    {
        //setting the age variable value
        this.age = age;
    }
}

Then this was implemented in the run() method in my Server class as follows:

//creates user object
                User use = new User(userID, firstName, lastName, age);
                //Mutator methods to set user objects
                use.setuserID(userID);
                use.setlastName(lastName);
                use.setfirstName(firstName);               
                use.setage(age); 

Calling one method from another within same class in Python

To accessing member functions or variables from one scope to another scope (In your case one method to another method we need to refer method or variable with class object. and you can do it by referring with self keyword which refer as class object.

class YourClass():

    def your_function(self, *args):

        self.callable_function(param) # if you need to pass any parameter

    def callable_function(self, *params): 
        print('Your param:', param)

unbound method f() must be called with fibo_ instance as first argument (got classobj instance instead)

Differences in In python 2 and 3 version:

If you already have a default method in a class with same name and you re-declare as a same name it will appear as unbound-method call of that class instance when you wanted to instantiated it.

If you wanted class methods, but you declared them as instance methods instead.

An instance method is a method that is used when to create an instance of the class.

An example would be

   def user_group(self):   #This is an instance method
        return "instance method returning group"

Class label method:

   @classmethod
   def user_group(groups):   #This is an class-label method
        return "class method returning group"

In python 2 and 3 version differ the class @classmethod to write in python 3 it automatically get that as a class-label method and don't need to write @classmethod I think this might help you.

Naming conventions for Java methods that return boolean

If you wish your class to be compatible with the Java Beans specification, so that tools utilizing reflection (e.g. JavaBuilders, JGoodies Binding) can recognize boolean getters, either use getXXXX() or isXXXX() as a method name. From the Java Beans spec:

8.3.2 Boolean properties

In addition, for boolean properties, we allow a getter method to match the pattern:

public boolean is<PropertyName>();

This “is<PropertyName>” method may be provided instead of a “get<PropertyName>” method, or it may be provided in addition to a “get<PropertyName>” method. In either case, if the “is<PropertyName>” method is present for a boolean property then we will use the “is<PropertyName>” method to read the property value. An example boolean property might be:

public boolean isMarsupial();
public void setMarsupial(boolean m);

Return a string method in C#

You're currently trying to access a method like a property

Console.WriteLine("{0}",x.fullNameMethod);

It should be

Console.WriteLine("{0}",x.fullNameMethod());

Alternatively you could turn it into a property using

public string fullName
{
   get
   {
        string x = firstName + " " + lastName;
        return x;
   }
}

Retrieving data from a POST method in ASP.NET

You need to examine (put a breakpoint on / Quick Watch) the Request object in the Page_Load method of your Test.aspx.cs file.

Write a mode method in Java to find the most frequently occurring element in an array

I would use this code. It includes an instancesOf function, and it runs through each number.

public class MathFunctions {

public static int mode(final int[] n) {
    int maxKey = 0;
    int maxCounts = 0;

    for (int i : n) {
        if (instancesOf(i, n) > maxCounts) {
            maxCounts = instancesOf(i, n);
            maxKey = i;
        }
    }

    return maxKey;
}

public static int instancesOf(int n, int[] Array) {
    int occurences = 0;
    for (int j : Array) {
        occurences += j == n ? 1 : 0;
    }
    return occurences;
}

public static void main (String[] args) {
    //TODO Auto-generated method stub
    System.out.println(mode(new int[] {100,200,2,300,300,300,500}));
}
}

I noticed that the code Gubatron posted doesn't work on my computer; it gave me an ArrayIndexOutOfBoundsException.

Calling a class method raises a TypeError in Python

Every function inside a class, and every class variable must take the self argument as pointed.

class mystuff:
    def average(a,b,c): #get the average of three numbers
            result=a+b+c
            result=result/3
            return result
    def sum(self,a,b):
            return a+b


print mystuff.average(9,18,27) # should raise error
print mystuff.sum(18,27) # should be ok

If class variables are involved:

 class mystuff:
    def setVariables(self,a,b):
            self.x = a
            self.y = b
            return a+b
    def mult(self):
            return x * y  # This line will raise an error
    def sum(self):
            return self.x + self.y

 print mystuff.setVariables(9,18) # Setting mystuff.x and mystuff.y
 print mystuff.mult() # should raise error
 print mystuff.sum()  # should be ok

Accessing a class' member variables in Python?

Implement the return statement like the example below! You should be good. I hope it helps someone..

class Example(object):
    def the_example(self):
        itsProblem = "problem"
        return itsProblem 


theExample = Example()
print theExample.the_example()

Declaration of Methods should be Compatible with Parent Methods in PHP

Just to expand on this error in the context of an interface, if you are type hinting your function parameters like so:

interface A

use Bar;

interface A
{
    public function foo(Bar $b);
}

Class B

class B implements A
{
    public function foo(Bar $b);
}

If you have forgotten to include the use statement on your implementing class (Class B), then you will also get this error even though the method parameters are identical.

When is the finalize() method called in Java?

Try runiing this Program for better understanding

public class FinalizeTest 
{       
    static {
        System.out.println(Runtime.getRuntime().freeMemory());
    }

    public void run() {
        System.out.println("run");
        System.out.println(Runtime.getRuntime().freeMemory());
    }

     protected void finalize() throws Throwable { 
         System.out.println("finalize");
         while(true)
             break;          
     }

     public static void main(String[] args) {
            for (int i = 0 ; i < 500000 ; i++ ) {
                    new FinalizeTest().run();
            }
     }
}

Can there exist two main methods in a Java program?

enter image description here

Case :1 > We have two main method but with "Main" AND "main2" so jvm only a=calling "main" method .

2> Same method but diff params, still jvm calling "main(String[] args) " meyhod.

3> Exactly same method but it gives copile time error as you can not have two same name method in a single class !!!

Hope it will give you clear pic

What does the return keyword do in a void method in Java?

It functions the same as a return for function with a specified parameter, except it returns nothing, as there is nothing to return and control is passed back to the calling method.

What's a "static method" in C#?

The static keyword, when applied to a class, tells the compiler to create a single instance of that class. It is not then possible to 'new' one or more instance of the class. All methods in a static class must themselves be declared static.

It is possible, And often desirable, to have static methods of a non-static class. For example a factory method when creates an instance of another class is often declared static as this means that a particular instance of the class containing the factor method is not required.

For a good explanation of how, when and where see MSDN

How can I create a Java method that accepts a variable number of arguments?

You could write a convenience method:

public PrintStream print(String format, Object... arguments) {
    return System.out.format(format, arguments);
}

But as you can see, you've simply just renamed format (or printf).

Here's how you could use it:

private void printScores(Player... players) {
    for (int i = 0; i < players.length; ++i) {
        Player player = players[i];
        String name   = player.getName();
        int    score  = player.getScore();
        // Print name and score followed by a newline
        System.out.format("%s: %d%n", name, score);
    }
}

// Print a single player, 3 players, and all players
printScores(player1);
System.out.println();
printScores(player2, player3, player4);
System.out.println();
printScores(playersArray);

// Output
Abe: 11

Bob: 22
Cal: 33
Dan: 44

Abe: 11
Bob: 22
Cal: 33
Dan: 44

Note there's also the similar System.out.printf method that behaves the same way, but if you peek at the implementation, printf just calls format, so you might as well use format directly.

How to log as much information as possible for a Java Exception?

A logging script that I have written some time ago might be of help, although it is not exactly what you want. It acts in a way like a System.out.println but with much more information about StackTrace etc. It also provides Clickable text for Eclipse:

private static final SimpleDateFormat   extended    = new SimpleDateFormat( "dd MMM yyyy (HH:mm:ss) zz" );

public static java.util.logging.Logger initLogger(final String name) {
    final java.util.logging.Logger logger = java.util.logging.Logger.getLogger( name );
    try {

        Handler ch = new ConsoleHandler();
        logger.addHandler( ch );

        logger.setLevel( Level.ALL ); // Level selbst setzen

        logger.setUseParentHandlers( false );

        final java.util.logging.SimpleFormatter formatter = new SimpleFormatter() {

            @Override
            public synchronized String format(final LogRecord record) {
                StackTraceElement[] trace = new Throwable().getStackTrace();
                String clickable = "(" + trace[ 7 ].getFileName() + ":" + trace[ 7 ].getLineNumber() + ") ";
                /* Clickable text in Console. */

                for( int i = 8; i < trace.length; i++ ) {
                    /* 0 - 6 is the logging trace, 7 - x is the trace until log method was called */
                    if( trace[ i ].getFileName() == null )
                        continue;
                    clickable = "(" + trace[ i ].getFileName() + ":" + trace[ i ].getLineNumber() + ") -> " + clickable;
                }

                final String time = "<" + extended.format( new Date( record.getMillis() ) ) + "> ";

                StringBuilder level = new StringBuilder("[" + record.getLevel() + "] ");
                while( level.length() < 15 ) /* extend for tabby display */
                    level.append(" ");

                StringBuilder name = new StringBuilder(record.getLoggerName()).append(": ");
                while( name.length() < 15 ) /* extend for tabby display */
                    name.append(" ");

                String thread = Thread.currentThread().getName();
                if( thread.length() > 18 ) /* trim if too long */
                    thread = thread.substring( 0, 16 ) + "..."; 
                else {
                    StringBuilder sb = new StringBuilder(thread);
                    while( sb.length() < 18 ) /* extend for tabby display */
                        sb.append(" ");
                    thread = sb.insert( 0, "Thread " ).toString();
                }

                final String message = "\"" + record.getMessage() + "\" ";

                return level + time + thread + name + clickable + message + "\n";
            }
        };
        ch.setFormatter( formatter );
        ch.setLevel( Level.ALL );
    } catch( final SecurityException e ) {
        e.printStackTrace();
    }
    return logger;
}

Notice this outputs to the console, you can change that, see http://docs.oracle.com/javase/1.4.2/docs/api/java/util/logging/Logger.html for more information on that.

Now, the following will probably do what you want. It will go through all causes of a Throwable and save it in a String. Note that this does not use StringBuilder, so you can optimize by changing it.

Throwable e = ...
String detail = e.getClass().getName() + ": " + e.getMessage();
for( final StackTraceElement s : e.getStackTrace() )
    detail += "\n\t" + s.toString();
while( ( e = e.getCause() ) != null ) {
    detail += "\nCaused by: ";
    for( final StackTraceElement s : e.getStackTrace() )
        detail += "\n\t" + s.toString();
}

Regards,
Danyel

Method to get all files within folder and subfolders that will return a list

I am not sure of why you're adding the strings to files, which is declared as a field rather than a temporary variable. You could change the signature of DirSearch to:

private List<string> DirSearch(string sDir)

And, after the catch block, add:

return files;

Alternatively, you could create a temporary variable inside of your method and return it, which seems to me the approach you might desire. Otherwise, each time you call that method, the newly found strings will be added to the same list as before and you'll have duplicates.

Can two Java methods have same name with different return types?

According the JLS, you cannot however due to a feature/bug in the Java 6/7 compiler (Oracle's JDK, OpenJDK, IBM's JDK) you can have different return types for the same method signature if you use generics.

public class Main {
    public static void main(String... args) {
        Main.<Integer>print();
        Main.<Short>print();
        Main.<Byte>print();
        Main.<Void>print();
    }

    public static <T extends Integer> int print() {
        System.out.println("here - Integer");
        return 0;
    }
    public static <T extends Short> short print() {
        System.out.println("here - Short");
        return 0;
    }
    public static <T extends Byte> byte print() {
        System.out.println("here - Byte");
        return 0;
    }
    public static <T extends Void> void print() {
        System.out.println("here - Void");
    }
}

Prints

here - Integer
here - Short
here - Byte
here - Void

For more details, read my article here

'Class' does not contain a definition for 'Method'

If you are using a class from another project, the project needs to re-build and create re-the dll. Make sure "Build" is checked for that project on Build -> Configuration Manager in Visual Studio. So the reference project will re-build and update the dll.

Is Java "pass-by-reference" or "pass-by-value"?

You can never pass by reference in Java, and one of the ways that is obvious is when you want to return more than one value from a method call. Consider the following bit of code in C++:

void getValues(int& arg1, int& arg2) {
    arg1 = 1;
    arg2 = 2;
}
void caller() {
    int x;
    int y;
    getValues(x, y);
    cout << "Result: " << x << " " << y << endl;
}

Sometimes you want to use the same pattern in Java, but you can't; at least not directly. Instead you could do something like this:

void getValues(int[] arg1, int[] arg2) {
    arg1[0] = 1;
    arg2[0] = 2;
}
void caller() {
    int[] x = new int[1];
    int[] y = new int[1];
    getValues(x, y);
    System.out.println("Result: " + x[0] + " " + y[0]);
}

As was explained in previous answers, in Java you're passing a pointer to the array as a value into getValues. That is enough, because the method then modifies the array element, and by convention you're expecting element 0 to contain the return value. Obviously you can do this in other ways, such as structuring your code so this isn't necessary, or constructing a class that can contain the return value or allow it to be set. But the simple pattern available to you in C++ above is not available in Java.

python: how to get information about a function?

You can use pydoc.

Open your terminal and type python -m pydoc list.append

The advantage of pydoc over help() is that you do not have to import a module to look at its help text. For instance python -m pydoc random.randint.

Also you can start an HTTP server to interactively browse documentation by typing python -m pydoc -b (python 3)

For more information python -m pydoc

What does 'public static void' mean in Java?

It means three things.

First public means that any other object can access it.

static means that the class in which it resides doesn't have to be instantiated first before the function can be called.

void means that the function does not return a value.

Since you are just learning, don't worry about the first two too much until you learn about classes, and the third won't matter much until you start writing functions (other than main that is).

Best piece of advice I got when learning to program, and which I pass along to you, is don't worry about the little details you don't understand right away. Get a broad overview of the fundamentals, then go back and worry about the details. The reason is that you have to use some things (like public static void) in your first programs which can't really be explained well without teaching you about a bunch of other stuff first. So, for the moment, just accept that that's the way it's done, and move on. You will understand them shortly.

Why can't I call a public method in another class?

It sounds like you're not instantiating your class. That's the primary reason I get the "an object reference is required" error.

MyClass myClass = new MyClass();

once you've added that line you can then call your method

myClass.myMethod();

Also, are all of your classes in the same namespace? When I was first learning c# this was a common tripping point for me.

multiple conditions for JavaScript .includes() method

That can be done by using some/every methods of Array and RegEx.

To check whether ALL of words from list(array) are present in the string:

const multiSearchAnd = (text, searchWords) => (
  searchWords.every((el) => {
    return text.match(new RegExp(el,"i"))
  })
)

multiSearchAnd("Chelsey Dietrich Engineer 2018-12-11 Hire", ["cle", "hire"]) //returns false
multiSearchAnd("Chelsey Dietrich Engineer 2018-12-11 Hire", ["che", "hire"]) //returns true

To check whether ANY of words from list(array) are present in the string:

const multiSearchOr = (text, searchWords) => (
  searchWords.some((el) => {
    return text.match(new RegExp(el,"i"))
  })
)

multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["che", "hire"]) //returns true
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["aaa", "hire"]) //returns true
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["che", "zzzz"]) //returns true
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["aaa", "1111"]) //returns false

Difference between staticmethod and classmethod

@staticmethod just disables the default function as method descriptor. classmethod wraps your function in a container callable that passes a reference to the owning class as first argument:

>>> class C(object):
...  pass
... 
>>> def f():
...  pass
... 
>>> staticmethod(f).__get__(None, C)
<function f at 0x5c1cf0>
>>> classmethod(f).__get__(None, C)
<bound method type.f of <class '__main__.C'>>

As a matter of fact, classmethod has a runtime overhead but makes it possible to access the owning class. Alternatively I recommend using a metaclass and putting the class methods on that metaclass:

>>> class CMeta(type):
...  def foo(cls):
...   print cls
... 
>>> class C(object):
...  __metaclass__ = CMeta
... 
>>> C.foo()
<class '__main__.C'>

how to set default method argument values?

You can overload the method with different parameters:

public int doSomething(int arg1, int arg2)
{
//some logic here
        return 0;
}

public int doSomething(
{
doSomething(0,0)
}

Why does Python code use len() function instead of a length method?

Something missing from the rest of the answers here: the len function checks that the __len__ method returns a non-negative int. The fact that len is a function means that classes cannot override this behaviour to avoid the check. As such, len(obj) gives a level of safety that obj.len() cannot.

Example:

>>> class A:
...     def __len__(self):
...         return 'foo'
...
>>> len(A())
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    len(A())
TypeError: 'str' object cannot be interpreted as an integer
>>> class B:
...     def __len__(self):
...         return -1
... 
>>> len(B())
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    len(B())
ValueError: __len__() should return >= 0

Of course, it is possible to "override" the len function by reassigning it as a global variable, but code which does this is much more obviously suspicious than code which overrides a method in a class.

calling a function from class in python - different way

Your methods don't refer to an object (that is, self), so you should use the @staticmethod decorator:

class MathsOperations:
    @staticmethod
    def testAddition (x, y):
        return x + y

    @staticmethod
    def testMultiplication (a, b):
        return a * b

Java: Enum parameter in method

Sure, you could use an enum. Would something like the following work?

enum Alignment {
    LEFT,
    RIGHT
}

private static String drawCellValue(int maxCellLength, String cellValue, Alignment alignment) { }

If you wanted to use a boolean, you could rename the align parameter to something like alignLeft. I agree that this implementation is not as clean, but if you don't anticipate a lot of changes and this is not a public interface, it might be a good choice.

Compare two objects with .equals() and == operator

Here the output will be false , false beacuse in first sopln statement you are trying to compare a string type varible of Myclass type to the other MyClass type and it will allow because of both are Object type and you have used "==" oprerator which will check the reference variable value holding the actual memory not the actual contnets inside the memory . In the second sopln also it is the same as you are again calling a.equals(object2) where a is a varible inside object1 . Do let me know your findings on this .

method in class cannot be applied to given types

I think you want something like this. The formatting is off, but it should give the essential information you want.

   import java.util.Scanner;
public class BookstoreCredit 
{

   public static void computeDiscount(String name, double gpa) 
   {
      double credits;
      credits = gpa * 10;
      System.out.println(name + " your GPA is " +
         gpa + " so your credit is $" + credits);
   
   }

   public static void main (String args[]) 
   {
      String studentName;
      double gradeAverage;
      Scanner inputDevice = new Scanner(System.in);
      System.out.println("Enter Student name: ");
      studentName = inputDevice.nextLine();
      System.out.println("Enter student GPA: ");
      gradeAverage = inputDevice.nextDouble();  
      
      computeDiscount(studentName, gradeAverage);
   }
}

Purpose of a constructor in Java?

The class definition defines the API for your class. In other words, it is a blueprint that defines the contract that exists between the class and its clients--all the other code that uses this class. The contract indicates which methods are available, how to call them, and what to expect in return.

But the class definition is a spec. Until you have an actual object of this class, the contract is just "a piece of paper." This is where the constructor comes in.

A constructor is the means of creating an instance of your class by creating an object in memory and returning a reference to it. Something that should happen in the constructor is that the object is in a proper initial state for the subsequent operations on the object to make sense.

This object returned from the constructor will now honor the contract specified in the class definition, and you can use this object to do real work.

Think of it this way. If you ever look at the Porsche website, you will see what it can do--the horsepower, the torque, etc. But it isn't fun until you have an actual Porsche to drive.

Hope that helps.

How to get an object's methods?

the best way is:

let methods = Object.getOwnPropertyNames(yourobject);
console.log(methods)

use 'let' only in es6, use 'var' instead

Calling a function within a Class method?

  class sampleClass
    { 
        public function f1()
        {
           return "f1 run";
        }

        public function f2()
        {
           echo ("f2 run" );
           $result =  $this->f1();
           echo ($result);
        }   

    f2();  

    }

output :

f2 run f1 run

Usage of @see in JavaDoc?

I use @see to annotate methods of an interface implementation class where the description of the method is already provided in the javadoc of the interface. When we do that I notice that Eclipse pulls up the interface's documentation even when I am looking up method on the implementation reference during code complete

Python 3 string.join() equivalent?

There are method join for string objects:

".".join(("a","b","c"))

Why do some functions have underscores "__" before and after the function name?

Names surrounded by double underscores are "special" to Python. They're listed in the Python Language Reference, section 3, "Data model".

How to Exit a Method without Exiting the Program?

The basic problem here is that you are mistaking System.Environment.Exit for return.

HTTP Status 405 - Request method 'POST' not supported (Spring MVC)

The problem is that your controller expect a parameter hasId=false or hasId=true, but you are not passing that. Your hidden field has the id hasId but is passed as hasCustomerName, so no mapping matches.

Either change the path of the hidden field to hasId or the mapping parameter to expect hasCustomerName=true or hasCustomerName=false.

Count words in a string method?

There is a Simple Solution You can Try this code

    String s = "hju   vg    jhdgsf  dh gg    g g  g  ";

    String[] words = s.trim().split("\\s+");

    System.out.println("count is = "+(words.length));

Why can't I declare static methods in an interface?

Since static methods can not be inherited . So no use placing it in the interface. Interface is basically a contract which all its subscribers have to follow . Placing a static method in interface will force the subscribers to implement it . which now becomes contradictory to the fact that static methods can not be inherited .

PHP call Class method / function

Create object for the class and call, if you want to call it from other pages.

$obj = new Functions();

$var = $obj->filter($_GET['params']);

Or inside the same class instances [ methods ], try this.

$var = $this->filter($_GET['params']);

Passing null arguments to C# methods

I think the nearest C# equivalent to int* would be ref int?. Because ref int? allows the called method to pass a value back to the calling method.

int*

  • Can be null.
  • Can be non-null and point to an integer value.
  • If not null, value can be changed, and the change propagates to the caller.
  • Setting to null is not passed back to the caller.

ref int?

  • Can be null.
  • Can have an integer value.
  • Value can be always be changed, and the change propagates to the caller.
  • Value can be set to null, and this change will also propagate to the caller.

Python safe method to get value of nested dictionary

An adaptation of unutbu's answer that I found useful in my own code:

example_dict.setdefaut('key1', {}).get('key2')

It generates a dictionary entry for key1 if it does not have that key already so that you avoid the KeyError. If you want to end up a nested dictionary that includes that key pairing anyway like I did, this seems like the easiest solution.

How do I write a method to calculate total cost for all items in an array?

The total of 7 numbers in an array can be created as:

import java.util.*;
class Sum
{
   public static void main(String arg[])
   {
     int a[]=new int[7];
     int total=0;
     Scanner n=new Scanner(System.in);
     System.out.println("Enter the no. for total");

     for(int i=0;i<=6;i++) 
     {
       a[i]=n.nextInt();
       total=total+a[i];
      }
       System.out.println("The total is :"+total);
    }
}

Getting the name of the currently executing method

We used this code to mitigate potential variability in stack trace index - now just call methodName util:

public class MethodNameTest {
    private static final int CLIENT_CODE_STACK_INDEX;

    static {
        // Finds out the index of "this code" in the returned stack trace - funny but it differs in JDK 1.5 and 1.6
        int i = 0;
        for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
            i++;
            if (ste.getClassName().equals(MethodNameTest.class.getName())) {
                break;
            }
        }
        CLIENT_CODE_STACK_INDEX = i;
    }

    public static void main(String[] args) {
        System.out.println("methodName() = " + methodName());
        System.out.println("CLIENT_CODE_STACK_INDEX = " + CLIENT_CODE_STACK_INDEX);
    }

    public static String methodName() {
        return Thread.currentThread().getStackTrace()[CLIENT_CODE_STACK_INDEX].getMethodName();
    }
}

Seems overengineered, but we had some fixed number for JDK 1.5 and were a bit surprised it changed when we moved to JDK 1.6. Now it's the same in Java 6/7, but you just never know. It is not proof to changes in that index during runtime - but hopefully HotSpot doesn't do that bad. :-)

includes() not working in all browsers

If you look at the documentation of includes(), most of the browsers don't support this property.

You can use widely supported indexOf() after converting the property to string using toString():

if ($(".right-tree").css("background-image").indexOf("stage1") > -1) {
//                                           ^^^^^^^^^^^^^^^^^^^^^^

You can also use the polyfill from MDN.

if (!String.prototype.includes) {
    String.prototype.includes = function() {
        'use strict';
        return String.prototype.indexOf.apply(this, arguments) !== -1;
    };
}

Python calling method in class

Let's say you have a shiny Foo class. Well you have 3 options:

1) You want to use the method (or attribute) of a class inside the definition of that class:

class Foo(object):
    attribute1 = 1                   # class attribute (those don't use 'self' in declaration)
    def __init__(self):
        self.attribute2 = 2          # instance attribute (those are accessible via first
                                     # parameter of the method, usually called 'self'
                                     # which will contain nothing but the instance itself)
    def set_attribute3(self, value): 
        self.attribute3 = value

    def sum_1and2(self):
        return self.attribute1 + self.attribute2

2) You want to use the method (or attribute) of a class outside the definition of that class

def get_legendary_attribute1():
    return Foo.attribute1

def get_legendary_attribute2():
    return Foo.attribute2

def get_legendary_attribute1_from(cls):
    return cls.attribute1

get_legendary_attribute1()           # >>> 1
get_legendary_attribute2()           # >>> AttributeError: type object 'Foo' has no attribute 'attribute2'
get_legendary_attribute1_from(Foo)   # >>> 1

3) You want to use the method (or attribute) of an instantiated class:

f = Foo()
f.attribute1                         # >>> 1
f.attribute2                         # >>> 2
f.attribute3                         # >>> AttributeError: 'Foo' object has no attribute 'attribute3'
f.set_attribute3(3)
f.attribute3                         # >>> 3

Can overridden methods differ in return type?

Yes it may differ but there are some limitations.

Before Java 5.0, when you override a method, both parameters and return type must match exactly. Java 5.0 it introduces a new facility called covariant return type. You can override a method with the same signature but return a subclass of the object returned.

In another words, a method in a subclass can return an object whose type is a subclass of the type returned by the method with the same signature in the superclass.

How to return a boolean method in java?

You're allowed to have more than one return statement, so it's legal to write

if (some_condition) {
  return true;
}
return false;

It's also unnecessary to compare boolean values to true or false, so you can write

if (verifyPwd())  {
  // do_task
}

Edit: Sometimes you can't return early because there's more work to be done. In that case you can declare a boolean variable and set it appropriately inside the conditional blocks.

boolean success = true;

if (some_condition) {
  // Handle the condition.
  success = false;
} else if (some_other_condition) {
  // Handle the other condition.
  success = false;
}
if (another_condition) {
  // Handle the third condition.
}

// Do some more critical things.

return success;

Verify a method call using Moq

You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.

You should be doing something more like this:

class MyClassTest
{
    [TestMethod]
    public void MyMethodTest()
    {
        string action = "test";
        Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();

        mockSomeClass.Setup(mock => mock.DoSomething());

        MyClass myClass = new MyClass(mockSomeClass.Object);
        myClass.MyMethod(action);

        // Explicitly verify each expectation...
        mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());

        // ...or verify everything.
        // mockSomeClass.VerifyAll();
    }
}

In other words, you are verifying that calling MyClass#MyMethod, your class will definitely call SomeClass#DoSomething once in that process. Note that you don't need the Times argument; I was just demonstrating its value.

What is the difference between class and instance methods?

All the technical details have been nicely covered in the other answers. I just want to share a simple analogy that I think nicely illustrates the difference between a class and an instance:

enter image description here

A class is like the blueprint of a house: You only have one blueprint and (usually) you can't do that much with the blueprint alone.

enter image description here

An instance (or an object) is the actual house that you build based on the blueprint: You can build lots of houses from the same blueprint. You can then paint the walls a different color in each of the houses, just as you can independently change the properties of each instance of a class without affecting the other instances.

Passing a method as a parameter in Ruby

You have to call the method "call" of the function object:

weight = weightf.call( dist )

EDIT: as explained in the comments, this approach is wrong. It would work if you're using Procs instead of normal functions.

Abstract methods in Java

The error message tells the exact reason: "abstract methods cannot have a body".

They can only be defined in abstract classes and interfaces (interface methods are implicitly abstract!) and the idea is, that the subclass implements the method.

Example:

 public abstract class AbstractGreeter {
   public abstract String getHelloMessage();

   public void sayHello() {
     System.out.println(getHelloMessage());
   }
 }

 public class FrenchGreeter extends AbstractGreeter{

   // we must implement the abstract method
   @Override
   public String getHelloMessage() {
     return "bonjour";
   }
 }

How to get instance variables in Python?

You can also test if an object has a specific variable with:

>>> hi_obj = hi()
>>> hasattr(hi_obj, "some attribute")

Why doesn't Mockito mock static methods?

I think the reason may be that mock object libraries typically create mocks by dynamically creating classes at runtime (using cglib). This means they either implement an interface at runtime (that's what EasyMock does if I'm not mistaken), or they inherit from the class to mock (that's what Mockito does if I'm not mistaken). Both approaches do not work for static members, since you can't override them using inheritance.

The only way to mock statics is to modify a class' byte code at runtime, which I suppose is a little more involved than inheritance.

That's my guess at it, for what it's worth...

Can I get all methods of a class?

To know about all methods use this statement in console:

javap -cp jar-file.jar packagename.classname

or

javap class-file.class packagename.classname

or for example:

javap java.lang.StringBuffer

Adding a Method to an Existing Object Instance

Consolidating Jason Pratt's and the community wiki answers, with a look at the results of different methods of binding:

Especially note how adding the binding function as a class method works, but the referencing scope is incorrect.

#!/usr/bin/python -u
import types
import inspect

## dynamically adding methods to a unique instance of a class


# get a list of a class's method type attributes
def listattr(c):
    for m in [(n, v) for n, v in inspect.getmembers(c, inspect.ismethod) if isinstance(v,types.MethodType)]:
        print m[0], m[1]

# externally bind a function as a method of an instance of a class
def ADDMETHOD(c, method, name):
    c.__dict__[name] = types.MethodType(method, c)

class C():
    r = 10 # class attribute variable to test bound scope

    def __init__(self):
        pass

    #internally bind a function as a method of self's class -- note that this one has issues!
    def addmethod(self, method, name):
        self.__dict__[name] = types.MethodType( method, self.__class__ )

    # predfined function to compare with
    def f0(self, x):
        print 'f0\tx = %d\tr = %d' % ( x, self.r)

a = C() # created before modified instnace
b = C() # modified instnace


def f1(self, x): # bind internally
    print 'f1\tx = %d\tr = %d' % ( x, self.r )
def f2( self, x): # add to class instance's .__dict__ as method type
    print 'f2\tx = %d\tr = %d' % ( x, self.r )
def f3( self, x): # assign to class as method type
    print 'f3\tx = %d\tr = %d' % ( x, self.r )
def f4( self, x): # add to class instance's .__dict__ using a general function
    print 'f4\tx = %d\tr = %d' % ( x, self.r )


b.addmethod(f1, 'f1')
b.__dict__['f2'] = types.MethodType( f2, b)
b.f3 = types.MethodType( f3, b)
ADDMETHOD(b, f4, 'f4')


b.f0(0) # OUT: f0   x = 0   r = 10
b.f1(1) # OUT: f1   x = 1   r = 10
b.f2(2) # OUT: f2   x = 2   r = 10
b.f3(3) # OUT: f3   x = 3   r = 10
b.f4(4) # OUT: f4   x = 4   r = 10


k = 2
print 'changing b.r from {0} to {1}'.format(b.r, k)
b.r = k
print 'new b.r = {0}'.format(b.r)

b.f0(0) # OUT: f0   x = 0   r = 2
b.f1(1) # OUT: f1   x = 1   r = 10  !!!!!!!!!
b.f2(2) # OUT: f2   x = 2   r = 2
b.f3(3) # OUT: f3   x = 3   r = 2
b.f4(4) # OUT: f4   x = 4   r = 2

c = C() # created after modifying instance

# let's have a look at each instance's method type attributes
print '\nattributes of a:'
listattr(a)
# OUT:
# attributes of a:
# __init__ <bound method C.__init__ of <__main__.C instance at 0x000000000230FD88>>
# addmethod <bound method C.addmethod of <__main__.C instance at 0x000000000230FD88>>
# f0 <bound method C.f0 of <__main__.C instance at 0x000000000230FD88>>

print '\nattributes of b:'
listattr(b)
# OUT:
# attributes of b:
# __init__ <bound method C.__init__ of <__main__.C instance at 0x000000000230FE08>>
# addmethod <bound method C.addmethod of <__main__.C instance at 0x000000000230FE08>>
# f0 <bound method C.f0 of <__main__.C instance at 0x000000000230FE08>>
# f1 <bound method ?.f1 of <class __main__.C at 0x000000000237AB28>>
# f2 <bound method ?.f2 of <__main__.C instance at 0x000000000230FE08>>
# f3 <bound method ?.f3 of <__main__.C instance at 0x000000000230FE08>>
# f4 <bound method ?.f4 of <__main__.C instance at 0x000000000230FE08>>

print '\nattributes of c:'
listattr(c)
# OUT:
# attributes of c:
# __init__ <bound method C.__init__ of <__main__.C instance at 0x0000000002313108>>
# addmethod <bound method C.addmethod of <__main__.C instance at 0x0000000002313108>>
# f0 <bound method C.f0 of <__main__.C instance at 0x0000000002313108>>

Personally, I prefer the external ADDMETHOD function route, as it allows me to dynamically assign new method names within an iterator as well.

def y(self, x):
    pass
d = C()
for i in range(1,5):
    ADDMETHOD(d, y, 'f%d' % i)
print '\nattributes of d:'
listattr(d)
# OUT:
# attributes of d:
# __init__ <bound method C.__init__ of <__main__.C instance at 0x0000000002303508>>
# addmethod <bound method C.addmethod of <__main__.C instance at 0x0000000002303508>>
# f0 <bound method C.f0 of <__main__.C instance at 0x0000000002303508>>
# f1 <bound method ?.y of <__main__.C instance at 0x0000000002303508>>
# f2 <bound method ?.y of <__main__.C instance at 0x0000000002303508>>
# f3 <bound method ?.y of <__main__.C instance at 0x0000000002303508>>
# f4 <bound method ?.y of <__main__.C instance at 0x0000000002303508>>

How to call a method daily, at specific time, in C#?

If you want an executable to run, use Windows Scheduled Tasks. I'm going to assume (perhaps erroneously) that you want a method to run in your current program.

Why not just have a thread running continuously storing the last date that the method was called?

Have it wake up every minute (for example) and, if the current time is greater than the specified time and the last date stored is not the current date, call the method then update the date.

Python interpreter error, x takes no arguments (1 given)

Make sure, that all of your class methods (updateVelocity, updatePosition, ...) take at least one positional argument, which is canonically named self and refers to the current instance of the class.

When you call particle.updateVelocity(), the called method implicitly gets an argument: the instance, here particle as first parameter.

Method to find string inside of the text file. Then getting the following lines up to a certain limit

Here is a java 8 method to find a string in a text file:

for (String toFindUrl : urlsToTest) {
        streamService(toFindUrl);
    }

private void streamService(String item) {
        try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
           stream.filter(lines -> lines.contains(item))
                       .forEach(System.out::println);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Calling another method java GUI

I'm not sure what you're trying to do, but here's something to consider: c(); won't do anything. c is an instance of the class checkbox and not a method to be called. So consider this:

public class FirstWindow extends JFrame {      public FirstWindow() {         checkbox c = new checkbox();         c.yourMethod(yourParameters); // call the method you made in checkbox     } }  public class checkbox extends JFrame {      public checkbox(yourParameters) {          // this is the constructor method used to initialize instance variables     }      public void yourMethod() // doesn't have to be void     {         // put your code here     } } 

How to use a variable of one method in another method?

You can't. Variables defined inside a method are local to that method.

If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).


Looks like you're using instance methods instead of static ones.

If you don't want to create an object, you should declare all your methods static, so something like

private static void methodName(Argument args...)

If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.

private static int[][] array = new int[3][5];

Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.

Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.

Here's a final (shortened) example of what your code should be like:

public class Test3 {
    //Use this array in your methods
    private static int[][] scores = new int[3][5];

    /* Rather than just "Scores" name it so people know what
     * to expect
     */
    private static void createScores() {
        //Code...
    }
    //Other methods...

    /* Since you're now using static methods, you don't 
     * have to initialise an object and call its methods.
     */
    public static void main(String[] args){
        createScores();
        MD();   //Don't know what these do
        sumD(); //so I'll leave them.
    }
}

Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.

Android ListView with onClick items

listview.setOnItemClickListener(new OnItemClickListener(){

    @Override
    public void onItemClick(AdapterView<?>adapter,View v, int position){
    Intent intent;
    switch(position){
      case 0:
        intent = new Intent(Activity.this,firstActivity.class);
        break;
      case 1:
        intent = new Intent(Activity.this,secondActivity.class);
        break;
     case 2:
        intent = new Intent(Activity.this,thirdActivity.class);
        break;
    //add more if you have more items in listview
   //0 is the first item 1 second and so on...
    }
    startActivity(intent);
  }

});

How to call a parent method from child class in javascript?

ES6 style allows you to use new features, such as super keyword. super keyword it's all about parent class context, when you are using ES6 classes syntax. As a very simple example, checkout:

class Foo {
    static classMethod() {
        return 'hello';
    }
}

class Bar extends Foo {
    static classMethod() {
        return super.classMethod() + ', too';
    }
}
Bar.classMethod(); // 'hello, too'

Also, you can use super to call parent constructor:

class Foo {}

class Bar extends Foo {
    constructor(num) {
        let tmp = num * 2; // OK
        this.num = num; // ReferenceError
        super();
        this.num = num; // OK
    }
}

And of course you can use it to access parent class properties super.prop. So, use ES6 and be happy.

Python __call__ special method practical example

I find a good place to use callable objects, those that define __call__(), is when using the functional programming capabilities in Python, such as map(), filter(), reduce().

The best time to use a callable object over a plain function or a lambda function is when the logic is complex and needs to retain some state or uses other info that in not passed to the __call__() function.

Here's some code that filters file names based upon their filename extension using a callable object and filter().

Callable:

import os

class FileAcceptor(object):
    def __init__(self, accepted_extensions):
        self.accepted_extensions = accepted_extensions

    def __call__(self, filename):
        base, ext = os.path.splitext(filename)
        return ext in self.accepted_extensions

class ImageFileAcceptor(FileAcceptor):
    def __init__(self):
        image_extensions = ('.jpg', '.jpeg', '.gif', '.bmp')
        super(ImageFileAcceptor, self).__init__(image_extensions)

Usage:

filenames = [
    'me.jpg',
    'me.txt',
    'friend1.jpg',
    'friend2.bmp',
    'you.jpeg',
    'you.xml']

acceptor = ImageFileAcceptor()
image_filenames = filter(acceptor, filenames)
print image_filenames

Output:

['me.jpg', 'friend1.jpg', 'friend2.bmp', 'you.jpeg']

How to make method call another one in classes?

Because the Method2 is static, all you have to do is call like this:

public class AllMethods
{
    public static void Method2()
    {
        // code here
    }
}

class Caller
{
    public static void Main(string[] args)
    {
        AllMethods.Method2();
    }
}

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

public class MyClass
{
    public void InstanceMethod() 
    { 
        // ...
    }
}

public static void Main(string[] args)
{
    var instance = new MyClass();
    instance.InstanceMethod();
}

Update

As of C# 6, you can now also achieve this with using static directive to call static methods somewhat more gracefully, for example:

// AllMethods.cs
namespace Some.Namespace
{
    public class AllMethods
    {
        public static void Method2()
        {
            // code here
        }
    }
}

// Caller.cs
using static Some.Namespace.AllMethods;

namespace Other.Namespace
{
    class Caller
    {
        public static void Main(string[] args)
        {
            Method2(); // No need to mention AllMethods here
        }
    }
}

Further Reading

Why are exclamation marks used in Ruby methods?

! typically means that the method acts upon the object instead of returning a result. From the book Programming Ruby:

Methods that are "dangerous," or modify the receiver, might be named with a trailing "!".

How do I pass multiple parameters in Objective-C?

The text before each parameter is part of the method name. From your example, the name of the method is actually

-getBusStops:forTime:

Each : represents an argument. In a method call, the method name is split at the :s and arguments appear after the :s. e.g.

[getBusStops: arg1 forTime: arg2]

How to check whether an object has certain method/property?

To avoid AmbiguousMatchException, I would rather say

objectToCheck.GetType().GetMethods().Count(m => m.Name == method) > 0

calling another method from the main method in java

If you want to use do() in your main method there are 2 choices because one is static but other (do()) not

  1. Create new instance and invoke do() like new Foo().do();
  2. make static do() method

Have a look at this sun tutorial

How to call a method in another class of the same package?

You can either create a static method or use the other class as a member of your class calling the function in the constructor.

public class aClass {
      private SomeOtherClass oc;
      public class aClass( SomeOtherClass otherClass) {
         oc = otherClass;
      }

      public callOtherClassMethod() {
         oc.otherClassMethod();
       }
    }

Defining an abstract class without any abstract methods

Actually there is no mean if an abstract class doesnt have any abstract method . An abstract class is like a father. This father have some properties and behaviors,when you as a child want to be a child of the father, father says the child(you)that must be this way, its our MOTO, and if you don`t want to do, you are not my child.

Passing just a type as a parameter in C#

foo.GetColumnValues(dm.mainColumn, typeof(int));
foo.GetColumnValues(dm.mainColumn, typeof(string));

Or using generics:

foo.GetColumnValues<int>(dm.mainColumn);
foo.GetColumnValues<string>(dm.mainColumn);

Is arr.__len__() the preferred way to get the length of an array in Python?

Just use len(arr):

>>> import array
>>> arr = array.array('i')
>>> arr.append('2')
>>> arr.__len__()
1
>>> len(arr)
1

ReactJS - Call One Component Method From Another Component

You can do something like this

import React from 'react';

class Header extends React.Component {

constructor() {
    super();
}

checkClick(e, notyId) {
    alert(notyId);
}

render() {
    return (
        <PopupOver func ={this.checkClick } />
    )
}
};

class PopupOver extends React.Component {

constructor(props) {
    super(props);
    this.props.func(this, 1234);
}

render() {
    return (
        <div className="displayinline col-md-12 ">
            Hello
        </div>
    );
}
}

export default Header;

Using statics

var MyComponent = React.createClass({
 statics: {
 customMethod: function(foo) {
  return foo === 'bar';
  }
 },
   render: function() {
 }
});

MyComponent.customMethod('bar');  // true

How to find the minimum value of a column in R?

Since it is a numeric operation, we should be converting it to numeric form first. This operation cannot take place if the data is in factor data type.
Check the data type of the columns using str().

min(as.numeric(data[,2]))

How to auto-scroll to end of div when data is added?

var objDiv = document.getElementById("divExample");
objDiv.scrollTop = objDiv.scrollHeight;

Is there a function to copy an array in C/C++?

As others have mentioned, in C you would use memcpy. Note however that this does a raw memory copy, so if your data structures have pointer to themselves or to each other, the pointers in the copy will still point to the original objects.

In C++ you can also use memcpy if your array members are POD (that is, essentially types which you could also have used unchanged in C), but in general, memcpy will not be allowed. As others mentioned, the function to use is std::copy.

Having said that, in C++ you rarely should use raw arrays. Instead you should either use one of the standard containers (std::vector is the closest to a built-in array, and also I think the closest to Java arrays — closer than plain C++ arrays, indeed —, but std::deque or std::list may be more appropriate in some cases) or, if you use C++11, std::array which is very close to built-in arrays, but with value semantics like other C++ types. All the types I mentioned here can be copied by assignment or copy construction. Moreover, you can "cross-copy" from opne to another (and even from a built-in array) using iterator syntax.

This gives an overview of the possibilities (I assume all relevant headers have been included):

int main()
{
  // This works in C and C++
  int a[] = { 1, 2, 3, 4 };
  int b[4];
  memcpy(b, a, 4*sizeof(int)); // int is a POD

  // This is the preferred method to copy raw arrays in C++ and works with all types that can be copied:
  std::copy(a, a+4, b);

  // In C++11, you can also use this:
  std::copy(std::begin(a), std::end(a), std::begin(b));

  // use of vectors
  std::vector<int> va(a, a+4); // copies the content of a into the vector
  std::vector<int> vb = va;    // vb is a copy of va

  // this initialization is only valid in C++11:
  std::vector<int> vc { 5, 6, 7, 8 }; // note: no equal sign!

  // assign vc to vb (valid in all standardized versions of C++)
  vb = vc;

  //alternative assignment, works also if both container types are different
  vb.assign(vc.begin(), vc.end());

  std::vector<int> vd; // an *empty* vector

  // you also can use std::copy with vectors
  // Since vd is empty, we need a `back_inserter`, to create new elements:
  std::copy(va.begin(), va.end(), std::back_inserter(vd));

  // copy from array a to vector vd:
  // now vd already contains four elements, so this new copy doesn't need to
  // create elements, we just overwrite the existing ones.
  std::copy(a, a+4, vd.begin());

  // C++11 only: Define a `std::array`:
  std::array<int, 4> sa = { 9, 10, 11, 12 };

  // create a copy:
  std::array<int, 4> sb = sa;

  // assign the array:
  sb = sa;
}

VSCode single to double quote automatic replace

Correct solution :

I add .prettierrc.js file in my main root project and write

module.exports = {
    singleQuote: true
  };

unable to remove file that really exists - fatal: pathspec ... did not match any files

If your file idea/workspace.xml is added to .gitignore (or its parent folder) just add it manually to git version control. Also you can add it using TortoiseGit. After the next push you will see, that your problem is solved.

Add to git versioning using TortoiseGit

Accessing JSON object keys having spaces

The way to do this is via the bracket notation.

_x000D_
_x000D_
var test = {_x000D_
    "id": "109",_x000D_
    "No. of interfaces": "4"_x000D_
}_x000D_
alert(test["No. of interfaces"]);
_x000D_
_x000D_
_x000D_

For more info read out here:

What is the difference between res.end() and res.send()?

res is an HttpResponse object which extends from OutgoingMessage. res.send calls res.end which is implemented by OutgoingMessage to send HTTP response and close connection. We see code here

How to remove specific object from ArrayList in Java?

Here is full example. we have to use Iterator's remove() method

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayTest {
    int i;
    public static void main(String args[]) {
        ArrayList<ArrayTest> test = new ArrayList<ArrayTest>();
        ArrayTest obj;
        obj = new ArrayTest(1);
        test.add(obj);
        obj = new ArrayTest(2);
        test.add(obj);
        obj = new ArrayTest(3);
        test.add(obj);
        System.out.println("Before removing size is " + test.size() + " And Element are : " + test);
        Iterator<ArrayTest> itr = test.iterator();
        while (itr.hasNext()) {
            ArrayTest number = itr.next();
            if (number.i == 1) {
                itr.remove();
            }
        }
        System.out.println("After removing size is " + test.size() + " And Element are :" + test);
    }
    public ArrayTest(int i) {
        this.i = i;
    }
    @Override
    public String toString() {
        return "ArrayTest [i=" + i + "]";
    }

}

Working demo Screen

android: how to align image in the horizontal center of an imageview?

Your ImageView has the attribute wrap_content. I would think that the Image is centered inside the imageview but the imageview itself is not centered in the parentview. If you have only the imageview on the screen try match_parent instead of wrap_content. If you have more then one view in the layout you have to center the imageview.

Setting width/height as percentage minus pixels

Presuming 17px header height

List css:

height: 100%;
padding-top: 17px;

Header css:

height: 17px;
float: left;
width: 100%;

Strings and character with printf

If you want to display a single character then you can also use name[0] instead of using pointer.

It will serve your purpose but if you want to display full string using %c, you can try this:

#include<stdio.h>
void main()
{ 
    char name[]="siva";
    int i;
    for(i=0;i<4;i++)
    {
        printf("%c",*(name+i));
    }
} 

How to add some non-standard font to a website?

Safari and Internet Explorer both support the CSS @font-face rule, however they support two different embedded font types. Firefox is planning to support the same type as Apple some time soon. SVG can embed fonts but isn't that widely supported yet (without a plugin).

I think the most portable solution I've seen is to use a JavaScript function to replace headings etc. with an image generated and cached on the server with your font of choice -- that way you simply update the text and don't have to stuff around in Photoshop.

How to reset AUTO_INCREMENT in MySQL?

You can reset the counter with:

ALTER TABLE tablename AUTO_INCREMENT = 1

For InnoDB you cannot set the auto_increment value lower or equal to the highest current index. (quote from ViralPatel):

Note that you cannot reset the counter to a value less than or equal to any that have already been used. For MyISAM, if the value is less than or equal to the maximum value currently in the AUTO_INCREMENT column, the value is reset to the current maximum plus one. For InnoDB, if the value is less than the current maximum value in the column, no error occurs and the current sequence value is not changed.

See How to Reset an MySQL AutoIncrement using a MAX value from another table? on how to dynamically get an acceptable value.

How to hide element label by element id in CSS?

This is worked for me.

#_account_id{
        display: none;
    }
    label[for="_account_id"] { display: none !important; }

Rails 3 execute custom sql query without a model

Maybe try this:

ActiveRecord::Base.establish_connection(...)
ActiveRecord::Base.connection.execute(...)

How to display image from URL on Android

I've same issue. I test this code and works well. This code Get Image from URL and put in - "bmpImage"

URL url = new URL("http://your URL");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(60000 /* milliseconds */);
            conn.setConnectTimeout(65000 /* milliseconds */);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.connect();
            int response = conn.getResponseCode();
            //Log.d(TAG, "The response is: " + response);
            is = conn.getInputStream();


            BufferedInputStream bufferedInputStream = new BufferedInputStream(is);

            Bitmap bmpImage = BitmapFactory.decodeStream(bufferedInputStream);

Installing and Running MongoDB on OSX

For those that could be facing the same problem and the solutions suggested above aren't working, for example in my case, I had installed mongodb-community, so you might wanna run the command below to restart your mongo server.

For those that installed mongodb-community using brew

brew services start mongodb-community

How to copy a selection to the OS X clipboard

For MacVim and Windows Gvim, simply add the following to your ~/.vimrc:

set clipboard=unnamed

Now all operations such as yy, D, and P work with the clipboard. No need to prefix them with "* or "+.

Operand type clash: int is incompatible with date + The INSERT statement conflicted with the FOREIGN KEY constraint

I had the same problem. I tried 'yyyy-mm-dd' format i.e. '2013-26-11' and got rid of this problem...

How to set my default shell on Mac?

You can use chsh to change a user's shell.

Run the following code, for instance, to change your shell to Zsh

chsh -s /bin/zsh

As described in the manpage, and by Lorin, if the shell is not known by the OS, you have to add it to its known list: /etc/shells.

What do two question marks together mean in C#?

coalescing operator

it's equivalent to

FormsAuth = formsAUth == null ? new FormsAuthenticationWrapper() : formsAuth

php check if array contains all array values from another array

Look at array_intersect().

$containsSearch = count(array_intersect($search_this, $all)) == count($search_this);

What is the meaning of 'No bundle URL present' in react-native?

This problem may happen when we have multiple versions of node managed by nvm and default version is not intended version to run react-native. (make sure it is Node 8.3 or newer)

react-native run-ios

opens a new terminal and runs the version of node found in the $PATH.

If it finds an older version of node not supported by react native, it may give this error.

Make sure, the $PATH variable is already pointing to intended version of node(make sure it is Node 8.3 or newer) when a new terminal is opened.

That solved the issue for me. Good luck.

How do I enable C++11 in gcc?

H2CO3 is right, you can use a makefile with the CXXFLAGS set with -std=c++11 A makefile is a simple text file with instructions about how to compile your program. Create a new file named Makefile (with a capital M). To automatically compile your code just type the make command in a terminal. You may have to install make.

Here's a simple one :

CXX=clang++
CXXFLAGS=-g -std=c++11 -Wall -pedantic
BIN=prog

SRC=$(wildcard *.cpp)
OBJ=$(SRC:%.cpp=%.o)

all: $(OBJ)
    $(CXX) -o $(BIN) $^

%.o: %.c
    $(CXX) $@ -c $<

clean:
    rm -f *.o
    rm $(BIN)

It assumes that all the .cpp files are in the same directory as the makefile. But you can easily tweak your makefile to support a src, include and build directories.

Edit : I modified the default c++ compiler, my version of g++ isn't up-to-date. With clang++ this makefile works fine.

How to retrieve the dimensions of a view?

Simple Response: This worked for me with no Problem. It seems the key is to ensure that the View has focus before you getHeight etc. Do this by using the hasFocus() method, then using getHeight() method in that order. Just 3 lines of code required.

ImageButton myImageButton1 =(ImageButton)findViewById(R.id.imageButton1); myImageButton1.hasFocus();

int myButtonHeight = myImageButton1.getHeight();

Log.d("Button Height: ", ""+myButtonHeight );//Not required

Hope it helps.

Re-enabling window.alert in Chrome

I can see that this only for actually turning the dialogs back on. But if you are a web dev and you would like to see a way to possibly have some form of notification when these are off...in the case that you are using native alerts/confirms for validation or whatever. Check this solution to detect and notify the user https://stackoverflow.com/a/23697435/1248536

How to alert using jQuery

For each works with JQuery as in

$(<selector>).each(function() {
   //this points to item
   alert('<msg>');
});

JQuery also, for a popup, has in the UI library a dialog widget: http://jqueryui.com/demos/dialog/

Check it out, works really well.

HTH.

How to create own dynamic type or dynamic object in C#?

dynamic myDynamic = new { PropertyOne = true, PropertyTwo = false};

Convert char array to single int?

I use :

int convertToInt(char a[1000]){
    int i = 0;
    int num = 0;
    while (a[i] != 0)
    {
        num =  (a[i] - '0')  + (num * 10);
        i++;
    }
    return num;;
}

What does "atomic" mean in programming?

It's something that "appears to the rest of the system to occur instantaneously", and falls under categorisation of Linearizability in computing processes. To quote that linked article further:

Atomicity is a guarantee of isolation from concurrent processes. Additionally, atomic operations commonly have a succeed-or-fail definition — they either successfully change the state of the system, or have no apparent effect.

So, for instance, in the context of a database system, one can have 'atomic commits', meaning that you can push a changeset of updates to a relational database and those changes will either all be submitted, or none of them at all in the event of failure, in this way data does not become corrupt, and consequential of locks and/or queues, the next operation will be a different write or a read, but only after the fact. In the context of variables and threading this is much the same, applied to memory.

Your quote highlights that this need not be expected behaviour in all instances.

How do you remove a specific revision in the git history?

I also landed in a similar situation. Use interactive rebase using the command below and while selecting, drop 3rd commit.

git rebase -i remote/branch

Clear the entire history stack and start a new activity on Android

Try below code,

Intent intent = new Intent(ManageProfileActivity.this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|
                Intent.FLAG_ACTIVITY_CLEAR_TASK| 
                Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

Difference between agile and iterative and incremental development

Incremental development means that different parts of a software project are continuously integrated into the whole, instead of a monolithic approach where all the different parts are assembled in one or a few milestones of the project.

Iterative means that once a first version of a component is complete it is tested, reviewed and the results are almost immediately transformed into a new version (iteration) of this component.

So as a first result: iterative development doesn't need to be incremental and vice versa, but these methods are a good fit.

Agile development aims to reduce massive planing overhead in software projects to allow fast reactions to change e.g. in customer wishes. Incremental and iterative development are almost always part of an agile development strategy. There are several approaches to Agile development (e.g. scrum).

scp files from local to remote machine error: no such file or directory

Be sure the folder from where you send the file does not contain space !

I was trying to send a file to a remote server from my windows machine from VS code terminal, and I got this error even if the file was here.

It's because the folder where the file was contained space in its name...

Google Play Services Library update and missing symbol @integer/google_play_services_version

Google suggests you don't create a project directly from the SDK directory. It's better to copy the lib project out to the location where your app is, then import it from there. Otherwise the next time you go to import the project for another app, it will already be in use.

https://developer.android.com/google/play-services/setup.html

Note: You should be referencing a copy of the library that you copied to your development workspace—you should not reference the library directly from the Android SDK directory.

Running Java gives "Error: could not open `C:\Program Files\Java\jre6\lib\amd64\jvm.cfg'"

Had suddenly the same Problem, from one day to another eclipse said

Failed to load the JNI shared library "C:/JDK/bin/client/jvm.dll"`.

after trying to run java on the console

Error: could not open `C:\WINDOWS\jre\lib\amd64\jvm.cfg' 

now i just deleted the whole directory

C:\WINDOWS\jre

and everything worked again... i don't know there this jre came from, i hope it was not a virus

ECMAScript 6 arrow function that returns an object

You can always check this out for more custom solutions:

x => ({}[x.name] = x);

How can I post data as form data instead of a request payload?

var fd = new FormData();
    fd.append('file', file);
    $http.post(uploadUrl, fd, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    })
    .success(function(){
    })
    .error(function(){
    });

Please checkout! https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs

good postgresql client for windows?

I heartily recommended dbVis. The client runs on Mac, Windows and Linux and supports a variety of database servers, including PostgreSQL.

Labeling file upload button

You get your browser's language for your button. There's no way to change it programmatically.

How to get records randomly from the oracle database?

SAMPLE() is not guaranteed to give you exactly 20 rows, but might be suitable (and may perform significantly better than a full query + sort-by-random for large tables):

SELECT *
FROM   table SAMPLE(20);

Note: the 20 here is an approximate percentage, not the number of rows desired. In this case, since you have 100 rows, to get approximately 20 rows you ask for a 20% sample.

How to use Ajax.ActionLink?

Sure, a very similar question was asked before. Set the controller for ajax requests:

public ActionResult Show()
{
    if (Request.IsAjaxRequest()) 
    {
        return PartialView("Your_partial_view", new Model());
    }
    else 
    {
        return View();
    }
}

Set the action link as wanted:

@Ajax.ActionLink("Show", 
                 "Show", 
                 null, 
                 new AjaxOptions { HttpMethod = "GET", 
                 InsertionMode = InsertionMode.Replace, 
                 UpdateTargetId = "dialog_window_id", 
                 OnComplete = "your_js_function();" })

Note that I'm using Razor view engine, and that your AjaxOptions may vary depending on what you want. Finally display it on a modal window. The jQuery UI dialog is suggested.

Converting java.sql.Date to java.util.Date

This function will return a converted java date from SQL date object.

public static java.util.Date convertFromSQLDateToJAVADate(
            java.sql.Date sqlDate) {
        java.util.Date javaDate = null;
        if (sqlDate != null) {
            javaDate = new Date(sqlDate.getTime());
        }
        return javaDate;
    }

Replace first occurrence of pattern in a string

I think you can use the overload of Regex.Replace to specify the maximum number of times to replace...

var regex = new Regex(Regex.Escape("o"));
var newText = regex.Replace("Hello World", "Foo", 1);

Getting Error - ORA-01858: a non-numeric character was found where a numeric was expected

The error you are getting is either because you are doing TO_DATE on a column that's already a date, and you're using a format mask that is different to your nls_date_format parameter[1] or because the event_occurrence column contains data that isn't a number.

You need to a) correct your query so that it's not using TO_DATE on the date column, and b) correct your data, if event_occurrence is supposed to be just numbers.

And fix the datatype of that column to make sure you can only store numbers.



[1] What Oracle does when you do: TO_DATE(date_column, non_default_format_mask) is: TO_DATE(TO_CHAR(date_column, nls_date_format), non_default_format_mask)

Generally, the default nls_date_format parameter is set to dd-MON-yy, so in your query, what is likely to be happening is your date column is converted to a string in the format dd-MON-yy, and you're then turning it back to a date using the format MMDD. The string is not in this format, so you get an error.

How to read json file into java with simple JSON library

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class Delete_01 {
    public static void main(String[] args) throws FileNotFoundException,
            IOException, ParseException {

        JSONParser parser = new JSONParser();
        JSONArray jsonArray = (JSONArray) parser.parse(new FileReader(
                "delete_01.json"));

        for (Object o : jsonArray) {
            JSONObject person = (JSONObject) o;

            String strName = (String) person.get("name");
            System.out.println("Name::::" + strName);

            String strCity = (String) person.get("city");
            System.out.println("City::::" + strCity);

            JSONArray arrays = (JSONArray) person.get("cars");
            for (Object object : arrays) {
                System.out.println("cars::::" + object);
            }
            String strJob = (String) person.get("job");
            System.out.println("Job::::" + strJob);
            System.out.println();

        }

    }
}

Can someone give an example of cosine similarity, in a very simple, graphical way?

Two Vectors A and B exists in a 2D space or 3D space, the angle between those vectors is cos similarity.

If the angle is more (can reach max 180 degree) which is Cos 180=-1 and the minimum angle is 0 degree. cos 0 =1 implies the vectors are aligned to each other and hence the vectors are similar.

cos 90=0 (which is sufficient to conclude that the vectors A and B are not similar at all and since distance cant be negative, the cosine values will lie from 0 to 1. Hence, more angle implies implies reducing similarity (visualising also it makes sense)

Can't install laravel installer via composer

Centos 7 with PHP7.2:

sudo yum --enablerepo=remi-php72 install php-pecl-zip

How to read and write to a text file in C++?

To read you should create an instance of ifsteam and not ofstream.

ifstream iusrfile;

You should open the file in read mode.

iusrfile.open("usrfile.txt", ifstream::in);

Also this statement is not correct.

cout<<iusrfile;

If you are trying to print the data you read from the file you should do:

cout<<usr;

You can read more about ifstream and its API here

How do I move focus to next input with jQuery?

Use eq to get to specific element.

Documentation about index

_x000D_
_x000D_
$("input").keyup(function () {_x000D_
   var index = $(this).index("input");    _x000D_
   $("input:eq(" + (index +1) + ")").focus(); _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="text" maxlength="1"  />_x000D_
<input type="text" maxlength="1"  />_x000D_
_x000D_
<input type="text" maxlength="1"  />_x000D_
_x000D_
<input type="text" maxlength="1"  />_x000D_
<input type="text" maxlength="1"  />_x000D_
<input type="text" maxlength="1"  />
_x000D_
_x000D_
_x000D_

How do I fix a NoSuchMethodError?

I ran into a similar problem when I was changing method signatures in my application. Cleaning and rebuilding my project resolved the "NoSuchMethodError".

Binding an enum to a WinForms combo box, and then setting it

comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));

comboBox1.SelectedIndex = (int)MyEnum.Something;

comboBox1.SelectedIndex = Convert.ToInt32(MyEnum.Something);

Both of these work for me are you sure there isn't something else wrong?

How to wait for async method to complete?

Here is a workaround using a flag:

//outside your event or method, but inside your class
private bool IsExecuted = false;

private async Task MethodA()
{

//Do Stuff Here

IsExecuted = true;
}

.
.
.

//Inside your event or method

{
await MethodA();

while (!isExecuted) Thread.Sleep(200); // <-------

await MethodB();
}

Check whether a value is a number in JavaScript or jQuery

You've an number of options, depending on how you want to play it:

isNaN(val)

Returns true if val is not a number, false if it is. In your case, this is probably what you need.

isFinite(val)

Returns true if val, when cast to a String, is a number and it is not equal to +/- Infinity

/^\d+$/.test(val)

Returns true if val, when cast to a String, has only digits (probably not what you need).

Excel: Search for a list of strings within a particular string using array formulas?

This will return the matching word or an error if no match is found. For this example I used the following.

List of words to search for: G1:G7
Cell to search in: A1

=INDEX(G1:G7,MAX(IF(ISERROR(FIND(G1:G7,A1)),-1,1)*(ROW(G1:G7)-ROW(G1)+1)))

Enter as an array formula by pressing Ctrl+Shift+Enter.

This formula works by first looking through the list of words to find matches, then recording the position of the word in the list as a positive value if it is found or as a negative value if it is not found. The largest value from this array is the position of the found word in the list. If no word is found, a negative value is passed into the INDEX() function, throwing an error.

To return the row number of a matching word, you can use the following:

=MAX(IF(ISERROR(FIND(G1:G7,A1)),-1,1)*ROW(G1:G7))

This also must be entered as an array formula by pressing Ctrl+Shift+Enter. It will return -1 if no match is found.

Django - Did you forget to register or load this tag?

{% load static %}

Please add this template tag on top of the HTML or base HTML file

How to delete empty folders using windows command prompt?

for /f "usebackq" %%d in (`"dir /ad/b/s | sort /R"`) do rd "%%d"

from: http://blogs.msdn.com/b/oldnewthing/archive/2008/04/17/8399914.aspx

Of course I'd test it first without deleting before I do that command. Also, here's a modded version from the comments that includes folders with spaces:

 for /f "usebackq delims=" %%d in (`"dir /ad/b/s | sort /R"`) do rd "%%d"

P.S. there are more comments in the blog post that might help you out so be sure to read those too before you try this out

How do I get client IP address in ASP.NET CORE?

I found that, some of you found that the IP address you get is :::1 or 0.0.0.1

This is the problem because of you try to get IP from your own machine, and the confusion of C# that try to return IPv6.

So, I implement the answer from @Johna (https://stackoverflow.com/a/41335701/812720) and @David (https://stackoverflow.com/a/8597351/812720), Thanks to them!

and here to solution:

  1. add Microsoft.AspNetCore.HttpOverrides Package in your References (Dependencies/Packages)

  2. add this line in Startup.cs

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        // your current code
    
        // start code to add
        // to get ip address
        app.UseForwardedHeaders(new ForwardedHeadersOptions
        {
        ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
        });
        // end code to add
    
    }
    
  3. to get IPAddress, use this code in any of your Controller.cs

    IPAddress remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress;
    string result = "";
    if (remoteIpAddress != null)
    {
        // If we got an IPV6 address, then we need to ask the network for the IPV4 address 
        // This usually only happens when the browser is on the same machine as the server.
        if (remoteIpAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
        {
            remoteIpAddress = System.Net.Dns.GetHostEntry(remoteIpAddress).AddressList
    .First(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
        }
        result = remoteIpAddress.ToString();
    }
    

and now you can get IPv4 address from remoteIpAddress or result

How to get the Full file path from URI

Answer of @S.A.Parkhid on kotlin.

class FileUtils @Inject constructor(private val context: Context) {

    private var selection: String? = null
    private var selectionArgs: Array<String>? = null

    fun getFile(uri: Uri): File? {
        val path = getPath(uri)
        return if (path != null) {
            File(path)
        } else {
            null
        }
    }

    fun getPath(uri: Uri): String? {
        // check here to KITKAT or new version
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getPathForKitKatAndAbove(uri)
        } else {
            getPathBelowKitKat(uri)
        }
    }

    @SuppressLint("NewApi")
    private fun handleExternalStorage(uri: Uri): String? {
        val docId = DocumentsContract.getDocumentId(uri)
        val split = docId.split(":".toRegex()).toTypedArray()
        val fullPath = getPathFromExtSD(split)
        return if (fullPath !== "") {
            fullPath
        } else {
            null
        }
    }

    @SuppressLint("NewApi")
    private fun handleDownloads(uri: Uri): String? {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            handleDownloads23ApiAndAbove(uri)
        } else {
            handleDownloadsBelow23Api(uri)
        }
        return null
    }

    @SuppressLint("NewApi")
    private fun handleDownloadsBelow23Api(uri: Uri): String? {
        val id = DocumentsContract.getDocumentId(uri)
        if (id.startsWith("raw:")) {
            return id.replaceFirst("raw:".toRegex(), "")
        }
        var contentUri: Uri? = null
        try {
            contentUri = ContentUris.withAppendedId(
                Uri.parse("content://downloads/public_downloads"), id.toLong()
            )
        } catch (e: NumberFormatException) {
            log(e)
        }
        if (contentUri != null) {
            return getDataColumn(contentUri)
        }
        return null
    }

    @SuppressLint("NewApi")
    private fun handleDownloads23ApiAndAbove(uri: Uri): String? {
        var cursor: Cursor? = null
        try {
            cursor = context.contentResolver
                .query(uri, arrayOf(MediaStore.MediaColumns.DISPLAY_NAME), null, null, null)
            if (cursor != null && cursor.moveToFirst()) {
                val fileName = cursor.getString(0)
                val path: String =
                    Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName
                if (path.isNotEmpty()) {
                    return path
                }
            }
        } finally {
            cursor?.close()
        }
        val id: String = DocumentsContract.getDocumentId(uri)
        if (id.isNotEmpty()) {
            if (id.startsWith("raw:")) {
                return id.replaceFirst("raw:".toRegex(), "")
            }
            val contentUriPrefixesToTry = arrayOf(
                "content://downloads/public_downloads",
                "content://downloads/my_downloads"
            )
            for (contentUriPrefix in contentUriPrefixesToTry) {
                return try {
                    val contentUri = ContentUris.withAppendedId(
                        Uri.parse(contentUriPrefix),
                        id.toLong()
                    )
                    getDataColumn(contentUri)
                } catch (e: NumberFormatException) {
                    //In Android 8 and Android P the id is not a number
                    uri.path.orEmpty().replaceFirst("^/document/raw:".toRegex(), "")
                        .replaceFirst("^raw:".toRegex(), "")
                }
            }
        }
        return null
    }

    @SuppressLint("NewApi")
    private fun handleMedia(uri: Uri): String? {
        val docId = DocumentsContract.getDocumentId(uri)
        val split = docId.split(":".toRegex()).toTypedArray()
        val contentUri: Uri? = when (split[0]) {
            "image" -> {
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            }
            "video" -> {
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI
            }
            "audio" -> {
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
            }
            else -> null
        }
        selection = "_id=?"
        selectionArgs = arrayOf(split[1])
        return if (contentUri != null) {
            getDataColumn(contentUri)
        } else {
            null
        }
    }

    private fun handleContentScheme(uri: Uri): String? {
        if (isGooglePhotosUri(uri)) {
            return uri.lastPathSegment
        }
        if (isGoogleDriveUri(uri)) {
            return getDriveFilePath(uri)
        }
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            copyFileToInternalStorage(uri, "userfiles")
        } else {
            getDataColumn(uri)
        }
    }

    @SuppressLint("NewApi")
    private fun getPathForKitKatAndAbove(uri: Uri): String? {
        return when {
            // ExternalStorageProvider
            isExternalStorageDocument(uri) -> handleExternalStorage(uri)
            // DownloadsProvider
            isDownloadsDocument(uri) -> handleDownloads(uri)
            // MediaProvider
            isMediaDocument(uri) -> handleMedia(uri)
            //GoogleDriveProvider
            isGoogleDriveUri(uri) -> getDriveFilePath(uri)
            //WhatsAppProvider
            isWhatsAppFile(uri) -> getFilePathForWhatsApp(uri)
            //ContentScheme
            "content".equals(uri.scheme, ignoreCase = true) -> handleContentScheme(uri)
            //FileScheme
            "file".equals(uri.scheme, ignoreCase = true) -> uri.path
            else -> null
        }
    }

    private fun getPathBelowKitKat(uri: Uri): String? {
        if (isWhatsAppFile(uri)) {
            return getFilePathForWhatsApp(uri)
        }
        if ("content".equals(uri.scheme, ignoreCase = true)) {
            val projection = arrayOf(
                MediaStore.Images.Media.DATA
            )
            var cursor: Cursor? = null
            try {
                cursor = context.contentResolver
                    .query(uri, projection, selection, selectionArgs, null)
                val columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
                if (cursor.moveToFirst()) {
                    return cursor.getString(columnIndex)
                }
            } catch (e: IOException) {
                log(e)
            } finally {
                cursor?.close()
            }
        }
        return null
    }

    private fun fileExists(filePath: String): Boolean {
        val file = File(filePath)
        return file.exists()
    }

    private fun getPathFromExtSD(pathData: Array<String>): String {
        val type = pathData[0]
        val relativePath = "/" + pathData[1]
        var fullPath: String

        // on my Sony devices (4.4.4 & 5.1.1), `type` is a dynamic string
        // something like "71F8-2C0A", some kind of unique id per storage
        // don't know any API that can get the root path of that storage based on its id.
        //
        // so no "primary" type, but let the check here for other devices
        if ("primary".equals(type, ignoreCase = true)) {
            fullPath = Environment.getExternalStorageDirectory().toString() + relativePath
            if (fileExists(fullPath)) {
                return fullPath
            }
        }

        // Environment.isExternalStorageRemovable() is `true` for external and internal storage
        // so we cannot relay on it.
        //
        // instead, for each possible path, check if file exists
        // we'll start with secondary storage as this could be our (physically) removable sd card
        fullPath = System.getenv("SECONDARY_STORAGE").orEmpty() + relativePath
        if (fileExists(fullPath)) {
            return fullPath
        }
        fullPath = System.getenv("EXTERNAL_STORAGE").orEmpty() + relativePath
        return if (fileExists(fullPath)) {
            fullPath
        } else fullPath
    }

    private fun getDriveFilePath(uri: Uri): String? {
        context.contentResolver.query(
            uri, null, null, null, null
        )?.use { cursor ->
            /*
             * Get the column indexes of the data in the Cursor,
             *     * move to the first row in the Cursor, get the data,
             *     * and display it.
             * */
            val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
            cursor.moveToFirst()
            val name = cursor.getString(nameIndex)
            val file = File(context.cacheDir, name)
            try {
                val inputStream = context.contentResolver.openInputStream(uri)!!
                val outputStream = FileOutputStream(file)
                val bytesAvailable = inputStream.available()

                val bufferSize = min(bytesAvailable, MAX_BUFFER_SIZE)
                val buffers = ByteArray(bufferSize)
                var read: Int
                while (inputStream.read(buffers).also { read = it } != -1) {
                    outputStream.write(buffers, 0, read)
                }
                inputStream.close()
                outputStream.close()
            } catch (e: IOException) {
                log(e)
            } finally {
                cursor.close()
            }
            return file.path
        }
        return null
    }

    /***
     * Used for Android Q+
     * @param uri
     * @param newDirName if you want to create a directory, you can set this variable
     * @return
     */
    private fun copyFileToInternalStorage(uri: Uri, newDirName: String): String? {
        context.contentResolver.query(
            uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, null
        )?.use { cursor ->
            /*
             * Get the column indexes of the data in the Cursor,
             *     * move to the first row in the Cursor, get the data,
             *     * and display it.
             * */
            val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
            cursor.moveToFirst()
            val name = cursor.getString(nameIndex)
            val output: File = if (newDirName != "") {
                val dir = File(context.filesDir.toString() + "/" + newDirName)
                if (!dir.exists()) {
                    dir.mkdir()
                }
                File(context.filesDir.toString() + "/" + newDirName + "/" + name)
            } else {
                File(context.filesDir.toString() + "/" + name)
            }
            try {
                val inputStream = context.contentResolver.openInputStream(uri) ?: return null
                val outputStream = FileOutputStream(output)
                var read: Int
                val buffers = ByteArray(BUFFER_SIZE)
                while (inputStream.read(buffers).also { read = it } != -1) {
                    outputStream.write(buffers, 0, read)
                }
                inputStream.close()
                outputStream.close()
            } catch (e: IOException) {
                log(e)
            } finally {
                cursor.close()
            }
            return output.path
        }
        return null
    }

    private fun getFilePathForWhatsApp(uri: Uri): String? {
        return copyFileToInternalStorage(uri, "whatsapp")
    }

    private fun getDataColumn(uri: Uri): String? {
        var cursor: Cursor? = null
        val column = "_data"
        val projection = arrayOf(column)
        try {
            cursor = context.contentResolver.query(
                uri, projection,
                selection, selectionArgs, null
            )
            if (cursor != null && cursor.moveToFirst()) {
                val index = cursor.getColumnIndexOrThrow(column)
                return cursor.getString(index)
            }
        } finally {
            cursor?.close()
        }
        return null
    }

    private fun isExternalStorageDocument(uri: Uri): Boolean {
        return EXTERNAL_STORAGE_CONTENT == uri.authority
    }

    private fun isDownloadsDocument(uri: Uri): Boolean {
        return DOWNLOAD_DOCUMENT_CONTENT == uri.authority
    }

    private fun isMediaDocument(uri: Uri): Boolean {
        return MEDIA_DOCUMENT_CONTENT == uri.authority
    }

    private fun isGooglePhotosUri(uri: Uri): Boolean {
        return GOOGLE_PHOTOS_CONTENT == uri.authority
    }

    private fun isWhatsAppFile(uri: Uri): Boolean {
        return WHATS_APP_CONTENT == uri.authority
    }

    private fun isGoogleDriveUri(uri: Uri): Boolean {
        return GOOGLE_DRIVE_CONTENT == uri.authority || "com.google.android.apps.docs.storage.legacy" == uri.authority
    }

    companion object {
        private const val BUFFER_SIZE = 1024
        private const val MAX_BUFFER_SIZE = 1024 * 1024
        private const val GOOGLE_DRIVE_CONTENT = "com.google.android.apps.docs.storage"
        private const val WHATS_APP_CONTENT = "com.whatsapp.provider.media"
        private const val GOOGLE_PHOTOS_CONTENT = "com.google.android.apps.photos.content"
        private const val MEDIA_DOCUMENT_CONTENT = "com.android.providers.media.documents"
        private const val DOWNLOAD_DOCUMENT_CONTENT = "com.android.providers.downloads.documents"
        private const val EXTERNAL_STORAGE_CONTENT = "com.android.externalstorage.documents"
    }
}

Moving Panel in Visual Studio Code to right side

Click menu option View > Appearance > Move Side Bar Right or in settings.json:

"workbench.panel.defaultLocation": "right"

How do I get the application exit code from a Windows command line?

It's worth noting that .BAT and .CMD files operate differently.

Reading https://ss64.com/nt/errorlevel.html it notes the following:

There is a key difference between the way .CMD and .BAT batch files set errorlevels:

An old .BAT batch script running the 'new' internal commands: APPEND, ASSOC, PATH, PROMPT, FTYPE and SET will only set ERRORLEVEL if an error occurs. So if you have two commands in the batch script and the first fails, the ERRORLEVEL will remain set even after the second command succeeds.

This can make debugging a problem BAT script more difficult, a CMD batch script is more consistent and will set ERRORLEVEL after every command that you run [source].

This was causing me no end of grief as I was executing successive commands, but the ERRORLEVEL would remain unchanged even in the event of a failure.

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

some problem, but I find the solution, this is :


2 February Feb 28 (29 in leap years)

this is my code

 public string GetCountArchiveByMonth(int iii)
        {
// iii: is number of months, use any number other than (**2**)

            con.Open();

            SqlCommand cmd10 = con.CreateCommand();
            cmd10.CommandType = CommandType.Text;
            cmd10.CommandText = "select count(id_post) from posts where dateadded between CONVERT(VARCHAR, @start, 103) and CONVERT(VARCHAR, @end, 103)";
            cmd10.Parameters.AddWithValue("@start", "" + iii + "/01/2019");
            cmd10.Parameters.AddWithValue("@end", "" + iii + "/30/2019");
            string result = cmd10.ExecuteScalar().ToString();

            con.Close();

            return result;
        }

now for test

 lbl1.Text = GetCountArchiveByMonth(**7**).ToString();  // here use any number other than (**2**)

**

because of check **February** is maxed 28 days,

**

PHP: Limit foreach() statement?

In PHP 5.5+, you can do

function limit($iterable, $limit) {
    foreach ($iterable as $key => $value) {
        if (!$limit--) break;
        yield $key => $value;
    }
}

foreach (limit($arr, 10) as $key => $value) {
    // do stuff
}

Generators rock.

Popup window in PHP?

You'll have to use JS to open the popup, though you can put it on the page conditionally with PHP, you're right that you'll have to use a JavaScript function.

Remove Top Line of Text File with PowerShell

Another approach to remove the first line from file, using multiple assignment technique. Refer Link

 $firstLine, $restOfDocument = Get-Content -Path $filename 
 $modifiedContent = $restOfDocument 
 $modifiedContent | Out-String | Set-Content $filename

C# Listbox Item Double Click Event

This is very old post but if anyone ran into similar problem and need quick answer:

  • To capture if a ListBox item is clicked use MouseDown event.
  • To capture if an item is clicked rather than empty space in list box check if listBox1.IndexFromPoint(new Point(e.X,e.Y))>=0
  • To capture doubleclick event check if e.Clicks == 2

Angular 2 Scroll to bottom (Chat style)

const element = document.getElementById('box');
element.scrollIntoView({ behavior: 'smooth', block: 'end', inline: 'nearest' });

How to overwrite files with Copy-Item in PowerShell

How about calling the .NET Framework methods?

You can do ANYTHING with them... :

[System.IO.File]::Copy($src, $dest, $true);

The $true argument makes it overwrite.

VB.Net .Clear() or txtbox.Text = "" textbox clear methods

Clear() set the Text property to nothing. So txtbox1.Text = Nothing does the same thing as clear. An empty string (also available through String.Empty) is not a null reference, but has no value of course.

Eclipse+Maven src/main/java not visible in src folder in Package Explorer

I used this tutorial to create my maven web project http://crunchify.com/how-to-create-dynamic-web-project-using-maven-in-eclipse/ and eclipse did not create src/main/java folder for me. When i tired to create the source folder src/main/java eclipse did not let me. So i created the folder outside eclipse in the project directly and then src/main/java appeared in eclipse.

Avoid Adding duplicate elements to a List C#

If you want to save distinct values into a collection you could try HashSet Class. It will automatically remove the duplicate values and save your coding time. :)

Intel HAXM installation error - This computer does not support Intel Virtualization Technology (VT-x)

If any of the answers doesn't work just remove Android Emulator and reinstall it again. and after that try installing Intel Haxm.

What is an application binary interface (ABI)?

ABI - Application Binary Interface is about a machine code communication in runtime between two binary parts like - application, library, OS... ABI describes how objects are saved in memory, how functions are called(calling convention), mangling...

A good example of API and ABI is iOS ecosystem with Swift language.

  • Application layer - When you create an application using different languages. For example you can create application using Swift and Objective-C[Mixing Swift and Objective-C]

  • Application - OS layer - runtime - Swift runtime and standard libraries are parts of OS and they should not be included into each bundle(e.g. app, framework). It is the same as like Objective-C uses

  • Library layer - Module Stability case - compile time - you will be able to import a framework which was built with another version of Swift's compiler. It means that it is safety to create a closed-source(pre-build) binary which will be consumed by a different version of compiler( .swiftinterface is used with .swiftmodule) and you will not get

    Module compiled with _ cannot be imported by the _ compiler
    
  • Library layer - Library Evolution case

    1. Compile time - if a dependency was changed, a client has not to be recompiled.
    2. Runtime - a system library or a dynamic framework can be hot-swapped by a new one.

[API vs ABI]
[Swift Module and Library stability]

Bug? #1146 - Table 'xxx.xxxxx' doesn't exist

I had the same problem and can't get a good tip for this over the web, so I shared this for you and for all who needs.

In my situation I copy a database (all files: frm, myd) to the data folder in MySQL data folder (using Wamp at home). All thing was OK until I want to create a table and have the error #1146 Table '...' doesn't exist!.

I use Wamp 2.1 with MySQL version 5.5.16.

My solution:

  1. Export the database to file;

  2. verify if exported file is really OK!!;

  3. drop the database where I have issues;

  4. create a new database with the same name that the last;

  5. import the file to the database.

FOR ME IS PROBLEM SOLVED. Now I can create tables again without errors.

jQuery xml error ' No 'Access-Control-Allow-Origin' header is present on the requested resource.'

There's a kind of hack-tastic way to do it if you have php enabled on your server. Change this line:

url:   'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml',

to this line:

url: '/path/to/phpscript.php',

and then in the php script (if you have permission to use the file_get_contents() function):

<?php

header('Content-type: application/xml');
echo file_get_contents("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");

?>

Php doesn't seem to mind if that url is from a different origin. Like I said, this is a hacky answer, and I'm sure there's something wrong with it, but it works for me.

Edit: If you want to cache the result in php, here's the php file you would use:

<?php

$cacheName = 'somefile.xml.cache';
// generate the cache version if it doesn't exist or it's too old!
$ageInSeconds = 3600; // one hour
if(!file_exists($cacheName) || filemtime($cacheName) > time() + $ageInSeconds) {
  $contents = file_get_contents('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
  file_put_contents($cacheName, $contents);
}

$xml = simplexml_load_file($cacheName);

header('Content-type: application/xml');
echo $xml;

?>

Caching code take from here.

How do I join two SQLite tables in my Android application?

An alternate way is to construct a view which is then queried just like a table. In many database managers using a view can result in better performance.

CREATE VIEW xyz SELECT q.question, a.alternative  
   FROM tbl_question AS q, tbl_alternative AS a
  WHERE q.categoryid = a.categoryid 
    AND q._id = a.questionid;

This is from memory so there may be some syntactic issues. http://www.sqlite.org/lang_createview.html

I mention this approach because then you can use SQLiteQueryBuilder with the view as you implied that it was preferred.

Limit the output of the TOP command to a specific process name

I run it (eg.): top -b | egrep -w 'java|mysqld'

div inside table

While you can, as others have noted here, put a DIV inside a TD (not as a direct child of TABLE), I strongly advise against using a DIV as a child of a TD. Unless, of course, you're a fan of headaches.

There is little to be gained and a whole lot to be lost, as there are many cross-browser discrepancies regarding how widths, margins, borders, etc., are handled when you combine the two. I can't tell you how many times I've had to clean up that kind of markup for clients because they were having trouble getting their HTML to display correctly in this or that browser.

Then again, if you're not fussy about how things look, disregard this advice.

Unable to preventDefault inside passive event listener

I am getting this issue when using owl carousal and scrolling the images.

So get solved just adding below CSS in your page.

.owl-carousel {
-ms-touch-action: pan-y;
touch-action: pan-y;
}

or

.owl-carousel {
-ms-touch-action: none;
touch-action: none;
}

Locate Git installation folder on Mac OS X

On Mojave

The binary is in

/usr/bin/git

The related scripts are here

/Applications/Xcode.app/Contents/Developer/usr/libexec/git-core/git

Android add placeholder text to EditText

If you mean the location where you will add it in the layout. You can define a container like a FrameLayout and add this EditText to it when it is created.

<LinearLayout xmlns=".."/>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/container" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

FrameLayout layout = (FrameLayout) findViewById(R.id.container);
layout.addView(name);

How to download a file from a URL in C#?

Include this namespace

using System.Net;

Download Asynchronously and put a ProgressBar to show the status of the download within the UI Thread Itself

private void BtnDownload_Click(object sender, RoutedEventArgs e)
{
    using (WebClient wc = new WebClient())
    {
        wc.DownloadProgressChanged += wc_DownloadProgressChanged;
        wc.DownloadFileAsync (
            // Param1 = Link of file
            new System.Uri("http://www.sayka.com/downloads/front_view.jpg"),
            // Param2 = Path to save
            "D:\\Images\\front_view.jpg"
        );
    }
}
// Event to track the progress
void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    progressBar.Value = e.ProgressPercentage;
}

What's a good (free) visual merge tool for Git? (on windows)

  • TortoiseMerge (part of ToroiseSVN) is much better than kdiff3 (I use both and can compare);
  • p4merge (from Perforce) works also very well;
  • Diffuse isn't so bad;
  • Diffmerge from SourceGear has only one flaw in handling UTF8-files without BOM, making in unusable for this case.

MongoDB: How to find out if an array field contains an element?

I am trying to explain by putting problem statement and solution to it. I hope it will help

Problem Statement:

Find all the published products, whose name like ABC Product or PQR Product, and price should be less than 15/-

Solution:

Below are the conditions that need to be taken care of

  1. Product price should be less than 15
  2. Product name should be either ABC Product or PQR Product
  3. Product should be in published state.

Below is the statement that applies above criterion to create query and fetch data.

$elements = $collection->find(
             Array(
                [price] => Array( [$lt] => 15 ),
                [$or] => Array(
                            [0]=>Array(
                                    [product_name]=>Array(
                                       [$in]=>Array(
                                            [0] => ABC Product,
                                            [1]=> PQR Product
                                            )
                                        )
                                    )
                                ),
                [state]=>Published
                )
            );

How do I import an SQL file using the command line in MySQL?

-> Create a database in MySQL.

-> then go to your computer directory C:\xampp>mysql>bin . and write cmd on address bar, then hit enter.

-> Unzip your sql file

-> then wirte:- mysql -u root -p dbname, then press enter.

-> write:- source sql.file. Like Source C:\xampp\htdocs\amarbazarltd\st1159.sql Done

How to split one string into multiple variables in bash shell?

read with IFS are perfect for this:

$ IFS=- read var1 var2 <<< ABCDE-123456
$ echo "$var1"
ABCDE
$ echo "$var2"
123456

Edit:

Here is how you can read each individual character into array elements:

$ read -a foo <<<"$(echo "ABCDE-123456" | sed 's/./& /g')"

Dump the array:

$ declare -p foo
declare -a foo='([0]="A" [1]="B" [2]="C" [3]="D" [4]="E" [5]="-" [6]="1" [7]="2" [8]="3" [9]="4" [10]="5" [11]="6")'

If there are spaces in the string:

$ IFS=$'\v' read -a foo <<<"$(echo "ABCDE 123456" | sed 's/./&\v/g')"
$ declare -p foo
declare -a foo='([0]="A" [1]="B" [2]="C" [3]="D" [4]="E" [5]=" " [6]="1" [7]="2" [8]="3" [9]="4" [10]="5" [11]="6")'

Plot 3D data in R

I think the following code is close to what you want

x    <- c(0.1, 0.2, 0.3, 0.4, 0.5)
y    <- c(1, 2, 3, 4, 5)
zfun <- function(a,b) {a*b * ( 0.9 + 0.2*runif(a*b) )}
z    <- outer(x, y, FUN="zfun")

It gives data like this (note that x and y are both increasing)

> x
[1] 0.1 0.2 0.3 0.4 0.5
> y
[1] 1 2 3 4 5
> z
          [,1]      [,2]      [,3]      [,4]      [,5]
[1,] 0.1037159 0.2123455 0.3244514 0.4106079 0.4777380
[2,] 0.2144338 0.4109414 0.5586709 0.7623481 0.9683732
[3,] 0.3138063 0.6015035 0.8308649 1.2713930 1.5498939
[4,] 0.4023375 0.8500672 1.3052275 1.4541517 1.9398106
[5,] 0.5146506 1.0295172 1.5257186 2.1753611 2.5046223

and a graph like

persp(x, y, z)

persp(x, y, z)

Altering user-defined table types in SQL Server

If you can use a Database project in Visual Studio, you can make your changes in the project and use schema compare to synchronize the changes to your database.

This way, dropping and recreating the dependent objects is handled by the change script.

JQuery find first parent element with specific class prefix

Jquery later allowed you to to find the parents with the .parents() method.

Hence I recommend using:

var $div = $('#divid').parents('div[class^="div-a"]');

This gives all parent nodes matching the selector. To get the first parent matching the selector use:

var $div = $('#divid').parents('div[class^="div-a"]').eq(0);

For other such DOM traversal queries, check out the documentation on traversing the DOM.

Get SELECT's value and text in jQuery

You can do like this, to get the currently selected value:

$('#myDropdownID').val();

& to get the currently selected text:

$('#myDropdownID:selected').text();

List Git aliases

As of git 2.18 you can use git --list-cmds=alias

Image resizing in React Native

This worked for me:

image: {
    flex: 1,
    aspectRatio: 1.5, 
    resizeMode: 'contain',

  }

aspectRatio is just width/height (my image is 45px wide x 30px high).

"Unmappable character for encoding UTF-8" error

You have encoding problem with your sourcecode file. It is maybe ISO-8859-1 encoded, but the compiler was set to use UTF-8. This will results in errors when using characters, which will not have the same bytes representation in UTF-8 and ISO-8859-1. This will happen to all characters which are not part of ASCII, for example ¬ NOT SIGN.

You can simulate this with the following program. It just uses your line of source code and generates a ISO-8859-1 byte array and decode this "wrong" with UTF-8 encoding. You can see at which position the line gets corrupted. I added 2 spaces at your source code to fit position 74 to fit this to ¬ NOT SIGN, which is the only character, which will generate different bytes in ISO-8859-1 encoding and UTF-8 encoding. I guess this will match indentation with the real source file.

 String reg = "      String reg = \"^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[~#;:?/@&!\"'%*=¬.,-])(?=[^\\s]+$).{8,24}$\";";
 String corrupt=new String(reg.getBytes("ISO-8859-1"),"UTF-8");
 System.out.println(corrupt+": "+corrupt.charAt(74));
 System.out.println(reg+": "+reg.charAt(74));     

which results in the following output (messed up because of markup):

String reg = "^(?=.[0-9])(?=.[a-z])(?=.[A-Z])(?=.[~#;:?/@&!"'%*=?.,-])(?=[^\s]+$).{8,24}$";: ?

String reg = "^(?=.[0-9])(?=.[a-z])(?=.[A-Z])(?=.[~#;:?/@&!"'%*=¬.,-])(?=[^\s]+$).{8,24}$";: ¬

See "live" at https://ideone.com/ShZnB

To fix this, save the source files with UTF-8 encoding.

TypeError: method() takes 1 positional argument but 2 were given

Newcomer to Python, I had this issue when I was using the Python's ** feature in a wrong way. Trying to call this definition from somewhere:

def create_properties_frame(self, parent, **kwargs):

using a call without a double star was causing the problem:

self.create_properties_frame(frame, kw_gsp)

TypeError: create_properties_frame() takes 2 positional arguments but 3 were given

The solution is to add ** to the argument:

self.create_properties_frame(frame, **kw_gsp)

How to use Comparator in Java to sort

For the sake of completeness, here's a simple one-liner compare method:

Collections.sort(people, new Comparator<Person>() {
    @Override
    public int compare(Person lhs, Person rhs) {  
        return Integer.signum(lhs.getId() - rhs.getId());  
    }
});

Gson: Is there an easier way to serialize a map

Default

The default Gson implementation of Map serialization uses toString() on the key:

Gson gson = new GsonBuilder()
        .setPrettyPrinting().create();
Map<Point, String> original = new HashMap<>();
original.put(new Point(1, 2), "a");
original.put(new Point(3, 4), "b");
System.out.println(gson.toJson(original));

Will give:

{
  "java.awt.Point[x\u003d1,y\u003d2]": "a",
  "java.awt.Point[x\u003d3,y\u003d4]": "b"
}


Using enableComplexMapKeySerialization

If you want the Map Key to be serialized according to default Gson rules you can use enableComplexMapKeySerialization. This will return an array of arrays of key-value pairs:

Gson gson = new GsonBuilder().enableComplexMapKeySerialization()
        .setPrettyPrinting().create();
Map<Point, String> original = new HashMap<>();
original.put(new Point(1, 2), "a");
original.put(new Point(3, 4), "b");
System.out.println(gson.toJson(original));

Will return:

[
  [
    {
      "x": 1,
      "y": 2
    },
    "a"
  ],
  [
    {
      "x": 3,
      "y": 4
    },
    "b"
  ]
]

More details can be found here.

Reading Datetime value From Excel sheet

Reading Datetime value From Excel sheet : Try this will be work.

string sDate = (xlRange.Cells[4, 3] as Excel.Range).Value2.ToString();

double date = double.Parse(sDate);

var dateTime = DateTime.FromOADate(date).ToString("MMMM dd, yyyy");

How to remove all CSS classes using jQuery/JavaScript?

Just set the className attribute of the real DOM element to '' (nothing).

$('#item')[0].className = ''; // the real DOM element is at [0]

Edit: Other people have said that just calling removeClass works - I tested this with the Google JQuery Playground: http://savedbythegoog.appspot.com/?id=ag5zYXZlZGJ5dGhlZ29vZ3ISCxIJU2F2ZWRDb2RlGIS61gEM ... and it works. So you can also do it this way:

$("#item").removeClass();

What's the most concise way to read query parameters in AngularJS?

Just a precision to Ellis Whitehead's answer. $locationProvider.html5Mode(true); won't work with new version of angularjs without specifying the base URL for the application with a <base href=""> tag or setting the parameter requireBase to false

From the doc :

If you configure $location to use html5Mode (history.pushState), you need to specify the base URL for the application with a tag or configure $locationProvider to not require a base tag by passing a definition object with requireBase:false to $locationProvider.html5Mode():

$locationProvider.html5Mode({
  enabled: true,
  requireBase: false
});

Your project contains error(s), please fix it before running it

Well, in my case some libraries were addressed twice in the:

Project >> Properties >> Java Build Path >> Libraries

I just had to remove the duplicate and it worked fine without any cleanings or refreshing.

Splitting on last delimiter in Python string?

You can use rsplit

string.rsplit('delimeter',1)[1]

To get the string from reverse.

Java double comparison epsilon

Whoa whoa whoa. Is there a specific reason you're using floating-point for currency, or would things be better off with an arbitrary-precision, fixed-point number format? I have no idea what the specific problem that you're trying to solve is, but you should think about whether or not half a cent is really something you want to work with, or if it's just an artifact of using an imprecise number format.

How to do a Postgresql subquery in select clause with join in from clause like SQL Server?

I am just answering here with the formatted version of the final sql I needed based on Bob Jarvis answer as posted in my comment above:

select n1.name, n1.author_id, cast(count_1 as numeric)/total_count
  from (select id, name, author_id, count(1) as count_1
          from names
          group by id, name, author_id) n1
inner join (select author_id, count(1) as total_count
              from names
              group by author_id) n2
  on (n2.author_id = n1.author_id)

Why does range(start, end) not include end?

Consider the code

for i in range(10):
    print "You'll see this 10 times", i

The idea is that you get a list of length y-x, which you can (as you see above) iterate over.

Read up on the python docs for range - they consider for-loop iteration the primary usecase.

Can not run Java Applets in Internet Explorer 11 using JRE 7u51

This type of issue is cropping up again using the Windows 8 / IE 11 combination with the new version of Java (1.8.0_31). The installation seems to work, but after installing Java via the Java Control Panel Update tab, every time you run a Java applet you are told your version of Java is outdated, but when you follow the prompts to again update, you are told your version of Java is newer than the one on the web.

As with a previous iteration of such problems, what worked for me was, after installation, unchecking "Internet Options | Security | Enable Protected Mode", running a Java applet and then re-checking it and everything is fine.

Do people at Oracle not test on Windows 8 with IE or does this only happen for people with particular extensions enabled?

As before, this problem didn't happen on Windows 7, but there I noticed that the SSLv3 changes now prevent you from running a local applet in Internet Explorer unless you remove that line from the java.security file. But this problem doesn't happen on Windows 8, so it is not clear what is actually happening.

If Oracle doesn't make the update process less rocky, people won't update. I've seen many people lately using 2009 versions of JRE 1.6. That is the sort of situation that often doesn't end well.

How to exclude rows that don't join with another table?

If you want to select the columns from First Table "which are also present in Second table, then in this case you can also use EXCEPT. In this case, column names can be different as well but data type should be same.

Example:

select ID, FName
from FirstTable
EXCEPT
select ID, SName
from SecondTable

Jquery checking success of ajax post

If you need a failure function, you can't use the $.get or $.post functions; you will need to call the $.ajax function directly. You pass an options object that can have "success" and "error" callbacks.

Instead of this:

$.post("/post/url.php", parameters, successFunction);

you would use this:

$.ajax({
    url: "/post/url.php",
    type: "POST",
    data: parameters,
    success: successFunction,
    error: errorFunction
});

There are lots of other options available too. The documentation lists all the options available.

Adding Access-Control-Allow-Origin header response in Laravel 5.3 Passport

If you've applied the CORS middleware and it's still not working, try this.

If the route for your API is:

Route::post("foo", "MyController"})->middleware("cors");

Then you need to change it to allow for the OPTIONS method:

Route::match(['post', 'options'], "foo", "MyController")->middleware("cors");

extracting days from a numpy.timedelta64 value

You can convert it to a timedelta with a day precision. To extract the integer value of days you divide it with a timedelta of one day.

>>> x = np.timedelta64(2069211000000000, 'ns')
>>> days = x.astype('timedelta64[D]')
>>> days / np.timedelta64(1, 'D')
23

Or, as @PhillipCloud suggested, just days.astype(int) since the timedelta is just a 64bit integer that is interpreted in various ways depending on the second parameter you passed in ('D', 'ns', ...).

You can find more about it here.

How to replace blank (null ) values with 0 for all records?

Better solution is to use NZ (null to zero) function during generating table => NZ([ColumnName]) It comes 0 where is "null" in ColumnName.

Why does an SSH remote command get fewer environment variables then when run manually?

There are different types of shells. The SSH command execution shell is a non-interactive shell, whereas your normal shell is either a login shell or an interactive shell. Description follows, from man bash:

       A  login  shell  is  one whose first character of argument
       zero is a -, or one started with the --login option.

       An interactive shell is  one  started  without  non-option
       arguments  and  without the -c option whose standard input
       and error are both connected to terminals  (as  determined
       by  isatty(3)), or one started with the -i option.  PS1 is
       set and $- includes i if bash is interactive,  allowing  a
       shell script or a startup file to test this state.

       The  following  paragraphs  describe how bash executes its
       startup files.  If any of the files exist  but  cannot  be
       read,  bash reports an error.  Tildes are expanded in file
       names as described below  under  Tilde  Expansion  in  the
       EXPANSION section.

       When  bash is invoked as an interactive login shell, or as
       a non-interactive shell with the --login option, it  first
       reads and executes commands from the file /etc/profile, if
       that file exists.  After reading that file, it  looks  for
       ~/.bash_profile,  ~/.bash_login,  and  ~/.profile, in that
       order, and reads and executes commands from the first  one
       that  exists  and is readable.  The --noprofile option may
       be used when the shell is started to inhibit  this  behav­
       ior.

       When a login shell exits, bash reads and executes commands
       from the file ~/.bash_logout, if it exists.

       When an interactive shell that is not  a  login  shell  is
       started,  bash reads and executes commands from ~/.bashrc,
       if that file exists.  This may be inhibited by  using  the
       --norc  option.   The --rcfile file option will force bash
       to  read  and  execute  commands  from  file  instead   of
       ~/.bashrc.

       When  bash  is  started  non-interactively, to run a shell
       script, for example, it looks for the variable BASH_ENV in
       the  environment,  expands  its value if it appears there,
       and uses the expanded value as the name of a file to  read
       and  execute.   Bash  behaves  as if the following command
       were executed:
              if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi
       but the value of the PATH variable is not used  to  search
       for the file name.

How do I access an access array item by index in handlebars?

Try this:

<ul id="luke_should_be_here">
{{people.1.name}}
</ul>

Named tuple and default values for optional keyword arguments

Using the NamedTuple class from my Advanced Enum (aenum) library, and using the class syntax, this is quite simple:

from aenum import NamedTuple

class Node(NamedTuple):
    val = 0
    left = 1, 'previous Node', None
    right = 2, 'next Node', None

The one potential drawback is the requirement for a __doc__ string for any attribute with a default value (it's optional for simple attributes). In use it looks like:

>>> Node()
Traceback (most recent call last):
  ...
TypeError: values not provided for field(s): val

>>> Node(3)
Node(val=3, left=None, right=None)

The advantages this has over justinfay's answer:

from collections import namedtuple

class Node(namedtuple('Node', ['value', 'left', 'right'])):
    __slots__ = ()
    def __new__(cls, value, left=None, right=None):
        return super(Node, cls).__new__(cls, value, left, right)

is simplicity, as well as being metaclass based instead of exec based.

Function to calculate distance between two coordinates

Calculate the Distance between Two Points in javascript

function distance(lat1, lon1, lat2, lon2, unit) {
        var radlat1 = Math.PI * lat1/180
        var radlat2 = Math.PI * lat2/180
        var theta = lon1-lon2
        var radtheta = Math.PI * theta/180
        var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
        dist = Math.acos(dist)
        dist = dist * 180/Math.PI
        dist = dist * 60 * 1.1515
        if (unit=="K") { dist = dist * 1.609344 }
        if (unit=="N") { dist = dist * 0.8684 }
        return dist
}

For more details refer this: Reference Link

Query to get only numbers from a string

This UDF will work for all types of strings:

CREATE FUNCTION udf_getNumbersFromString (@string varchar(max))
RETURNS varchar(max)
AS
BEGIN
    WHILE  @String like '%[^0-9]%'
    SET    @String = REPLACE(@String, SUBSTRING(@String, PATINDEX('%[^0-9]%', @String), 1), '')
    RETURN @String
END

Set textarea width to 100% in bootstrap modal

If i understand right this is what your looking for.

.form-control { width: 100%; }

See demo on JSFiddle.

Signed versus Unsigned Integers

Everything except for point 2 is correct. There are many different notations for signed ints, some implementations use the first, others use the last and yet others use something completely different. That all depends on the platform you're working with.

Creating a folder if it does not exists - "Item already exists"

With New-Item you can add the Force parameter

New-Item -Force -ItemType directory -Path foo

Or the ErrorAction parameter

New-Item -ErrorAction Ignore -ItemType directory -Path foo

passing object by reference in C++

What seems to be confusing you is the fact that functions that are declared to be pass-by-reference (using the &) aren't called using actual addresses, i.e. &a.

The simple answer is that declaring a function as pass-by-reference:

void foo(int& x);

is all we need. It's then passed by reference automatically.

You now call this function like so:

int y = 5;
foo(y);

and y will be passed by reference.

You could also do it like this (but why would you? The mantra is: Use references when possible, pointers when needed) :

#include <iostream>
using namespace std;

class CDummy {
public:
    int isitme (CDummy* param);
};


int CDummy::isitme (CDummy* param)
{
    if (param == this) return true;
    else return false;
}

int main () {
    CDummy a;
    CDummy* b = &a;             // assigning address of a to b
    if ( b->isitme(&a) )        // Called with &a (address of a) instead of a
        cout << "yes, &a is b";
    return 0;
}

Output:

yes, &a is b

Strip spaces/tabs/newlines - python

Use the re library

import re
myString = "I want to Remove all white \t spaces, new lines \n and tabs \t"
myString = re.sub(r"[\n\t\s]*", "", myString)
print myString

Output:

IwanttoRemoveallwhitespaces,newlinesandtabs

How can I print using JQuery

Try like

$('.printMe').click(function(){
     window.print();
});

or if you want to print selected area try like

$('.printMe').click(function(){
     $("#outprint").print();
});

How to read and write excel file

If you go for third party library option, try using Aspose.Cells API that enables Java Applications to create (read/write) and manage Excel spreadsheets efficiently without requiring Microsoft Excel.

e.g

Sample code:

1.

//Load sample workbook
Workbook wb = new Workbook(dirPath + "sample.xlsx");

//Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);

//Access cells iterator
Iterator itrat = ws.getCells().iterator();

//Print cells name in iterator
while(itrat.hasNext())
{
    Cell cell = (Cell)itrat.next();

    System.out.println(cell.getName() + ": " + cell.getStringValue().trim());
}
Workbook book = new Workbook("sample.xlsx");
Worksheet sheet = book.getWorksheets().get(0);
Range range = sheet.getCells().getMaxDisplayRange();//You may also create your desired range (in the worksheet) using, e.g sheet.getCells().createRange("A1", "J11");
Iterator rangeIterator = range.iterator();
while(rangeIterator.hasNext())
{
Cell cell = (Cell)rangeIterator.next();
//your code goes here.
}

Hope, this helps a bit.

PS. I am working as Support developer/ Evangelist at Aspose.

Concatenating elements in an array to a string

take a look at generic method to print all elements in an array

but in short, the Arrays.toString(arr) is just a easy way of printing the content of a primative array.

How to read keyboard-input?

Non-blocking, multi-threaded example:

As blocking on keyboard input (since the input() function blocks) is frequently not what we want to do (we'd frequently like to keep doing other stuff), here's a very-stripped-down multi-threaded example to demonstrate how to keep running your main application while still reading in keyboard inputs whenever they arrive.

This works by creating one thread to run in the background, continually calling input() and then passing any data it receives to a queue.

In this way, your main thread is left to do anything it wants, receiving the keyboard input data from the first thread whenever there is something in the queue.

1. Bare Python 3 code example (no comments):

import threading
import queue
import time

def read_kbd_input(inputQueue):
    print('Ready for keyboard input:')
    while (True):
        input_str = input()
        inputQueue.put(input_str)

def main():
    EXIT_COMMAND = "exit"
    inputQueue = queue.Queue()

    inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True)
    inputThread.start()

    while (True):
        if (inputQueue.qsize() > 0):
            input_str = inputQueue.get()
            print("input_str = {}".format(input_str))

            if (input_str == EXIT_COMMAND):
                print("Exiting serial terminal.")
                break
            
            # Insert your code here to do whatever you want with the input_str.

        # The rest of your program goes here.

        time.sleep(0.01) 
    print("End.")

if (__name__ == '__main__'): 
    main()

2. Same Python 3 code as above, but with extensive explanatory comments:

"""
read_keyboard_input.py

Gabriel Staples
www.ElectricRCAircraftGuy.com
14 Nov. 2018

References:
- https://pyserial.readthedocs.io/en/latest/pyserial_api.html
- *****https://www.tutorialspoint.com/python/python_multithreading.htm
- *****https://en.wikibooks.org/wiki/Python_Programming/Threading
- https://stackoverflow.com/questions/1607612/python-how-do-i-make-a-subclass-from-a-superclass
- https://docs.python.org/3/library/queue.html
- https://docs.python.org/3.7/library/threading.html

To install PySerial: `sudo python3 -m pip install pyserial`

To run this program: `python3 this_filename.py`

"""

import threading
import queue
import time

def read_kbd_input(inputQueue):
    print('Ready for keyboard input:')
    while (True):
        # Receive keyboard input from user.
        input_str = input()
        
        # Enqueue this input string.
        # Note: Lock not required here since we are only calling a single Queue method, not a sequence of them 
        # which would otherwise need to be treated as one atomic operation.
        inputQueue.put(input_str)

def main():

    EXIT_COMMAND = "exit" # Command to exit this program

    # The following threading lock is required only if you need to enforce atomic access to a chunk of multiple queue
    # method calls in a row.  Use this if you have such a need, as follows:
    # 1. Pass queueLock as an input parameter to whichever function requires it.
    # 2. Call queueLock.acquire() to obtain the lock.
    # 3. Do your series of queue calls which need to be treated as one big atomic operation, such as calling
    # inputQueue.qsize(), followed by inputQueue.put(), for example.
    # 4. Call queueLock.release() to release the lock.
    # queueLock = threading.Lock() 

    #Keyboard input queue to pass data from the thread reading the keyboard inputs to the main thread.
    inputQueue = queue.Queue()

    # Create & start a thread to read keyboard inputs.
    # Set daemon to True to auto-kill this thread when all other non-daemonic threads are exited. This is desired since
    # this thread has no cleanup to do, which would otherwise require a more graceful approach to clean up then exit.
    inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True)
    inputThread.start()

    # Main loop
    while (True):

        # Read keyboard inputs
        # Note: if this queue were being read in multiple places we would need to use the queueLock above to ensure
        # multi-method-call atomic access. Since this is the only place we are removing from the queue, however, in this
        # example program, no locks are required.
        if (inputQueue.qsize() > 0):
            input_str = inputQueue.get()
            print("input_str = {}".format(input_str))

            if (input_str == EXIT_COMMAND):
                print("Exiting serial terminal.")
                break # exit the while loop
            
            # Insert your code here to do whatever you want with the input_str.

        # The rest of your program goes here.

        # Sleep for a short time to prevent this thread from sucking up all of your CPU resources on your PC.
        time.sleep(0.01) 
    
    print("End.")

# If you run this Python file directly (ex: via `python3 this_filename.py`), do the following:
if (__name__ == '__main__'): 
    main()

Sample output:

$ python3 read_keyboard_input.py
Ready for keyboard input:
hey
input_str = hey
hello
input_str = hello
7000
input_str = 7000
exit
input_str = exit
Exiting serial terminal.
End.

The Python Queue library is thread-safe:

Note that Queue.put() and Queue.get() and other Queue class methods are thread-safe! That means they implement all the internal locking semantics required for inter-thread operations, so each function call in the queue class can be considered as a single, atomic operation. See the notes at the top of the documentation: https://docs.python.org/3/library/queue.html (emphasis added):

The queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics.

References:

  1. https://pyserial.readthedocs.io/en/latest/pyserial_api.html
  2. *****https://www.tutorialspoint.com/python/python_multithreading.htm
  3. *****https://en.wikibooks.org/wiki/Python_Programming/Threading
  4. Python: How do I make a subclass from a superclass?
  5. https://docs.python.org/3/library/queue.html
  6. https://docs.python.org/3.7/library/threading.html

Related/Cross-Linked:

  1. PySerial non-blocking read loop

NameError: uninitialized constant (rails)

I was getting the error:

NameError: uninitialized constant

Then I noticed that I had accidentally created a plural model so I went back and renamed the model file to singular and also changed the class name in the model file to singular and that solved it.

how to get yesterday's date in C#

string result = DateTime.Now.Date.AddDays(-1).ToString("yyyy-MM-dd");

How to connect to a remote Git repository?

To me it sounds like the simplest way to expose your git repository on the server (which seems to be a Windows machine) would be to share it as a network resource.

Right click the folder "MY_GIT_REPOSITORY" and select "Sharing". This will give you the ability to share your git repository as a network resource on your local network. Make sure you give the correct users the ability to write to that share (will be needed when you and your co-workers push to the repository).

The URL for the remote that you want to configure would probably end up looking something like file://\\\\189.14.666.666\MY_GIT_REPOSITORY

If you wish to use any other protocol (e.g. HTTP, SSH) you'll have to install additional server software that includes servers for these protocols. In lieu of these the file sharing method is probably the easiest in your case right now.

What is the difference between Scope_Identity(), Identity(), @@Identity, and Ident_Current()?

Good question.

  • @@IDENTITY: returns the last identity value generated on your SQL connection (SPID). Most of the time it will be what you want, but sometimes it isn't (like when a trigger is fired in response to an INSERT, and the trigger executes another INSERT statement).

  • SCOPE_IDENTITY(): returns the last identity value generated in the current scope (i.e. stored procedure, trigger, function, etc).

  • IDENT_CURRENT(): returns the last identity value for a specific table. Don't use this to get the identity value from an INSERT, it's subject to race conditions (i.e. multiple connections inserting rows on the same table).

  • IDENTITY(): used when declaring a column in a table as an identity column.

For more reference, see: http://msdn.microsoft.com/en-us/library/ms187342.aspx.

To summarize: if you are inserting rows, and you want to know the value of the identity column for the row you just inserted, always use SCOPE_IDENTITY().

Set windows environment variables with a batch file

@ECHO OFF

:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/


:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"

:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m

:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m

PAUSE

How to remove an element slowly with jQuery?

target.fadeOut(300, function(){ $(this).remove();});

or

$('#target_id').fadeOut(300, function(){ $(this).remove();});

Duplicate: How to "fadeOut" & "remove" a div in jQuery?

ASP.NET MVC JsonResult Date Format

The easiest one:

var milisegundos = parseInt(data.replace("/Date(", "").replace(")/", ""));
Var newDate = new Date(milisegundos).toLocaleDateString("en-UE");

How do I select an entire row which has the largest ID in the table?

You could use a subselect:

SELECT row 
FROM table 
WHERE id=(
    SELECT max(id) FROM table
    )

Note that if the value of max(id) is not unique, multiple rows are returned.

If you only want one such row, use @MichaelMior's answer,

SELECT row from table ORDER BY id DESC LIMIT 1

SQL Server: convert ((int)year,(int)month,(int)day) to Datetime

Pure datetime solution, does not depend on language or DATEFORMAT, no strings

SELECT
    DATEADD(year, [year]-1900, DATEADD(month, [month]-1, DATEADD(day, [day]-1, 0)))
FROM
    dbo.Table

How to install a .ipa file into my iPhone?

You need to install the provisioning profile (drag and drop it into iTunes). Then drag and drop the .ipa. Ensure you device is set to sync apps, and try again.

Convert string to List<string> in one line?

If you already have a list and want to add values from a delimited string, you can use AddRange or InsertRange. For example:

existingList.AddRange(names.Split(','));

.htaccess not working on localhost with XAMPP

for xampp vm on MacOS capitan, high sierra, MacOS Mojave (10.12+), you can follow these

1. mount /opt/lampp
2. explore the folder
3. open terminal from the folder
4. cd to `htdocs`>yourapp (ex: techaz.co)
5. vim .htaccess
6. paste your .htaccess content (that is suggested on options-permalink.php)

enter image description here

How to check if a table exists in a given schema

It depends on what you want to test exactly.

Information schema?

To find "whether the table exists" (no matter who's asking), querying the information schema (information_schema.tables) is incorrect, strictly speaking, because (per documentation):

Only those tables and views are shown that the current user has access to (by way of being the owner or having some privilege).

The query provided by @kong can return FALSE, but the table can still exist. It answers the question:

How to check whether a table (or view) exists, and the current user has access to it?

SELECT EXISTS (
   SELECT FROM information_schema.tables 
   WHERE  table_schema = 'schema_name'
   AND    table_name   = 'table_name'
   );

The information schema is mainly useful to stay portable across major versions and across different RDBMS. But the implementation is slow, because Postgres has to use sophisticated views to comply to the standard (information_schema.tables is a rather simple example). And some information (like OIDs) gets lost in translation from the system catalogs - which actually carry all information.

System catalogs

Your question was:

How to check whether a table exists?

SELECT EXISTS (
   SELECT FROM pg_catalog.pg_class c
   JOIN   pg_catalog.pg_namespace n ON n.oid = c.relnamespace
   WHERE  n.nspname = 'schema_name'
   AND    c.relname = 'table_name'
   AND    c.relkind = 'r'    -- only tables
   );

Use the system catalogs pg_class and pg_namespace directly, which is also considerably faster. However, per documentation on pg_class:

The catalog pg_class catalogs tables and most everything else that has columns or is otherwise similar to a table. This includes indexes (but see also pg_index), sequences, views, materialized views, composite types, and TOAST tables;

For this particular question you can also use the system view pg_tables. A bit simpler and more portable across major Postgres versions (which is hardly of concern for this basic query):

SELECT EXISTS (
   SELECT FROM pg_tables
   WHERE  schemaname = 'schema_name'
   AND    tablename  = 'table_name'
   );

Identifiers have to be unique among all objects mentioned above. If you want to ask:

How to check whether a name for a table or similar object in a given schema is taken?

SELECT EXISTS (
   SELECT FROM pg_catalog.pg_class c
   JOIN   pg_catalog.pg_namespace n ON n.oid = c.relnamespace
   WHERE  n.nspname = 'schema_name'
   AND    c.relname = 'table_name'
   );

Alternative: cast to regclass

SELECT 'schema_name.table_name'::regclass

This raises an exception if the (optionally schema-qualified) table (or other object occupying that name) does not exist.

If you do not schema-qualify the table name, a cast to regclass defaults to the search_path and returns the OID for the first table found - or an exception if the table is in none of the listed schemas. Note that the system schemas pg_catalog and pg_temp (the schema for temporary objects of the current session) are automatically part of the search_path.

You can use that and catch a possible exception in a function. Example:

A query like above avoids possible exceptions and is therefore slightly faster.

to_regclass(rel_name) in Postgres 9.4+

Much simpler now:

SELECT to_regclass('schema_name.table_name');

Same as the cast, but it returns ...

... null rather than throwing an error if the name is not found

How to display list of repositories from subversion server

If your server is Apache, you should be able to configure it to see the repository list with viewvc - this is the most basic one, other more complex interfaces exist but this is not your purpose here.

In some versions, ViewVC is an option of the standard installation now, for instance from Collabnet.

Edit: Nevermind my previous idea just above, Peter has a much simpler way of sending the repository list.

From there, you will have to:

  • get the HTML page,
  • extract the list, and
  • process it for the individual repository search.

Unfortunately in this case I cannot think of something more straightforward.

There are examples on SO on how to extract text from HTML pages in Python, this would be a good option since Python also has bindings for SVN, to perform the repository search - you can still call svn directly from Python if you prefer.

If Python is not your cup of tea, you will have to process that differently with GNU tools (wget, then parsing tools or existing packages - I can't be of much help there, Carl gave you some more details in this post).

Can I automatically increment the file build version when using Visual Studio?

Maybe, for this task, you can use code like this:

    private bool IncreaseFileVersionBuild()
    {
        if (System.Diagnostics.Debugger.IsAttached)
        {
            try
            {
                var fi = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory).Parent.Parent.GetDirectories("Properties")[0].GetFiles("AssemblyInfo.cs")[0];
                var ve = System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly().Location);
                string ol = ve.FileMajorPart.ToString() + "." + ve.FileMinorPart.ToString() + "." + ve.FileBuildPart.ToString() + "." + ve.FilePrivatePart.ToString();
                string ne = ve.FileMajorPart.ToString() + "." + ve.FileMinorPart.ToString() + "." + (ve.FileBuildPart + 1).ToString() + "." + ve.FilePrivatePart.ToString();
                System.IO.File.WriteAllText(fi.FullName, System.IO.File.ReadAllText(fi.FullName).Replace("[assembly: AssemblyFileVersion(\"" + ol + "\")]", "[assembly: AssemblyFileVersion(\"" + ne + "\")]"));
                return true;
            }
            catch
            {
                return false;
            }
        }
        return false;
    }

and call it from form loading.
With this code you can update any part of file info in AssemblyInfo.cs (but you must use "standard" directory structure).

How do you check "if not null" with Eloquent?

If someone like me want to do it with query builder in Laravel 5.2.23 it can be done like ->

 $searchResultQuery = Users::query(); 
 $searchResultQuery->where('status_message', '<>', '', 'and'); // is not null
 $searchResultQuery->where('is_deleted', 'IS NULL', null, 'and'); // is null 

Or with scope in model :

public function scopeNotNullOnly($query){

    return $query->where('status_message', '<>', '');
}

Environment Specific application.properties file in Spring Boot application

My Point , IN this arent way asking developer to create all environment related in single go, resulting in risk of exposing Production Configuration to end developer

as per 12-Factor, shouldnt be enviornment specific reside in Enviornment only .

How do we do for CI CD

  • Build Spring one time and promote to aother environment, in that case, if we have spring jar has all environment, it iwll security risk, having all environment variable in GIT

Change icons of checked and unchecked for Checkbox for Android

Kind of a mix:

Set it in your layout file :-

 <CheckBox android:layout_width="wrap_content"
           android:layout_height="wrap_content" 
           android:text="new checkbox"
           android:background="@drawable/checkbox_background" 
           android:button="@drawable/checkbox" />

where the @drawable/checkbox will look like:

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:state_checked="true" android:state_focused="true"
  android:drawable="@drawable/checkbox_on_background_focus_yellow" />
 <item android:state_checked="false" android:state_focused="true"
  android:drawable="@drawable/checkbox_off_background_focus_yellow" />
 <item android:state_checked="false"
  android:drawable="@drawable/checkbox_off_background" />
 <item android:state_checked="true"
  android:drawable="@drawable/checkbox_on_background" />
</selector>

For each row return the column name of the largest value

A dplyr solution:

Idea:

  • add rowids as a column
  • reshape to long format
  • filter for max in each group

Code:

DF = data.frame(V1=c(2,8,1),V2=c(7,3,5),V3=c(9,6,4))
DF %>% 
  rownames_to_column() %>%
  gather(column, value, -rowname) %>%
  group_by(rowname) %>% 
  filter(rank(-value) == 1) 

Result:

# A tibble: 3 x 3
# Groups:   rowname [3]
  rowname column value
  <chr>   <chr>  <dbl>
1 2       V1         8
2 3       V2         5
3 1       V3         9

This approach can be easily extended to get the top n columns. Example for n=2:

DF %>% 
  rownames_to_column() %>%
  gather(column, value, -rowname) %>%
  group_by(rowname) %>% 
  mutate(rk = rank(-value)) %>%
  filter(rk <= 2) %>% 
  arrange(rowname, rk) 

Result:

# A tibble: 6 x 4
# Groups:   rowname [3]
  rowname column value    rk
  <chr>   <chr>  <dbl> <dbl>
1 1       V3         9     1
2 1       V2         7     2
3 2       V1         8     1
4 2       V3         6     2
5 3       V2         5     1
6 3       V3         4     2

Using numpy to build an array of all combinations of two arrays

The following numpy implementation should be approx. 2x the speed of the given answer:

def cartesian2(arrays):
    arrays = [np.asarray(a) for a in arrays]
    shape = (len(x) for x in arrays)

    ix = np.indices(shape, dtype=int)
    ix = ix.reshape(len(arrays), -1).T

    for n, arr in enumerate(arrays):
        ix[:, n] = arrays[n][ix[:, n]]

    return ix

Applying Comic Sans Ms font style

You need to use quote marks.

font-family: "Comic Sans MS", cursive, sans-serif;

Although you really really shouldn't use comic sans. The font has massive stigma attached to it's use; it's not seen as professional at all.

PHP - Get bool to echo false when false

This is the easiest way to do this:

$text = var_export($bool_value,true);
echo $text;

or

var_export($bool_value)

If the second argument is not true, it will output the result directly.

Dynamically changing font size of UILabel

minimumFontSize has been deprecated with iOS 6. You can use minimumScaleFactor.

yourLabel.adjustsFontSizeToFitWidth=YES;
yourLabel.minimumScaleFactor=0.5;

This will take care of your font size according width of label and text.

Convert blob URL to normal URL

another way to create a data url from blob url may be using canvas.

var canvas = document.createElement("canvas")
var context = canvas.getContext("2d")
context.drawImage(img, 0, 0) // i assume that img.src is your blob url
var dataurl = canvas.toDataURL("your prefer type", your prefer quality)

as what i saw in mdn, canvas.toDataURL is supported well by browsers. (except ie<9, always ie<9)

System.Threading.Timer in C# it seems to be not working. It runs very fast every 3 second

 var span = TimeSpan.FromMinutes(2);
 var t = Task.Factory.StartNew(async delegate / () =>
   {
        this.SomeAsync();
        await Task.Delay(span, source.Token);
  }, source.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);

source.Cancel(true/or not);

// or use ThreadPool(whit defaul options thread) like this
Task.Start(()=>{...}), source.Token)

if u like use some loop thread inside ...

public async void RunForestRun(CancellationToken token)
{
  var t = await Task.Factory.StartNew(async delegate
   {
       while (true)
       {
           await Task.Delay(TimeSpan.FromSeconds(1), token)
                 .ContinueWith(task => { Console.WriteLine("End delay"); });
           this.PrintConsole(1);
        }
    }, token) // drop thread options to default values;
}

// And somewhere there
source.Cancel();
//or
token.ThrowIfCancellationRequested(); // try/ catch block requred.

How to upgrade pip3?

You are using pip3 to install flask-script which is associated with python 3.5. However, you are trying to upgrade pip associated with the python 2.7, try running pip3 install --upgrade pip.

It might be a good idea to take some time and read about virtual environments in Python. It isn't a best practice to install all of your packages to the base python installation. This would be a good start: http://docs.python-guide.org/en/latest/dev/virtualenvs/

Save file/open file dialog box, using Swing & Netbeans GUI editor

I have created a sample UI which shows the save and open file dialog. Click on save button to open save dialog and click on open button to open file dialog.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class FileChooserEx {
    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                new FileChooserEx().createUI();
            }
        };

        EventQueue.invokeLater(r);
    }

    private void createUI() {
        JFrame frame = new JFrame();
        frame.setLayout(new BorderLayout());

        JButton saveBtn = new JButton("Save");
        JButton openBtn = new JButton("Open");

        saveBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                JFileChooser saveFile = new JFileChooser();
                saveFile.showSaveDialog(null);
            }
        });

        openBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                JFileChooser openFile = new JFileChooser();
                openFile.showOpenDialog(null);
            }
        });

        frame.add(new JLabel("File Chooser"), BorderLayout.NORTH);
        frame.add(saveBtn, BorderLayout.CENTER);
        frame.add(openBtn, BorderLayout.SOUTH);
        frame.setTitle("File Chooser");
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

What is the difference between an expression and a statement in Python?

Though this isn't related to Python:

An expression evaluates to a value. A statement does something.

>>> x + 2         # an expression
>>> x = 1         # a statement 
>>> y = x + 1     # a statement
>>> print y       # a statement (in 2.x)
2

What is the difference between Builder Design pattern and Factory Design pattern?

Both are very much similar , but if you have a large number of parameters for object creation with some of them optional with some default values , go for Builder pattern.

Installation failed with message Invalid File

Click Build tab ---> Clean Project

Click Build tab ---> Build APK

Run.

How to use google maps without api key

this simple code work 100% all you need is changing 'lat','long' for address to show

<iframe src="http://maps.google.com/maps?q=25.3076008,51.4803216&z=16&output=embed" height="450" width="600"></iframe>

What does the arrow operator, '->', do in Java?

That's part of the syntax of the new lambda expressions, to be introduced in Java 8. There are a couple of online tutorials to get the hang of it, here's a link to one. Basically, the -> separates the parameters (left-side) from the implementation (right side).

The general syntax for using lambda expressions is

(Parameters) -> { Body } where the -> separates parameters and lambda expression body.

The parameters are enclosed in parentheses which is the same way as for methods and the lambda expression body is a block of code enclosed in braces.

How to set page content to the middle of screen?

If you want to center the content horizontally and vertically, but don't know in prior how high your page will be, you have to you use JavaScript.

HTML:

<body>
    <div id="content">...</div>
</body>

CSS:

#content {
    max-width: 1000px;
    margin: auto;
    left: 1%;
    right: 1%;
    position: absolute;
}

JavaScript (using jQuery):

$(function() {
    $(window).on('resize', function resize()  {
        $(window).off('resize', resize);
        setTimeout(function () {
            var content = $('#content');
            var top = (window.innerHeight - content.height()) / 2;
            content.css('top', Math.max(0, top) + 'px');
            $(window).on('resize', resize);
        }, 50);
    }).resize();
});

Centered horizontally and vertically

Demo: http://jsfiddle.net/nBzcb/

javascript find and remove object in array based on key value

Maybe you are looking for $.grep() function:

arr = [
  {"id":"88","name":"Lets go testing"},
  {"id":"99","name":"Have fun boys and girls"},
  {"id":"108","name":"You are awesome!"}
];

id = 88;
arr = $.grep(arr, function(data, index) {
   return data.id != id
});

Copying text to the clipboard using Java

The following class allows you to copy/paste a String to/from the clipboard.

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;

import static java.awt.event.KeyEvent.*;
import static org.apache.commons.lang3.SystemUtils.IS_OS_MAC;

public class SystemClipboard
{
    public static void copy(String text)
    {
        Clipboard clipboard = getSystemClipboard();
        clipboard.setContents(new StringSelection(text), null);
    }

    public static void paste() throws AWTException
    {
        Robot robot = new Robot();

        int controlKey = IS_OS_MAC ? VK_META : VK_CONTROL;
        robot.keyPress(controlKey);
        robot.keyPress(VK_V);
        robot.keyRelease(controlKey);
        robot.keyRelease(VK_V);
    }

    public static String get() throws Exception
    {
        Clipboard systemClipboard = getSystemClipboard();
        DataFlavor dataFlavor = DataFlavor.stringFlavor;

        if (systemClipboard.isDataFlavorAvailable(dataFlavor))
        {
            Object text = systemClipboard.getData(dataFlavor);
            return (String) text;
        }

        return null;
    }

    private static Clipboard getSystemClipboard()
    {
        Toolkit defaultToolkit = Toolkit.getDefaultToolkit();
        return defaultToolkit.getSystemClipboard();
    }
}

How to change the default message of the required field in the popover of form-control in bootstrap?

You can use setCustomValidity function when oninvalid event occurs.

Like below:-

<input class="form-control" type="email" required="" 
    placeholder="username" oninvalid="this.setCustomValidity('Please Enter valid email')">
</input>

Update:-

To clear the message once you start entering use oninput="setCustomValidity('') attribute to clear the message.

<input class="form-control" type="email"  required="" placeholder="username"
 oninvalid="this.setCustomValidity('Please Enter valid email')"
 oninput="setCustomValidity('')"></input>

Get host domain from URL?

The best way, and the right way to do it is using Uri.Authority field

Load and use Uri like so :

Uri NewUri;

if (Uri.TryCreate([string with your Url], UriKind.Absolute, out NewUri))
{
     Console.Writeline(NewUri.Authority);
}

Input : http://support.domain.com/default.aspx?id=12345
Output : support.domain.com

Input : http://www.domain.com/default.aspx?id=12345
output : www.domain.com

Input : http://localhost/default.aspx?id=12345
Output : localhost

If you want to manipulate Url, using Uri object is the good way to do it. https://msdn.microsoft.com/en-us/library/system.uri(v=vs.110).aspx

When do we need curly braces around shell variables?

Following SierraX and Peter's suggestion about text manipulation, curly brackets {} are used to pass a variable to a command, for instance:

Let's say you have a sposi.txt file containing the first line of a well-known Italian novel:

> sposi="somewhere/myfolder/sposi.txt"
> cat $sposi

Ouput: quel ramo del lago di como che volge a mezzogiorno

Now create two variables:

# Search the 2nd word found in the file that "sposi" variable points to
> word=$(cat $sposi | cut -d " " -f 2)

# This variable will replace the word
> new_word="filone"

Now substitute the word variable content with the one of new_word, inside sposi.txt file

> sed -i "s/${word}/${new_word}/g" $sposi
> cat $sposi

Ouput: quel filone del lago di como che volge a mezzogiorno

The word "ramo" has been replaced.

jQuery: how to find first visible input/select/textarea excluding buttons?

This is an improvement over @Mottie's answer because as of jQuery 1.5.2 :text selects input elements that have no specified type attribute (in which case type="text" is implied):

$('form').find(':text,textarea,select').filter(':visible:first')

Oracle PL/SQL - Are NO_DATA_FOUND Exceptions bad for stored procedure performance?

Yes, you're missing using cursors

DECLARE
  CURSOR foo_cur IS 
    SELECT NEEDED_FIELD WHERE condition ;
BEGIN
  OPEN foo_cur;
  FETCH foo_cur INTO foo_rec;
  IF foo_cur%FOUND THEN
     ...
  END IF;
  CLOSE foo_cur;
EXCEPTION
  WHEN OTHERS THEN
    CLOSE foo_cur;
    RAISE;
END ;

admittedly this is more code, but it doesn't use EXCEPTIONs as flow-control which, having learnt most of my PL/SQL from Steve Feuerstein's PL/SQL Programming book, I believe to be a good thing.

Whether this is faster or not I don't know (I do very little PL/SQL nowadays).

jQuery UI " $("#datepicker").datepicker is not a function"

Have you tried using $("#<%= txtDateElementId.ClientID %>").datepicker(); instead of $("#txtDateElementId").datepicker(); when selecting an element by ID using JQuery.

Setting user agent of a java URLConnection

Off hand, setting the http.agent system property to "" might do the trick (I don't have the code in front of me).

You might get away with:

 System.setProperty("http.agent", "");

but that might require a race between you and initialisation of the URL protocol handler, if it caches the value at startup (actually, I don't think it does).

The property can also be set through JNLP files (available to applets from 6u10) and on the command line:

-Dhttp.agent=

Or for wrapper commands:

-J-Dhttp.agent=

Remote Procedure call failed with sql server 2008 R2

I got the samilar issue, while both SQLServer and SQLServerAgent services are running. The error is fixed by a restart of services.

Server Manager > Service > 
    SQL Server > Stop
    SQL Server > Start
    SQL Server Agent > Start

super() raises "TypeError: must be type, not classobj" for new-style class

super() can be used only in the new-style classes, which means the root class needs to inherit from the 'object' class.

For example, the top class need to be like this:

class SomeClass(object):
    def __init__(self):
        ....

not

class SomeClass():
    def __init__(self):
        ....

So, the solution is that call the parent's init method directly, like this way:

class TextParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.all_data = []

Gradle Error:Execution failed for task ':app:processDebugGoogleServices'

check gradle.properties and add android.useAndroidX=true or you can also add android.enableJetifier=true or you can comment it by #

worked for me

What is JSON and why would I use it?

In short, it is a scripting notation for passing data about. In some ways an alternative to XML, natively supporting basic data types, arrays and associative arrays (name-value pairs, called Objects because that is what they represent).

The syntax is that used in JavaScript and JSON itself stands for "JavaScript Object Notation". However it has become portable and is used in other languages too.

A useful link for detail is here:

http://secretgeek.net/json_3mins.asp

How can I make a list of installed packages in a certain virtualenv?

If you're still a bit confused about virtualenv you might not pick up how to combine the great tips from the answers by Ioannis and Sascha. I.e. this is the basic command you need:

/YOUR_ENV/bin/pip freeze --local

That can be easily used elsewhere. E.g. here is a convenient and complete answer, suited for getting all the local packages installed in all the environments you set up via virtualenvwrapper:

cd ${WORKON_HOME:-~/.virtualenvs}
for dir in *; do [ -d $dir ] && $dir/bin/pip freeze --local >  /tmp/$dir.fl; done
more /tmp/*.fl

Get all rows from SQLite

I have been looking into the same problem! I think your problem is related to where you identify the variable that you use to populate the ArrayList that you return. If you define it inside the loop, then it will always reference the last row in the table in the database. In order to avoid this, you have to identify it outside the loop:

String name;
if (cursor.moveToFirst()) {

        while (cursor.isAfterLast() == false) {
            name = cursor.getString(cursor
                    .getColumnIndex(countyname));

            list.add(name);
            cursor.moveToNext();
        }
}

Javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: Failure in SSL library, usually a protocol error

When I got this error, it was because the protocols (TLS versions) and/or cipher suites supported by the server were not enabled on (and possibly not even supported by) the device. For API 16-19, TLSv1.1 and TLSv1.2 are supported but not enabled by default. Once I enabled them for these versions, I still got the error because these versions don't support any of the ciphers on our instance of AWS CloudFront.

Since it's not possible to add ciphers to Android, we had to switch our CloudFront version from TLSv1.2_2018 to TLSv1.1_2016 (which still supports TLSv1.2; it just doesn't require it), which has four of the ciphers supported by the earlier Android versions, two of which are still considered strong.

At that point, the error disappeared and the calls went through (with TLSv1.2) because there was at least one protocol and at least one cipher that the device and server shared.

Refer to the tables on this page to see which protocols and ciphers are supported by and enabled on which versions of Android.

Now was Android really trying to use SSLv3 as implied by the "sslv3 alert handshake failure" part of the error message? I doubt it; I suspect this is an old cobweb in the SSL library that hasn't been cleaned out but I can't say for sure.

In order to enable TLSv1.2 (and TLSv1.1), I was able to use a much simpler SSLSocketFactory than the ones seen elsewhere (like NoSSLv3SocketFactory). It simply makes sure that the enabled protocols include all the supported protocols and that the enabled ciphers include all the supported ciphers (the latter wasn't necessary for me but it could be for others) - see configure() at the bottom. If you'd rather enable only the latest protocols, you can replace socket.supportedProtocols with something like arrayOf("TLSv1.1", "TLSv1.2") (likewise for the ciphers):

class TLSSocketFactory : SSLSocketFactory() {

    private val socketFactory: SSLSocketFactory

    init {
        val sslContext = SSLContext.getInstance("TLS")
        sslContext.init(null, null, null)
        socketFactory = sslContext.socketFactory
    }

    override fun getDefaultCipherSuites(): Array<String> {
        return socketFactory.defaultCipherSuites
    }

    override fun getSupportedCipherSuites(): Array<String> {
        return socketFactory.supportedCipherSuites
    }

    override fun createSocket(s: Socket, host: String, port: Int, autoClose: Boolean): Socket {
        return configure(socketFactory.createSocket(s, host, port, autoClose) as SSLSocket)
    }

    override fun createSocket(host: String, port: Int): Socket {
        return configure(socketFactory.createSocket(host, port) as SSLSocket)
    }

    override fun createSocket(host: InetAddress, port: Int): Socket {
        return configure(socketFactory.createSocket(host, port) as SSLSocket)
    }

    override fun createSocket(host: String, port: Int, localHost: InetAddress, localPort: Int): Socket {
        return configure(socketFactory.createSocket(host, port, localHost, localPort) as SSLSocket)
    }

    override fun createSocket(address: InetAddress, port: Int, localAddress: InetAddress, localPort: Int): Socket {
        return configure(socketFactory.createSocket(address, port, localAddress, localPort) as SSLSocket)
    }

    private fun configure(socket: SSLSocket): SSLSocket {
        socket.enabledProtocols = socket.supportedProtocols
        socket.enabledCipherSuites = socket.supportedCipherSuites
        return socket
    }
}

SQLite - getting number of rows in a database

Extension of VolkerK's answer, to make code a little more readable, you can use AS to reference the count, example below:

SELECT COUNT(*) AS c from profile

This makes for much easier reading in some frameworks, for example, i'm using Exponent's (React Native) Sqlite integration, and without the AS statement, the code is pretty ugly.

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=0, data=null} to activity

If the user cancel the request, the data will be returned as NULL. The thread will throw a nullPointerException when you call data.getExtras().get("data");. I think you just need to add a conditional to check if the data returned is null.

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    if (requestCode == CAMERA_REQUEST) {
       if (data != null)
       {         
           Bitmap photo = (Bitmap) data.getExtras().get("data"); 
           imageView.setImageBitmap(photo);
       }
}  

How to kill a child process by the parent process?

Try something like this:

#include <signal.h>

pid_t child_pid = -1 ; //Global

void kill_child(int sig)
{
    kill(child_pid,SIGKILL);
}

int main(int argc, char *argv[])
{
    signal(SIGALRM,(void (*)(int))kill_child);
    child_pid = fork();
    if (child_pid > 0) {
     /*PARENT*/
        alarm(30);
        /*
         * Do parent's tasks here.
         */
        wait(NULL);
    }
    else if (child_pid == 0){
     /*CHILD*/
        /*
         * Do child's tasks here.
         */
    }
}

Best way to deploy Visual Studio application that can run without installing

First you need to publish the file by:

  1. BUILD -> PUBLISH or by right clicking project on Solution Explorer -> properties -> publish or select project in Solution Explorer and press Alt + Enter NOTE: if you are using Visual Studio 2013 then in properties you have to go to BUILD and then you have to disable define DEBUG constant and define TRACE constant and you are ready to go. Representation

  2. Save your file to a particular folder. Find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the bin\Debug folder below the project file (.csproj). In Visual Studio they are in the Application Files folder and inside that you just need the .exe and dll files. (You have to delete ClickOnce and other files and then make this folder a zip file and distribute it.)

NOTE: The ClickOnce application does install the project to system, but it has one advantage. You DO NOT require administrative privileges here to run (if your application follows the normal guidelines for which folders to use for application data, etc.).

Quicker way to get all unique values of a column in VBA?

Use Excel's AdvancedFilter function to do this.

Using Excels inbuilt C++ is the fastest way with smaller datasets, using the dictionary is faster for larger datasets. For example:

Copy values in Column A and insert the unique values in column B:

Range("A1:A6").AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("B1"), Unique:=True

It works with multiple columns too:

Range("A1:B4").AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("D1:E1"), Unique:=True

Be careful with multiple columns as it doesn't always work as expected. In those cases I resort to removing duplicates which works by choosing a selection of columns to base uniqueness. Ref: MSDN - Find and remove duplicates

enter image description here

Here I remove duplicate columns based on the third column:

Range("A1:C4").RemoveDuplicates Columns:=3, Header:=xlNo

Here I remove duplicate columns based on the second and third column:

Range("A1:C4").RemoveDuplicates Columns:=Array(2, 3), Header:=xlNo

Socket accept - "Too many open files"

On MacOS, show the limits:

launchctl limit maxfiles

Result like: maxfiles 256 1000

If the numbers (soft limit & hard limit) are too low, you have to set upper:

sudo launchctl limit maxfiles 65536 200000

Mounting multiple volumes on a docker container?

On Windows: if you had to mount two directories E:\data\dev & E:\data\dev2

Use:

docker run -v E:\data\dev:c:/downloads -v E:\data\dev2 c:/downloads2 -i --publish 1111:80 -P SomeBuiltContainerName:SomeLabel

How to create a sub array from another array in Java?

Use copyOfRange method from java.util.Arrays class:

int[] newArray = Arrays.copyOfRange(oldArray, startIndex, endIndex);

For more details:

Link to similar question

How to hash a password

I use a hash and a salt for my password encryption (it's the same hash that Asp.Net Membership uses):

private string PasswordSalt
{
   get
   {
      var rng = new RNGCryptoServiceProvider();
      var buff = new byte[32];
      rng.GetBytes(buff);
      return Convert.ToBase64String(buff);
   }
}

private string EncodePassword(string password, string salt)
{
   byte[] bytes = Encoding.Unicode.GetBytes(password);
   byte[] src = Encoding.Unicode.GetBytes(salt);
   byte[] dst = new byte[src.Length + bytes.Length];
   Buffer.BlockCopy(src, 0, dst, 0, src.Length);
   Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
   HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
   byte[] inarray = algorithm.ComputeHash(dst);
   return Convert.ToBase64String(inarray);
}

How do I create a circle or square with just CSS - with a hollow center?

You can use special characters to make lots of shapes. Examples: http://jsfiddle.net/martlark/jWh2N/2/

_x000D_
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>hollow square</td>_x000D_
    <td>&#9633;</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>solid circle</td>_x000D_
    <td>&bull;</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>open circle</td>_x000D_
    <td>&#3664;</td>_x000D_
  </tr>_x000D_
_x000D_
</table>
_x000D_
_x000D_
_x000D_

enter image description here

Many more can be found here: HTML Special Characters

Best way to style a TextBox in CSS

You could target all text boxes with input[type=text] and then explicitly define the class for the textboxes who need it.

You can code like below :

_x000D_
_x000D_
input[type=text] {_x000D_
  padding: 0;_x000D_
  height: 30px;_x000D_
  position: relative;_x000D_
  left: 0;_x000D_
  outline: none;_x000D_
  border: 1px solid #cdcdcd;_x000D_
  border-color: rgba(0, 0, 0, .15);_x000D_
  background-color: white;_x000D_
  font-size: 16px;_x000D_
}_x000D_
_x000D_
.advancedSearchTextbox {_x000D_
  width: 526px;_x000D_
  margin-right: -4px;_x000D_
}
_x000D_
<input type="text" class="advancedSearchTextBox" />
_x000D_
_x000D_
_x000D_

for-in statement

TypeScript isn't giving you a gun to shoot yourself in the foot with.

The iterator variable is a string because it is a string, full stop. Observe:

var obj = {};
obj['0'] = 'quote zero quote';
obj[0.0] = 'zero point zero';
obj['[object Object]'] = 'literal string "[object Object]"';
obj[<any>obj] = 'this obj'
obj[<any>undefined] = 'undefined';
obj[<any>"undefined"] = 'the literal string "undefined"';

for(var key in obj) {
    console.log('Type: ' + typeof key);
    console.log(key + ' => ' + obj[key]);
}

How many key/value pairs are in obj now? 6, more or less? No, 3, and all of the keys are strings:

Type: string
0 => zero point zero
Type: string
[object Object] => this obj; 
Type: string
undefined => the literal string "undefined" 

How can I create a Java method that accepts a variable number of arguments?

This is known as varargs see the link here for more details

In past java releases, a method that took an arbitrary number of values required you to create an array and put the values into the array prior to invoking the method. For example, here is how one used the MessageFormat class to format a message:

Object[] arguments = {
    new Integer(7),
    new Date(),
    "a disturbance in the Force"
};
    String result = MessageFormat.format(
        "At {1,time} on {1,date}, there was {2} on planet "
         + "{0,number,integer}.", arguments);

It is still true that multiple arguments must be passed in an array, but the varargs feature automates and hides the process. Furthermore, it is upward compatible with preexisting APIs. So, for example, the MessageFormat.format method now has this declaration:

public static String format(String pattern,
                            Object... arguments);

How do I configure Apache 2 to run Perl CGI scripts?

This post is intended to rescue the people who are suffering from *not being able to properly setup Apache2 for Perl on Ubuntu. (The system configurations specific to your Linux machine will be mentioned within square brackets, like [this]).

Possible outcome of an improperly setup Apache 2:

  1. Browser trying to download the .pl file instead of executing and giving out the result.
  2. Forbidden.
  3. Internal server error.

If one follows the steps described below with a reasonable intelligence, he/she can get through the errors mentioned above.

Before starting the steps. Go to /etc/hosts file and add IP address / domain-name` for example:

127.0.0.1 www.BECK.com

Step 1: Install apache2 Step 2: Install mod_perl Step 3: Configure apache2

open sites-available/default and add the following,

<Files ~ "\.(pl|cgi)$">
    SetHandler perl-script
    PerlResponseHandler ModPerl::PerlRun
    Options +ExecCGI
    PerlSendHeader On
</Files>

<Directory />
    Options FollowSymLinks
    AllowOverride None
</Directory>
<Directory [path-to-store-your-website-files-like-.html-(perl-scripts-should-be-stored-in-cgi-bin] >
####(The Perl/CGI scripts can be stored out of the cgi-bin directory, but that's a story for another day. Let's concentrate on washing out the issue at hand)
####
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

ScriptAlias /cgi-bin/ [path-where-you-want-your-.pl-and-.cgi-files]

<Directory [path-where-you-want-your-.pl-and-.cgi-files]>
    AllowOverride None
    Options ExecCGI -MultiViews +SymLinksIfOwnerMatch
    AddHandler cgi-script .pl
    Order allow,deny
    allow from all
</Directory>
<Files ~ "\.(pl|cgi)$">
    SetHandler perl-script
    PerlResponseHandler ModPerl::PerlRun
    Options +ExecCGI
    PerlSendHeader On
</Files>

<Directory />
    Options FollowSymLinks
    AllowOverride None
</Directory>
<Directory [path-to-store-your-website-files-like-.html-(perl-scripts-should-be-stored-in-cgi-bin] >
####(The Perl/CGI scripts can be stored out of the cgi-bin directory, but that's a story for another day. Let's concentrate on washing out the issue at hand)
####
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

ScriptAlias /cgi-bin/ [path-where-you-want-your-.pl-and-.cgi-files]

<Directory [path-where-you-want-your-.pl-and-.cgi-files]>
    AllowOverride None
    Options ExecCGI -MultiViews +SymLinksIfOwnerMatch
    AddHandler cgi-script .pl
    Order allow,deny
    allow from all
</Directory>

Step 4:

Add the following lines to your /etc/apache2/apache2.conf file.

AddHandler cgi-script .cgi .pl
<Files ~ "\.pl$">
Options +ExecCGI
</Files>
<Files ~ "\.cgi$">
Options +ExecCGI
</Files>

<IfModule mod_perl.c>
<IfModule mod_alias.c>
Alias /perl/ /home/sly/host/perl/
</IfModule>
<Location /perl>
SetHandler perl-script
PerlHandler Apache::Registry
Options +ExecCGI
</Location>
</IfModule>

<Files ~ "\.pl$">
Options +ExecCGI
</Files>

Step 5:

Very important, or at least I guess so, only after doing this step, I got it to work.

AddHandler cgi-script .cgi .pl

<Files ~ "\.pl$">
Options +ExecCGI
</Files>
<Files ~ "\.cgi$">
Options +ExecCGI
</Files>

<IfModule mod_perl.c>
<IfModule mod_alias.c>
Alias /perl/ /home/sly/host/perl/
</IfModule>
<Location /perl>
SetHandler perl-script
PerlHandler Apache::Registry
Options +ExecCGI
</Location>
</IfModule>

<Files ~ "\.pl$">
Options +ExecCGI
</Files>

Step 6

Very important, or at least I guess so, only after doing this step, I got it to work.

Add the following to you /etc/apache2/sites-enabled/000-default file

<Files ~ "\.(pl|cgi)$">
SetHandler perl-script
PerlResponseHandler ModPerl::PerlRun
Options +ExecCGI
PerlSendHeader On
</Files>

Step 7:

Now add, your Perl script as test.pl in the place where you mentioned before in step 3 as [path-where-you-want-your-.pl-and-.cgi-files].

Give permissions to the .pl file using chmod and then, type the webaddress/cgi-bin/test.pl in the address bar of the browser, there you go, you got it.

(Now, many of the things would have been redundant in this post. Kindly ignore it.)

Python write line by line to a text file

You may want to look into os dependent line separators, e.g.:

import os

with open('./output.txt', 'a') as f1:
    f1.write(content + os.linesep)

substring index range

For substring(startIndex, endIndex), startIndex is inclusive and endIndex are exclusive. The startIndex and endIndex are very confusing. I would understand substring(startIndex, length) to remember that.

jQuery - hashchange event

Note that in case of IE 7 and IE 9 if statment will give true for ("onhashchange" in windows) but the window.onhashchange will never fire, so its better to store hash and check it after every 100 millisecond whether its changed or not for all versions of IE.

    if (("onhashchange" in window) && !($.browser.msie)) { 
         window.onhashchange = function () { 
              alert(window.location.hash);             
         }            
         // Or $(window).bind( 'hashchange',function(e) {  
         //       alert(window.location.hash); 
         //   });              
    }
    else { 
        var prevHash = window.location.hash;
        window.setInterval(function () {
           if (window.location.hash != prevHash) {
              prevHash = window.location.hash;
              alert(window.location.hash);
           }
        }, 100);
    }

How to make Unicode charset in cmd.exe by default?

After I tried algirdas' solution, my Windows crashed (Win 7 Pro 64bit) so I decided to try a different solution:

  1. Start Run (Win+R)
  2. Type cmd /K chcp 65001

You will get mostly what you want. To start it from the taskbar or anywhere else, make a shortcut (you can name it cmd.unicode.exe or whatever you like) and change its Target to C:\Windows\System32\cmd.exe /K chcp 65001.

Correct format specifier for double in printf

It can be %f, %g or %e depending on how you want the number to be formatted. See here for more details. The l modifier is required in scanf with double, but not in printf.

How to break/exit from a each() function in JQuery?

if (condition){ // where condition evaluates to true 
    return false
}

see similar question asked 3 days ago.

Adding multiple columns AFTER a specific column in MySQL

The solution that worked for me with default value 0 is the following

ALTER TABLE reservations ADD COLUMN isGuest BIT DEFAULT 0

Calculate relative time in C#

Jeff, your code is nice but could be clearer with constants (as suggested in Code Complete).

const int SECOND = 1;
const int MINUTE = 60 * SECOND;
const int HOUR = 60 * MINUTE;
const int DAY = 24 * HOUR;
const int MONTH = 30 * DAY;

var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);
double delta = Math.Abs(ts.TotalSeconds);

if (delta < 1 * MINUTE)
  return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";

if (delta < 2 * MINUTE)
  return "a minute ago";

if (delta < 45 * MINUTE)
  return ts.Minutes + " minutes ago";

if (delta < 90 * MINUTE)
  return "an hour ago";

if (delta < 24 * HOUR)
  return ts.Hours + " hours ago";

if (delta < 48 * HOUR)
  return "yesterday";

if (delta < 30 * DAY)
  return ts.Days + " days ago";

if (delta < 12 * MONTH)
{
  int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
  return months <= 1 ? "one month ago" : months + " months ago";
}
else
{
  int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
  return years <= 1 ? "one year ago" : years + " years ago";
}

Fastest way to Remove Duplicate Value from a list<> by lambda

If you want to stick with the original List instead of creating a new one, you can something similar to what the Distinct() extension method does internally, i.e. use a HashSet to check for uniqueness:

HashSet<long> set = new HashSet<long>(longs.Count);
longs.RemoveAll(x => !set.Add(x));

The List class provides this convenient RemoveAll(predicate) method that drops all elements not satisfying the condition specified by the predicate. The predicate is a delegate taking a parameter of the list's element type and returning a bool value. The HashSet's Add() method returns true only if the set doesn't contain the item yet. Thus by removing any items from the list that can't be added to the set you effectively remove all duplicates.