Programs & Examples On #Main

In many programming languages, the main function, subroutine, or method marks the entry point of the program. It is generally the first-programmer-written function run when a program starts.

Can there exist two main methods in a Java program?

Yes it is possible to have two main() in the same program. For instance, if I have a class Demo1 as below. Compiling this file will generate Demo1.class file. And once you run this it will run the main() having array of String arguments by default. It won't even sniff at the main() with int argument.

class Demo1 {   
static int a, b;    
public static void main(int args) {
     System.out.println("Using Demo1 class Main with int arg");
     a =30;
     b =40;
     System.out.println("Product is: "+a*b);
 }
public static void main(String[] args) {
      System.out.println("Using Demo1 class Main with string arg");
      a =10;
      b =20;
      System.out.println("Product is: "+a*b);

 }
 }      

Output:
Using Demo1 class Main with string arg
Product is: 200

But if I add another class named Anonym and save the file as Anonym.java. Inside this I call the Demo1 class main()[either int argument or string argument one]. After compiling this Anonym.class file gets generated.

class Demo1 {   
    static int a, b;    
public static void main(int args) {
    System.out.println("Using Demo1 class Main with int arg");
    a =30;
    b =40;
    System.out.println("Product is: "+a*b);
}
public static void main(String[] args) {
    System.out.println("Using Demo1 class Main with string arg");
     a =10;
     b =20;
     System.out.println("Product is: "+a*b);        
} 
}       

class Anonym{
public static void main(String arg[])
{

    Demo1.main(1);
    Demo1.main(null);
}
}


Output:
Using Demo1 class Main with int arg
Product is: 1200
Using Demo1 class Main with string arg
Product is: 200

Can't execute jar- file: "no main manifest attribute"

I had the same issue today. My problem was solved my moving META-INF to the resources folder.

C# importing class into another class doesn't work

If they are separate class files within the same project, then you do not need to have an 'import' statement. Just use the class straight off. If the files are in separate projects, you need to add a reference to the project first before you can use an 'import' statement on it.

Using Spring 3 autowire in a standalone Java application

Spring works in standalone application. You are using the wrong way to create a spring bean. The correct way to do it like this:

@Component
public class Main {

    public static void main(String[] args) {
        ApplicationContext context = 
            new ClassPathXmlApplicationContext("META-INF/config.xml");

        Main p = context.getBean(Main.class);
        p.start(args);
    }

    @Autowired
    private MyBean myBean;
    private void start(String[] args) {
        System.out.println("my beans method: " + myBean.getStr());
    }
}

@Service 
public class MyBean {
    public String getStr() {
        return "string";
    }
}

In the first case (the one in the question), you are creating the object by yourself, rather than getting it from the Spring context. So Spring does not get a chance to Autowire the dependencies (which causes the NullPointerException).

In the second case (the one in this answer), you get the bean from the Spring context and hence it is Spring managed and Spring takes care of autowiring.

In Python, can I call the main() of an imported module?

It's just a function. Import it and call it:

import myModule

myModule.main()

If you need to parse arguments, you have two options:

  • Parse them in main(), but pass in sys.argv as a parameter (all code below in the same module myModule):

    def main(args):
        # parse arguments using optparse or argparse or what have you
    
    if __name__ == '__main__':
        import sys
        main(sys.argv[1:])
    

    Now you can import and call myModule.main(['arg1', 'arg2', 'arg3']) from other another module.

  • Have main() accept parameters that are already parsed (again all code in the myModule module):

    def main(foo, bar, baz='spam'):
        # run with already parsed arguments
    
    if __name__ == '__main__':
        import sys
        # parse sys.argv[1:] using optparse or argparse or what have you
        main(foovalue, barvalue, **dictofoptions)
    

    and import and call myModule.main(foovalue, barvalue, baz='ham') elsewhere and passing in python arguments as needed.

The trick here is to detect when your module is being used as a script; when you run a python file as the main script (python filename.py) no import statement is being used, so python calls that module "__main__". But if that same filename.py code is treated as a module (import filename), then python uses that as the module name instead. In both cases the variable __name__ is set, and testing against that tells you how your code was run.

Could not find or load main class with a Jar File

I know this is an old question, but I had this problem recently and none of the answers helped me. However, Corral's comment on Ryan Atkinson's answer did tip me off to the problem.

I had all my compiled class files in target/classes, which are not packages in my case. I was trying to package it with jar cvfe App.jar target/classes App, from the root directory of my project, as my App class was in the default unnamed package.

This doesn't work, as the newly created App.jar will have the class App.class in the directory target/classes. If you try to run this jar with java -jar App.jar, it will complain that it cannot find the App class. This is because the packages inside App.jar don't match the actual packages in the project.

This could be solved by creating the jar directly from the target/classes directory, using jar cvfe App.jar . App. This is rather cumbersome in my opinion.

The simple solution is to list the folders you want to add with the -C option instead of using the default way of listing folders. So, in my case, the correct command is java cvfe App.jar App -C target/classes .. This will directly add all files in the target/classes directory to the root of App.jar, thus solving the problem.

Why is the Java main method static?

I think the keyword 'static' makes the main method a class method, and class methods have only one copy of it and can be shared by all, and also, it does not require an object for reference. So when the driver class is compiled the main method can be invoked. (I'm just in alphabet level of java, sorry if I'm wrong)

What does if __name__ == "__main__": do?

When your script is run by passing it as a command to the Python interpreter,

python myscript.py

all of the code that is at indentation level 0 gets executed. Functions and classes that are defined are, well, defined, but none of their code gets run. Unlike other languages, there's no main() function that gets run automatically - the main() function is implicitly all the code at the top level.

In this case, the top-level code is an if block. __name__ is a built-in variable which evaluates to the name of the current module. However, if a module is being run directly (as in myscript.py above), then __name__ instead is set to the string "__main__". Thus, you can test whether your script is being run directly or being imported by something else by testing

if __name__ == "__main__":
    ...

If your script is being imported into another module, its various function and class definitions will be imported and its top-level code will be executed, but the code in the then-body of the if clause above won't get run as the condition is not met. As a basic example, consider the following two scripts:

# file one.py
def func():
    print("func() in one.py")

print("top-level in one.py")

if __name__ == "__main__":
    print("one.py is being run directly")
else:
    print("one.py is being imported into another module")
# file two.py
import one

print("top-level in two.py")
one.func()

if __name__ == "__main__":
    print("two.py is being run directly")
else:
    print("two.py is being imported into another module")

Now, if you invoke the interpreter as

python one.py

The output will be

top-level in one.py
one.py is being run directly

If you run two.py instead:

python two.py

You get

top-level in one.py
one.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly

Thus, when module one gets loaded, its __name__ equals "one" instead of "__main__".

Eclipse error "Could not find or load main class"

you should add bin folder - run->run Configuration tab classpath advanced button - add folder - choose bin folder (yourproyect/bin)

Explanation of 'String args[]' and static in 'public static void main(String[] args)'

If I were explaining this to someone I'd say we'll get to it later for now you need to know that the way to run your program is to use :

public static void main(String[] args) {
        ...
    }

Assuming he/she knows what an array is, I'd say the args is an argument array and you can show some cool examples.

Then after you've gone a bit about Java/JVM and that stuff, you'd get to modifiers eventually to static and public as well.

Then you can spend some time talking about meaning of these IMHO.

You could mention other "cool" stuff such as varargs that you can use this in later versions of Java.

public static void main(String ...args) {
        //...
    }

Maven Error: Could not find or load main class

I got this error(classNotFoundException for main class), I actually changed pom version , so did maven install again and then error vanished.

String method cannot be found in a main class method

It seem like your Resort method doesn't declare a compareTo method. This method typically belongs to the Comparable interface. Make sure your class implements it.

Additionally, the compareTo method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String argument, but rather a Resort.

Alternatively, you can compare the names of the resorts. For example

if (resortList[mid].getResortName().compareTo(resortName)>0)  

Error: Main method not found in class Calculate, please define the main method as: public static void main(String[] args)

My suggestions :

  • Keep the program modular. Keep the Calculate class in a separate Calculate.java file and create a new class that calls the main method. This would make the code readable.
  • For setting the values in the number, use constructors. Do not use like the methods you have used above like :

    public void setNumber(double fnum, double snum){ this.fn = fnum; this.sn = snum; }

    Constructors exists to initialize the objects.This is their job and they are pretty good at it.

  • Getters for members of Calculate class seem in place. But setters are not. Getters and setters serves as one important block in the bridge of efficient programming with java. Put setters for fnum and snum as well

  • In the main class, create a Calculate object using the new operator and the constructor in place.

  • Call the getAnswer() method with the created Calculate object.

Rest of the code looks fine to me. Be modular. You could read your program in a much better way.

Here is my modular piece of code. Two files : Main.java & Calculate.java

Calculate.java

public class Calculate {


private double fn;
private double sn;
private char op;

    public double getFn() {
        return fn;
    }

    public void setFn(double fn) {
        this.fn = fn;
    }

    public double getSn() {
        return sn;
    }

    public void setSn(double sn) {
        this.sn = sn;
    }

    public char getOp() {
        return op;
    }

    public void setOp(char op) {
        this.op = op;
    }



    public Calculate(double fn, double sn, char op) {
        this.fn = fn;
        this.sn = sn;
        this.op = op;
    }


public void getAnswer(){
    double ans;
    switch (getOp()){
        case '+': 
            ans = add(getFn(), getSn());
            ansOutput(ans);
            break;
        case '-': 
            ans = sub (getFn(), getSn());
            ansOutput(ans);
            break;
        case '*': 
            ans = mul (getFn(), getSn());
            ansOutput(ans);
            break;
        case '/': 
            ans = div (getFn(), getSn());
            ansOutput(ans);
            break;
        default:
            System.out.println("--------------------------");
            System.out.println("Invalid choice of operator");
            System.out.println("--------------------------");
        }
    }
    public static double add(double x,double y){
        return x + y;
    }
    public static double sub(double x, double y){
        return x - y;
    }
    public static double mul(double x, double y){
        return x * y;
    }
    public static double div(double x, double y){
        return x / y;
    }

    public static void ansOutput(double x){
        System.out.println("----------- -------");
        System.out.printf("the answer is %.2f\n", x);
        System.out.println("-------------------");
    }
}

Main.java

public class Main {
    public static void main(String args[])
    {
        Calculate obj = new Calculate(1,2,'+');
        obj.getAnswer();
    }
}

What is the Eclipse shortcut for "public static void main(String args[])"?

To get public static void main(String[] args) line in eclipse without typing the whole line type "main" and press Ctrl + space then, you will get the option for the main method select it.

enter image description here

What is the proper declaration of main in C++?

The two valid mains are int main() and int main(int, char*[]). Any thing else may or may not compile. If main doesn't explicitly return a value, 0 is implicitly returned.

C++ Fatal Error LNK1120: 1 unresolved externals

In my particular case, this error error was happening because the file which I've added wasn't referenced at .vcproj file.

What is "String args[]"? parameter in main method Java

in public static void main(String args[]) args is an array of console line argument whose data type is String. in this array, you can store various string arguments by invoking them at the command line as shown below: java myProgram Shaan Royal then Shaan and Royal will be stored in the array as arg[0]="Shaan"; arg[1]="Royal"; you can do this manually also inside the program, when you don't call them at the command line.

What does "Could not find or load main class" mean?

When running the java with the -cp option as advertised in Windows PowerShell you may get an error that looks something like:

The term `ClassName` is not recognized as the name of a cmdlet, function, script ...

In order to for PowerShell to accept the command, the arguments of the -cp option must be contained in quotes as in:

java -cp 'someDependency.jar;.' ClassName

Forming the command this way should allow Java process the classpath arguments correctly.

"Error: Main method not found in class MyClass, please define the main method as..."

The name of the exception suggests that the program tried to call a method that doesn't exist. In this context, it sounds like the program does not have a main method, though it would help if you posted the code that caused the error and the context in which the code was run.

This might have happened if the user tried to run a .class file or a .jar file that has no main method - in Java, the main method is the entry point to begin executing the program.

Normally the compiler is supposed to prevent this from happening so if this does happen, it's usually because the name of the method being called is getting determined ar run-time, rather than compile-time.

To fix this problem, a new programmer must either add the midding method (assuming still that it's main that's missing) or change the method call to the name of a method that does exist.

Read more about the main method here: http://csis.pace.edu/~bergin/KarelJava2ed/ch2/javamain.html

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

Should I return EXIT_SUCCESS or 0 from main()?

Some compilers might create issues with this - on a Mac C++ compiler, EXIT_SUCCESS worked fine for me but on a Linux C++ complier I had to add cstdlib for it to know what EXIT_SUCCESS is. Other than that, they are one and the same.

How to access global variables

I create a file dif.go that contains your code:

package dif

import (
    "time"
)

var StartTime = time.Now()

Outside the folder I create my main.go, it is ok!

package main

import (
    dif "./dif"
    "fmt"
)

func main() {
    fmt.Println(dif.StartTime)
}

Outputs:

2016-01-27 21:56:47.729019925 +0800 CST

Files directory structure:

folder
  main.go
  dif
    dif.go

It works!

What should main() return in C and C++?

The return value for main indicates how the program exited. Normal exit is represented by a 0 return value from main. Abnormal exit is signaled by a non-zero return, but there is no standard for how non-zero codes are interpreted. As noted by others, void main() is prohibited by the C++ standard and should not be used. The valid C++ main signatures are:

int main()

and

int main(int argc, char* argv[])

which is equivalent to

int main(int argc, char** argv)

It is also worth noting that in C++, int main() can be left without a return-statement, at which point it defaults to returning 0. This is also true with a C99 program. Whether return 0; should be omitted or not is open to debate. The range of valid C program main signatures is much greater.

Efficiency is not an issue with the main function. It can only be entered and left once (marking the program's start and termination) according to the C++ standard. For C, re-entering main() is allowed, but should be avoided.

How to convert NSNumber to NSString

Try:

NSString *myString = [NSNumber stringValue];

adding noise to a signal in python

Awesome answers above. I recently had a need to generate simulated data and this is what I landed up using. Sharing in-case helpful to others as well,

import logging
__name__ = "DataSimulator"
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

import numpy as np
import pandas as pd

def generate_simulated_data(add_anomalies:bool=True, random_state:int=42):
    rnd_state = np.random.RandomState(random_state)
    time = np.linspace(0, 200, num=2000)
    pure = 20*np.sin(time/(2*np.pi))

    # concatenate on the second axis; this will allow us to mix different data 
    # distribution
    data = np.c_[pure]
    mu = np.mean(data)
    sd = np.std(data)
    logger.info(f"Data shape : {data.shape}. mu: {mu} with sd: {sd}")
    data_df = pd.DataFrame(data, columns=['Value'])
    data_df['Index'] = data_df.index.values

    # Adding gaussian jitter
    jitter = 0.3*rnd_state.normal(mu, sd, size=data_df.shape[0])
    data_df['with_jitter'] = data_df['Value'] + jitter

    index_further_away = None
    if add_anomalies:
        # As per the 68-95-99.7 rule(also known as the empirical rule) mu+-2*sd 
        # covers 95.4% of the dataset.
        # Since, anomalies are considered to be rare and typically within the 
        # 5-10% of the data; this filtering
        # technique might work 
        #for us(https://en.wikipedia.org/wiki/68%E2%80%9395%E2%80%9399.7_rule)
        indexes_furhter_away = np.where(np.abs(data_df['with_jitter']) > (mu + 
         2*sd))[0]
        logger.info(f"Number of points further away : 
        {len(indexes_furhter_away)}. Indexes: {indexes_furhter_away}")
        # Generate a point uniformly and embed it into the dataset
        random = rnd_state.uniform(0, 5, 1)
        data_df.loc[indexes_furhter_away, 'with_jitter'] +=  
        random*data_df.loc[indexes_furhter_away, 'with_jitter']
    return data_df, indexes_furhter_away

WPF chart controls

Free tools supporting panning / zooming:

Free tools without built in pan / zoom support:

Paid tools with built in pan / zoom support:

Full Disclosure: I have been heavily involved in development of Visiblox, hence I know that library in much more detail than the others.

SCP Permission denied (publickey). on EC2 only when using -r flag on directories

I was initially running:

sudo scp

Once I ran just scp, without sudo, it copied everything fine:

scp

It seems to me that sudo scp command wasn't reading my current user's SSH public key at ~/.ssh/id_rsa.pub.

What is the documents directory (NSDocumentDirectory)?

It can be cleaner to add an extension to FileManager for this kind of awkward call, for tidiness if nothing else. Something like:

extension FileManager {
    static var documentDir : URL {
        return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    }
}

Scroll event listener javascript

I was looking a lot to find a solution for sticy menue with old school JS (without JQuery). So I build small test to play with it. I think it can be helpfull to those looking for solution in js. It needs improvments of unsticking the menue back, and making it more smooth. Also I find a nice solution with JQuery that clones the original div instead of position fixed, its better since the rest of page element dont need to be replaced after fixing. Anyone know how to that with JS ? Please remark, correct and improve.

<!DOCTYPE html>
<html>

<head>
<script>

// addEvent function by John Resig:
// http://ejohn.org/projects/flexible-javascript-events/

function addEvent( obj, type, fn ) {

    if ( obj.attachEvent ) {

        obj['e'+type+fn] = fn;
        obj[type+fn] = function(){obj['e'+type+fn]( window.event );};
        obj.attachEvent( 'on'+type, obj[type+fn] );
    } else {
        obj.addEventListener( type, fn, false );
    }
}
function getScrollY() {
    var  scrOfY = 0;
    if( typeof( window.pageYOffset ) == 'number' ) {
        //Netscape compliant
        scrOfY = window.pageYOffset;

    } else if( document.body && document.body.scrollTop )  {
        //DOM compliant
        scrOfY = document.body.scrollTop;
    } 
    return scrOfY;
}
</script>
<style>
#mydiv {
    height:100px;
    width:100%;
}
#fdiv {
    height:100px;
    width:100%;
}
</style>
</head>

<body>

<!-- HTML for example event goes here -->

<div id="fdiv" style="background-color:red;position:fix">
</div>
<div id="mydiv" style="background-color:yellow">
</div>
<div id="fdiv" style="background-color:green">
</div>

<script>

// Script for example event goes here

addEvent(window, 'scroll', function(event) {

    var x = document.getElementById("mydiv");

    var y = getScrollY();      
    if (y >= 100) {
        x.style.position = "fixed"; 
        x.style.top= "0";
    } 
});

</script>
</body>
</html>

Getting value of selected item in list box as string

If you want to retrieve the display text of the item, use the GetItemText method:

string text = listBox1.GetItemText(listBox1.SelectedItem);

Android Horizontal RecyclerView scroll Direction

Try this in fragment :

layoutManager = new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL,false);

mRecyclerView.setLayoutManager(layoutManager);

Array Size (Length) in C#

You can look at the documentation for Array to find out the answer to this question.

In this particular case you probably need Length:

int sizeOfArray = array.Length;

But since this is such a basic question and you no doubt have many more like this, rather than just telling you the answer I'd rather tell you how to find the answer yourself.

Visual Studio Intellisense

When you type the name of a variable and press the . key it shows you a list of all the methods, properties, events, etc. available on that object. When you highlight a member it gives you a brief description of what it does.

Press F1

If you find a method or property that might do what you want but you're not sure, you can move the cursor over it and press F1 to get help. Here you get a much more detailed description plus links to related information.

Search

The search terms size of array in C# gives many links that tells you the answer to your question and much more. One of the most important skills a programmer must learn is how to find information. It is often faster to find the answer yourself, especially if the same question has been asked before.

Use a tutorial

If you are just beginning to learn C# you will find it easier to follow a tutorial. I can recommend the C# tutorials on MSDN. If you want a book, I'd recommend Essential C#.

Stack Overflow

If you're not able to find the answer on your own, please feel free to post the question on Stack Overflow. But we appreciate it if you show that you have taken the effort to find the answer yourself first.

Parsing a CSV file using NodeJS

Try the line by line npm plugin.

npm install line-by-line --save

How to pass parameter to a promise function

Even shorter

var foo = (user, pass) =>
  new Promise((resolve, reject) => {
    if (/* condition */) {
      resolve("Fine");
    } else {
      reject("Error message");
    }
  });

foo(user, pass).then(result => {
  /* process */
});

Enable remote connections for SQL Server Express 2012

You can also set

Listen All to NO

in the protocol dialog then in the IP address IP1 (say)

set enabled to Yes,

define yr IP address,

set TCP Dynamic to Blank and

TCP port to 1433 (or whatever)

\r\n, \r and \n what is the difference between them?

They are normal symbols as 'a' or '?' or any other. Just (invisible) entries in a string. \r moves cursor to the beginning of the line. \n goes one line down.

As for your replacement, you haven't specified what language you're using, so here's the sketch:

someString.replace("\r\n", "\n").replace("\r", "\n")

How to Set Active Tab in jQuery Ui

You can use this:

$(document).ready(function() {
    $("#tabs").tabs();
    $('#action').click(function() {
        var selected = $("#tabs").tabs("option", "selected");
        $("#tabs").tabs("option", "selected", selected + 1);
    });
});

Also consider changing the input type as button instead of submit unless you want to submit the page.

How can I remove all files in my git repo and update/push from my local git repo?

I was trying to do :

git rm -r *

but at the end for me works :

git rm -r .

I hope it helps to you.

How to truncate float values?

When using a pandas df this worked for me

import math
def truncate(number, digits) -> float:
    stepper = 10.0 ** digits
    return math.trunc(stepper * number) / stepper

df['trunc'] = df['float_val'].apply(lambda x: truncate(x,1))
df['trunc']=df['trunc'].map('{:.1f}'.format)

How to call function on child component on parent events

You can use $emit and $on. Using @RoyJ code:

html:

<div id="app">
  <my-component></my-component>
  <button @click="click">Click</button>  
</div>

javascript:

var Child = {
  template: '<div>{{value}}</div>',
  data: function () {
    return {
      value: 0
    };
  },
  methods: {
    setValue: function(value) {
        this.value = value;
    }
  },
  created: function() {
    this.$parent.$on('update', this.setValue);
  }
}

new Vue({
  el: '#app',
  components: {
    'my-component': Child
  },
  methods: {
    click: function() {
        this.$emit('update', 7);
    }
  }
})

Running example: https://jsfiddle.net/rjurado/m2spy60r/1/

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

Set proxy through windows command line including login parameters

IE can set username and password proxies, so maybe setting it there and import does work

reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyEnable /t REG_DWORD /d 1
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyServer /t REG_SZ /d name:port
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyUser /t REG_SZ /d username
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyPass /t REG_SZ /d password
netsh winhttp import proxy source=ie

What does '?' do in C++?

It's the conditional operator.

a ? b : c

It's a shortcut for IF/THEN/ELSE.

means: if a is true, return b, else return c. In this case, if f==r, return 1, else return 0.

Android studio- "SDK tools directory is missing"

If your SDK tools directory is missing, maybe you deleted it by accident and there is a easy way to download it and guide android studio to it.

First go to android developer site (https://developer.android.com/studio/index.html), scroll to the bottom of the page and chose your download according to system you have(but don't download installer version for windows) you need a zip file which contains SDK.

After you download just put it in my documents (MAC or WINDOWS) and then when you open android studio screen will popup for installing SDK (like the time that you got error), don't click next, go to browse, find that file and press ok. After that go next and it will work like a charm.

That's it.

Row Offset in SQL Server

There is OFFSET .. FETCH in SQL Server 2012, but you will need to specify an ORDER BY column.

If you really don't have any explicit column that you could pass as an ORDER BY column (as others have suggested), then you can use this trick:

SELECT * FROM MyTable 
ORDER BY @@VERSION 
OFFSET 50 ROWS FETCH NEXT 25 ROWS ONLY

... or

SELECT * FROM MyTable 
ORDER BY (SELECT 0)
OFFSET 50 ROWS FETCH NEXT 25 ROWS ONLY

We're using it in jOOQ when users do not explicitly specify an order. This will then produce pretty random ordering without any additional costs.

Set disable attribute based on a condition for Html.TextBoxFor

The valid way is:

disabled="disabled"

Browsers also might accept disabled="" but I would recommend you the first approach.

Now this being said I would recommend you writing a custom HTML helper in order to encapsulate this disabling functionality into a reusable piece of code:

using System;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;

public static class HtmlExtensions
{
    public static IHtmlString MyTextBoxFor<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper, 
        Expression<Func<TModel, TProperty>> expression, 
        object htmlAttributes, 
        bool disabled
    )
    {
        var attributes = new RouteValueDictionary(htmlAttributes);
        if (disabled)
        {
            attributes["disabled"] = "disabled";
        }
        return htmlHelper.TextBoxFor(expression, attributes);
    }
}

which you could use like this:

@Html.MyTextBoxFor(
    model => model.ExpireDate, 
    new { 
        style = "width: 70px;", 
        maxlength = "10", 
        id = "expire-date" 
    }, 
    Model.ExpireDate == null
)

and you could bring even more intelligence into this helper:

public static class HtmlExtensions
{
    public static IHtmlString MyTextBoxFor<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TProperty>> expression,
        object htmlAttributes
    )
    {
        var attributes = new RouteValueDictionary(htmlAttributes);
        var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        if (metaData.Model == null)
        {
            attributes["disabled"] = "disabled";
        }
        return htmlHelper.TextBoxFor(expression, attributes);
    }
}

so that now you no longer need to specify the disabled condition:

@Html.MyTextBoxFor(
    model => model.ExpireDate, 
    new { 
        style = "width: 70px;", 
        maxlength = "10", 
        id = "expire-date" 
    }
)

The type or namespace name 'DbContext' could not be found

Right click your reference and go to manage NuGet packages, then choose online all, then NuGet package source in the search textbox type Entity Framework and install it.

Run exe file with parameters in a batch file

Unless it's just a simplified example for the question, my advice is that drop the batch wrapper and schedule PHP directly, more specifically the php-win.exe program, which won't open unnecessary windows.

Program: c:\program files\php\php-win.exe
Arguments: D:\mydocs\mp\index.php param1 param2

Otherwise, just quote stuff as Andrew points out.


In older versions of Windows, you should be able to put everything in the single "Run" text box (as long as you quote everything that has spaces):

"c:\program files\php\php-win.exe" D:\mydocs\mp\index.php param1 param2

Resize a large bitmap file to scaled output file on Android

This is 'Mojo Risin's and 'Ofir's solutions "combined". This will give you a proportionally resized image with the boundaries of max width and max height.

  1. It only reads meta data to get the original size (options.inJustDecodeBounds)
  2. It uses a rought resize to save memory (itmap.createScaledBitmap)
  3. It uses a precisely resized image based on the rough Bitamp created earlier.

For me it has been performing fine on 5 MegaPixel images an below.

try
{
    int inWidth = 0;
    int inHeight = 0;

    InputStream in = new FileInputStream(pathOfInputImage);

    // decode image size (decode metadata only, not the whole image)
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(in, null, options);
    in.close();
    in = null;

    // save width and height
    inWidth = options.outWidth;
    inHeight = options.outHeight;

    // decode full image pre-resized
    in = new FileInputStream(pathOfInputImage);
    options = new BitmapFactory.Options();
    // calc rought re-size (this is no exact resize)
    options.inSampleSize = Math.max(inWidth/dstWidth, inHeight/dstHeight);
    // decode full image
    Bitmap roughBitmap = BitmapFactory.decodeStream(in, null, options);

    // calc exact destination size
    Matrix m = new Matrix();
    RectF inRect = new RectF(0, 0, roughBitmap.getWidth(), roughBitmap.getHeight());
    RectF outRect = new RectF(0, 0, dstWidth, dstHeight);
    m.setRectToRect(inRect, outRect, Matrix.ScaleToFit.CENTER);
    float[] values = new float[9];
    m.getValues(values);

    // resize bitmap
    Bitmap resizedBitmap = Bitmap.createScaledBitmap(roughBitmap, (int) (roughBitmap.getWidth() * values[0]), (int) (roughBitmap.getHeight() * values[4]), true);

    // save image
    try
    {
        FileOutputStream out = new FileOutputStream(pathOfOutputImage);
        resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
    }
    catch (Exception e)
    {
        Log.e("Image", e.getMessage(), e);
    }
}
catch (IOException e)
{
    Log.e("Image", e.getMessage(), e);
}

Getting the Username from the HKEY_USERS values

By searching for my userid in the registry, I found

HKEY_CURRENT_USER\Volatile Environment\Username

Is there a way to list open transactions on SQL Server 2000 database?

For all databases query sys.sysprocesses

SELECT * FROM sys.sysprocesses WHERE open_tran = 1

For the current database use:

DBCC OPENTRAN

regex match any whitespace

The reason I used a + instead of a '*' is because a plus is defined as one or more of the preceding element, where an asterisk is zero or more. In this case we want a delimiter that's a little more concrete, so "one or more" spaces.

word[Aa]\s+word[Bb]\s+word[Cc]

will match:

wordA wordB     wordC
worda wordb wordc
wordA   wordb   wordC

The words, in this expression, will have to be specific, and also in order (a, b, then c)

How do I mock a REST template exchange?

This is an example with the non deprecated ArgumentMatchers class

when(restTemplate.exchange(
                ArgumentMatchers.anyString(),
                ArgumentMatchers.any(HttpMethod.class),
                ArgumentMatchers.any(),
                ArgumentMatchers.<Class<String>>any()))
             .thenReturn(responseEntity);

Regular cast vs. static_cast vs. dynamic_cast

Static cast

The static cast performs conversions between compatible types. It is similar to the C-style cast, but is more restrictive. For example, the C-style cast would allow an integer pointer to point to a char.
char c = 10;       // 1 byte
int *p = (int*)&c; // 4 bytes

Since this results in a 4-byte pointer pointing to 1 byte of allocated memory, writing to this pointer will either cause a run-time error or will overwrite some adjacent memory.

*p = 5; // run-time error: stack corruption

In contrast to the C-style cast, the static cast will allow the compiler to check that the pointer and pointee data types are compatible, which allows the programmer to catch this incorrect pointer assignment during compilation.

int *q = static_cast<int*>(&c); // compile-time error

Reinterpret cast

To force the pointer conversion, in the same way as the C-style cast does in the background, the reinterpret cast would be used instead.

int *r = reinterpret_cast<int*>(&c); // forced conversion

This cast handles conversions between certain unrelated types, such as from one pointer type to another incompatible pointer type. It will simply perform a binary copy of the data without altering the underlying bit pattern. Note that the result of such a low-level operation is system-specific and therefore not portable. It should be used with caution if it cannot be avoided altogether.

Dynamic cast

This one is only used to convert object pointers and object references into other pointer or reference types in the inheritance hierarchy. It is the only cast that makes sure that the object pointed to can be converted, by performing a run-time check that the pointer refers to a complete object of the destination type. For this run-time check to be possible the object must be polymorphic. That is, the class must define or inherit at least one virtual function. This is because the compiler will only generate the needed run-time type information for such objects.

Dynamic cast examples

In the example below, a MyChild pointer is converted into a MyBase pointer using a dynamic cast. This derived-to-base conversion succeeds, because the Child object includes a complete Base object.

class MyBase 
{ 
  public:
  virtual void test() {}
};
class MyChild : public MyBase {};



int main()
{
  MyChild *child = new MyChild();
  MyBase  *base = dynamic_cast<MyBase*>(child); // ok
}

The next example attempts to convert a MyBase pointer to a MyChild pointer. Since the Base object does not contain a complete Child object this pointer conversion will fail. To indicate this, the dynamic cast returns a null pointer. This gives a convenient way to check whether or not a conversion has succeeded during run-time.

MyBase  *base = new MyBase();
MyChild *child = dynamic_cast<MyChild*>(base);

 
if (child == 0) 
std::cout << "Null pointer returned";

If a reference is converted instead of a pointer, the dynamic cast will then fail by throwing a bad_cast exception. This needs to be handled using a try-catch statement.

#include <exception>
// …  
try
{ 
  MyChild &child = dynamic_cast<MyChild&>(*base);
}
catch(std::bad_cast &e) 
{ 
  std::cout << e.what(); // bad dynamic_cast
}

Dynamic or static cast

The advantage of using a dynamic cast is that it allows the programmer to check whether or not a conversion has succeeded during run-time. The disadvantage is that there is a performance overhead associated with doing this check. For this reason using a static cast would have been preferable in the first example, because a derived-to-base conversion will never fail.

MyBase *base = static_cast<MyBase*>(child); // ok

However, in the second example the conversion may either succeed or fail. It will fail if the MyBase object contains a MyBase instance and it will succeed if it contains a MyChild instance. In some situations this may not be known until run-time. When this is the case dynamic cast is a better choice than static cast.

// Succeeds for a MyChild object
MyChild *child = dynamic_cast<MyChild*>(base);

If the base-to-derived conversion had been performed using a static cast instead of a dynamic cast the conversion would not have failed. It would have returned a pointer that referred to an incomplete object. Dereferencing such a pointer can lead to run-time errors.

// Allowed, but invalid
MyChild *child = static_cast<MyChild*>(base);
 
// Incomplete MyChild object dereferenced
(*child);

Const cast

This one is primarily used to add or remove the const modifier of a variable.

const int myConst = 5;
int *nonConst = const_cast<int*>(&myConst); // removes const

Although const cast allows the value of a constant to be changed, doing so is still invalid code that may cause a run-time error. This could occur for example if the constant was located in a section of read-only memory.

*nonConst = 10; // potential run-time error

Const cast is instead used mainly when there is a function that takes a non-constant pointer argument, even though it does not modify the pointee.

void print(int *p) 
{
   std::cout << *p;
}

The function can then be passed a constant variable by using a const cast.

print(&myConst); // error: cannot convert 
                 // const int* to int*
 
print(nonConst); // allowed

Source and More Explanations

Excel: How to check if a cell is empty with VBA?

This site uses the method isEmpty().

Edit: content grabbed from site, before the url will going to be invalid.

Worksheets("Sheet1").Range("A1").Sort _
    key1:=Worksheets("Sheet1").Range("A1")
Set currentCell = Worksheets("Sheet1").Range("A1")
Do While Not IsEmpty(currentCell)
    Set nextCell = currentCell.Offset(1, 0)
    If nextCell.Value = currentCell.Value Then
        currentCell.EntireRow.Delete
    End If
    Set currentCell = nextCell
Loop

In the first step the data in the first column from Sheet1 will be sort. In the second step, all rows with same data will be removed.

How to set a variable to be "Today's" date in Python/Pandas

Easy solution in Python3+:

import time


todaysdate = time.strftime("%d/%m/%Y")

#with '.' isntead of '/'
todaysdate = time.strftime("%d.%m.%Y")

Input Type image submit form value?

Solution:

<form name="frmSeguimiento" id="frmSeguimiento" method="post" action="proc_seguimiento.php">  
    <input type="hidden" name="accion" id="accion"/>


<input name="save" type="image" src="imagenes/save.png" alt="Save" onmouseover="this.src='imagenes/save_over.png';" onmouseout="this.src='imagenes/save.png';" value="Save" onclick="validaFrmSeguimiento(this.value);"/>


function validaFrmSeguimiento(accion)
{
    document.frmSeguimiento.accion.value=accion;

}

Regards, jp

How to add a ScrollBar to a Stackpanel

It works like this:

<ScrollViewer VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Disabled" Width="340" HorizontalAlignment="Left" Margin="12,0,0,0">
        <StackPanel Name="stackPanel1" Width="311">

        </StackPanel>
</ScrollViewer>

TextBox tb = new TextBox();
tb.TextChanged += new TextChangedEventHandler(TextBox_TextChanged);
stackPanel1.Children.Add(tb);

'^M' character at end of lines

od -a $file is useful to explore those types of question on Linux (similar to dumphex in the above).

Extract substring from a string

The best way to get substring in Android is using (as @user2503849 said) TextUtlis.substring(CharSequence, int, int) method. I can explain why. If you will take a look at the String.substring(int, int) method from android.jar (newest API 22), you will see:

public String substring(int start) {
    if (start == 0) {
        return this;
    }
    if (start >= 0 && start <= count) {
        return new String(offset + start, count - start, value);
    }
    throw indexAndLength(start);
}

Ok, than... How do you think the private constructor String(int, int, char[]) looks like?

String(int offset, int charCount, char[] chars) {
    this.value = chars;
    this.offset = offset;
    this.count = charCount;
}

As we can see it keeps reference to the "old" value char[] array. So, the GC can not free it.

In the newest Java it was fixed:

String(int offset, int charCount, char[] chars) {
    this.value = Arrays.copyOfRange(chars, offset, offset + charCount);
    this.offset = offset;
    this.count = charCount;
}

Arrays.copyOfRange(...) uses native array copying inside.

That's it :)

Best regards!

Angular 2 optional route parameter

With angular4 we just need to organise routes together in hierarchy

const appRoutes: Routes = [
  { 
    path: '', 
    component: MainPageComponent 
  },
  { 
    path: 'car/details', 
    component: CarDetailsComponent 
  },
  { 
    path: 'car/details/platforms-products', 
    component: CarProductsComponent 
  },
  { 
    path: 'car/details/:id', 
    component: CadDetailsComponent 
  },
  { 
    path: 'car/details/:id/platforms-products', 
    component: CarProductsComponent 
  }
];

This works for me . This way router know what is the next route based on option id parameters.

how to add <script>alert('test');</script> inside a text box?

JQuery version:

$('yourInputSelectorHere').val("<script>alert('test');<\/script>")

Delete rows from multiple tables using a single query (SQL Express 2005) with a WHERE condition

$qry = "DELETE lg., l. FROM lessons_game lg RIGHT JOIN lessons l ON lg.lesson_id = l.id WHERE l.id = ?";

lessons is Main table and lessons_game is subtable so Right Join

Best way to check if an PowerShell Object exist?

You can also do

if ($ie) {
    # Do Something if $ie is not null
}

add elements to object array

I know this is old, but came across it looking for a simpler way, and this is how i do it, just create a new list of the same object and add it to the one you want to use e.g.

Subject[] subjectsList = {new Subject1{....}, new Subject2{....}, new Subject3{....}} 
univStudent.subjects = subjectsList ;

Form inside a form, is that alright?

Form nesting can be achieved with new HTML5 input element's form attribute. Although we don't nest forms structurally, inputs are evaluated as they are in their own form. In my tests, 3 major browsers support this except IE(IE11). Form nesting limitation was a big obstacle for HTML UI design.

Here is a sample code, when you click Save button you should see "2 3 success" (Original http://www.impressivewebs.com/html5-form-attribute/):

<form id="saveForm" action="/post/dispatch/save" method="post"></form>
<form id="deleteForm" action="/post/dispatch/delete" method="post"></form>

<div id="toolbar">
    <input type="text" name="foo" form="saveForm" />
    <input type="hidden" value="some_id" form="deleteForm" />
    <input type="text" name="foo2" id="foo2" form="saveForm" value="success" />

    <input type="submit" name="save" value="Save" form="saveForm" onclick="alert(document.getElementById('deleteForm').elements.length + ' ' + document.getElementById('saveForm').elements.length + ' ' + document.getElementById('saveForm').elements['foo2'].value);return false;" />
    <input type="submit" name="delete" value="Delete" form="deleteForm" />
    <a href="/home/index">Cancel</a>
</div>

What is the difference between a static method and a non-static method?

Basic difference is non static members are declared with out using the keyword 'static'

All the static members (both variables and methods) are referred with the help of class name. Hence the static members of class are also called as class reference members or class members..

In order to access the non static members of a class we should create reference variable . reference variable store an object..

how do I change text in a label with swift?

Swift uses the same cocoa-touch API. You can call all the same methods, but they will use Swift's syntax. In this example you can do something like this:

self.simpleLabel.text = "message"

Note the setText method isn't available. Setting the label's text with = will automatically call the setter in swift.

How can I remove a character from a string using JavaScript?

The shortest way would be to use splice

var inputString = "abc";
// convert to array and remove 1 element at position 4 and save directly to the array itself
let result = inputString.split("").splice(3, 1).join();
console.log(result);

How to call webmethod in Asp.net C#

The problem is at [System.Web.Services.WebMethod], add [WebMethod(EnableSession = false)] and you could get rid of page life cycle, by default EnableSession is true in Page and making page to come in life though life cycle events..

Please refer below page for more details http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.enablesessionstate.aspx

LaTex left arrow over letter in math mode

Use \overleftarrow to create a long arrow to the left.

\overleftarrow{blahblahblah}

LaTeX output

Unable to resolve host "<insert URL here>" No address associated with hostname

My bet is that you forgot to give your app the permission to use the internet. Try adding this to your android manifest:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

syntax error: unexpected token <

Just gonna throw this in here since I encountered the same error but for VERY different reasons.

I'm serving via node/express/jade and had ported an old jade file over. One of the lines was to not bork when Typekit failed:

script(type='text/javascript')
  try{Typekit.load();}catch(e){}

It seemed innocuous enough, but I finally realized that for jade script blocks where you're adding content you need a .:

script(type='text/javascript').
  try{Typekit.load();}catch(e){}

Simple, but tricky.

Faster way to zero memory than with memset?

Unless you have specific needs or know that your compiler/stdlib is sucky, stick with memset. It's general-purpose, and should have decent performance in general. Also, compilers might have an easier time optimizing/inlining memset() because it can have intrinsic support for it.

For instance, Visual C++ will often generate inline versions of memcpy/memset that are as small as a call to the library function, thus avoiding push/call/ret overhead. And there's further possible optimizations when the size parameter can be evaluated at compile-time.

That said, if you have specific needs (where size will always be tiny *or* huge), you can gain speed boosts by dropping down to assembly level. For instance, using write-through operations for zeroing huge chunks of memory without polluting your L2 cache.

But it all depends - and for normal stuff, please stick to memset/memcpy :)

Error:attempt to apply non-function

I got the error because of a clumsy typo:

This errors:

knitr::opts_chunk$seet(echo = FALSE)

Error: attempt to apply non-function

After correcting the typo, it works:

knitr::opts_chunk$set(echo = FALSE)

How to extract filename.tar.gz file

It happens sometimes for the files downloaded with "wget" command. Just 10 minutes ago, I was trying to install something to server from the command screen and the same thing happened. As a solution, I just downloaded the .tar.gz file to my machine from the web then uploaded it to the server via FTP. After that, the "tar" command worked as it was expected.

Python Socket Multiple Clients

This program will open 26 sockets where you would be able to connect a lot of TCP clients to it.

#!usr/bin/python
from thread import *
import socket
import sys

def clientthread(conn):
    buffer=""
    while True:
        data = conn.recv(8192)
        buffer+=data
        print buffer
    #conn.sendall(reply)
    conn.close()

def main():
    try:
        host = '192.168.1.3'
        port = 6666
        tot_socket = 26
        list_sock = []
        for i in range(tot_socket):
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
            s.bind((host, port+i))
            s.listen(10)
            list_sock.append(s)
            print "[*] Server listening on %s %d" %(host, (port+i))

        while 1:
            for j in range(len(list_sock)):
                conn, addr = list_sock[j].accept()
                print '[*] Connected with ' + addr[0] + ':' + str(addr[1])
                start_new_thread(clientthread ,(conn,))
        s.close()

    except KeyboardInterrupt as msg:
        sys.exit(0)


if __name__ == "__main__":
    main()

delete all record from table in mysql

It’s because you tried to update a table without a WHERE that uses a KEY column.

The quick fix is to add SET SQL_SAFE_UPDATES=0; before your query :

SET SQL_SAFE_UPDATES=0; 

Or

close the safe update mode. Edit -> Preferences -> SQL Editor -> SQL Editor remove Forbid UPDATE and DELETE statements without a WHERE clause (safe updates) .

BTW you can use TRUNCATE TABLE tablename; to delete all the records .

How do I find out which keystore was used to sign an app?

First, unzip the APK and extract the file /META-INF/ANDROID_.RSA (this file may also be CERT.RSA, but there should only be one .RSA file).

Then issue this command:

keytool -printcert -file ANDROID_.RSA

You will get certificate fingerprints like this:

     MD5:  B3:4F:BE:07:AA:78:24:DC:CA:92:36:FF:AE:8C:17:DB
     SHA1: 16:59:E7:E3:0C:AA:7A:0D:F2:0D:05:20:12:A8:85:0B:32:C5:4F:68
     Signature algorithm name: SHA1withRSA

Then use the keytool again to print out all the aliases of your signing keystore:

keytool -list -keystore my-signing-key.keystore

You will get a list of aliases and their certificate fingerprint:

android_key, Jan 23, 2010, PrivateKeyEntry,
Certificate fingerprint (MD5): B3:4F:BE:07:AA:78:24:DC:CA:92:36:FF:AE:8C:17:DB

Voila! we can now determined the apk has been signed with this keystore, and with the alias 'android_key'.

Keytool is part of Java, so make sure your PATH has Java installation dir in it.

How to prevent a click on a '#' link from jumping to top of page?

If you want to migrate to an Anchor Section on the same page without page jumping up use:

Just use "#/" instead of "#" e.g

<a href="#/home">Home</a>
<a href="#/about">About</a>
<a href="#/contact">contact</a> page will not jump up on click..

How can I check if a var is a string in JavaScript?

Combining the previous answers provides these solutions:

if (typeof str == 'string' || str instanceof String)

or

Object.prototype.toString.call(str) == '[object String]'

How to pass a parameter to routerLink that is somewhere inside the URL?

Maybe it is really late answer but if you want to navigate another page with param you can,

[routerLink]="['/user', user.id, 'details']"

also you shouldn't forget about routing config like ,

 [path: 'user/:id/details', component:userComponent, pathMatch: 'full']

Parser Error when deploy ASP.NET application

Very old question here, but I ran into the same error and none of the provided answers solved the issue.

My issue occurred because I manually changed the namespace and assembly names of the project after initial creation. Took me a little bit to notice that the namespace in the Inherits attribute didn't match the updated namespace.

Updating that namespace in the Global.asax markup to match the apps namespace fixed the error for me.

Read the current full URL with React?

To get the current router instance or current location you have to create a Higher order component with withRouter from react-router-dom. otherwise, when you are trying to access this.props.location it will return undefined

Example

import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';

class className extends Component {

      render(){
           return(
                ....
                  )
              }
}

export default withRouter(className)

What is a "web service" in plain English?

Web services are almost like normal a web page. The difference is that they are formatted to make it very easy for a program to pull data from the page, to the point of probably not using any HTML. They generally also are more reliable as to the consistency of the format, may use a different formal process to define the content such soap or raw xml, and there is often also a descriptor document that formally defines the structure for the data.

How to check if array is not empty?

I can't comment yet, but it should be mentioned that if you use numpy array with more than one element this will fail:

if l:
    print "list has items"

elif not l:
    print "list is empty"

the error will be:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Error when creating a new text file with python?

You can use open(name, 'a')

However, when you enter filename, use inverted commas on both sides, otherwise ".txt"cannot be added to filename

How to read a list of files from a folder using PHP?

This is what I like to do:

$files = array_values(array_filter(scandir($path), function($file) use ($path) { 
    return !is_dir($path . '/' . $file);
}));

foreach($files as $file){
    echo $file;
}

How to write "not in ()" sql query using join

SELECT d1.Short_Code 
FROM domain1 d1
LEFT JOIN domain2 d2
ON d1.Short_Code = d2.Short_Code
WHERE d2.Short_Code IS NULL

An efficient way to transpose a file in Bash

Another bash variant

$ cat file 
XXXX    col1    col2    col3
row1    0       1       2
row2    3       4       5
row3    6       7       8
row4    9       10      11

Script

#!/bin/bash

I=0
while read line; do
    i=0
    for item in $line; { printf -v A$I[$i] $item; ((i++)); }
    ((I++))
done < file
indexes=$(seq 0 $i)

for i in $indexes; {
    J=0
    while ((J<I)); do
        arr="A$J[$i]"
        printf "${!arr}\t"
        ((J++))
    done
    echo
}

Output

$ ./test 
XXXX    row1    row2    row3    row4    
col1    0       3       6       9   
col2    1       4       7       10  
col3    2       5       8       11

How do I unlock a SQLite database?

I had the same problem. Apparently the rollback function seems to overwrite the db file with the journal which is the same as the db file but without the most recent change. I've implemented this in my code below and it's been working fine since then, whereas before my code would just get stuck in the loop as the database stayed locked.

Hope this helps

my python code

##############
#### Defs ####
##############
def conn_exec( connection , cursor , cmd_str ):
    done        = False
    try_count   = 0.0
    while not done:
        try:
            cursor.execute( cmd_str )
            done = True
        except sqlite.IntegrityError:
            # Ignore this error because it means the item already exists in the database
            done = True
        except Exception, error:
            if try_count%60.0 == 0.0:       # print error every minute
                print "\t" , "Error executing command" , cmd_str
                print "Message:" , error

            if try_count%120.0 == 0.0:      # if waited for 2 miutes, roll back
                print "Forcing Unlock"
                connection.rollback()

            time.sleep(0.05)    
            try_count += 0.05


def conn_comit( connection ):
    done        = False
    try_count   = 0.0
    while not done:
        try:
            connection.commit()
            done = True
        except sqlite.IntegrityError:
            # Ignore this error because it means the item already exists in the database
            done = True
        except Exception, error:
            if try_count%60.0 == 0.0:       # print error every minute
                print "\t" , "Error executing command" , cmd_str
                print "Message:" , error

            if try_count%120.0 == 0.0:      # if waited for 2 miutes, roll back
                print "Forcing Unlock"
                connection.rollback()

            time.sleep(0.05)    
            try_count += 0.05       




##################
#### Run Code ####
##################
connection = sqlite.connect( db_path )
cursor = connection.cursor()
# Create tables if database does not exist
conn_exec( connection , cursor , '''CREATE TABLE IF NOT EXISTS fix (path TEXT PRIMARY KEY);''')
conn_exec( connection , cursor , '''CREATE TABLE IF NOT EXISTS tx (path TEXT PRIMARY KEY);''')
conn_exec( connection , cursor , '''CREATE TABLE IF NOT EXISTS completed (fix DATE, tx DATE);''')
conn_comit( connection )

Laravel: PDOException: could not find driver

ERROR: could not find driver (SQL: select * from tests where slug = a limit 1)

I was getting the above error in my laravel project, i am using nginx server on ubuntu 16.04

This error is because, php-mysql driver is missing. To install it type following command.

sudo apt-get install php7.2-mysql

Please specify your current php version in above command.

Open php.ini file and uncomment the followling line of code(Remove Semicolon).

;extension=pdo_mysql

Then Restart the nginx and php service

sudo systemctl restart php7.2-fpm
sudo systemctl restart nginx

It worked for me.

Get file content from URL?

Use file_get_contents in combination with json_decode and echo.

Design DFA accepting binary strings divisible by a number 'n'

I know I am quite late, but I just wanted to add a few things to the already correct answer provided by @Grijesh. I'd like to just point out that the answer provided by @Grijesh does not produce the minimal DFA. While the answer surely is the right way to get a DFA, if you need the minimal DFA you will have to look into your divisor.

Like for example in binary numbers, if the divisor is a power of 2 (i.e. 2^n) then the minimum number of states required will be n+1. How would you design such an automaton? Just see the properties of binary numbers. For a number, say 8 (which is 2^3), all its multiples will have the last 3 bits as 0. For example, 40 in binary is 101000. Therefore for a language to accept any number divisible by 8 we just need an automaton which sees if the last 3 bits are 0, which we can do in just 4 states instead of 8 states. That's half the complexity of the machine.

In fact, this can be extended to any base. For a ternary base number system, if for example we need to design an automaton for divisibility with 9, we just need to see if the last 2 numbers of the input are 0. Which can again be done in just 3 states.

Although if the divisor isn't so special, then we need to go through with @Grijesh's answer only. Like for example, in a binary system if we take the divisors of 3 or 7 or maybe 21, we will need to have that many number of states only. So for any odd number n in a binary system, we need n states to define the language which accepts all multiples of n. On the other hand, if the number is even but not a power of 2 (only in case of binary numbers) then we need to divide the number by 2 till we get an odd number and then we can find the minimum number of states by adding the odd number produced and the number of times we divided by 2.

For example, if we need to find the minimum number of states of a DFA which accepts all binary numbers divisible by 20, we do :

20/2 = 10 
10/2 = 5

Hence our answer is 5 + 1 + 1 = 7. (The 1 + 1 because we divided the number 20 twice).

%matplotlib line magic causes SyntaxError in Python script

The syntax '%' in %matplotlib inline is recognized by iPython (where it is set up to handle the magic methods), but not Python itself, which gives a SyntaxError. Here is given one solution.

Change Image of ImageView programmatically in Android

Short answer

Just copy an image into your res/drawable folder and use

imageView.setImageResource(R.drawable.my_image);

Details

The variety of answers can cause a little confusion. We have

The methods with Background in their name all belong to the View class, not to ImageView specifically. But since ImageView inherits from View you can use them, too. The methods with Image in their name belong specifically to ImageView.

The View methods all do the same thing as each other (though setBackgroundDrawable() is deprecated), so we will just focus on setBackgroundResource(). Similarly, the ImageView methods all do the same thing, so we will just focus on setImageResource(). The only difference between the methods is they type of parameter you pass in.

Setup

Here is a FrameLayout that contains an ImageView. The ImageView initially doesn't have any image in it. (I only added the FrameLayout so that I could put a border around it. That way you can see the edge of the ImageView.)

enter image description here

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/frameLayout"
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:background="@drawable/border"
        android:layout_centerInParent="true">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

    </FrameLayout>
</RelativeLayout>

Below we will compare the different methods.

setImageResource()

If you use ImageView's setImageResource(), then the image keeps its aspect ratio and is resized to fit. Here are two different image examples.

  • imageView.setImageResource(R.drawable.sky);
  • imageView.setImageResource(R.drawable.balloons);

enter image description here

setBackgroundResource()

Using View's setBackgroundResource(), on the other hand, causes the image resource to be stretched to fill the view.

  • imageView.setBackgroundResource(R.drawable.sky);
  • imageView.setBackgroundResource(R.drawable.balloons);

enter image description here

Both

The View's background image and the ImageView's image are drawn separately, so you can set them both.

imageView.setBackgroundResource(R.drawable.sky);
imageView.setImageResource(R.drawable.balloons);

enter image description here

Javascript to convert UTC to local time

Try:

var date = new Date('2012-11-29 17:00:34 UTC');
date.toString();

How to open a specific port such as 9090 in Google Compute Engine

You'll need to add a firewall rule to open inbound access to tcp:9090 to your instances. If you have more than the two instances, and you only want to open 9090 to those two, you'll want to make sure that there is a tag that those two instances share. You can add or update tags via the console or the command-line; I'd recommend using the GUI for that if needed because it handles the read-modify-write cycle with setinstancetags.

If you want to open port 9090 to all instances, you can create a firewall rule like:

gcutil addfirewall allow-9090 --allowed=tcp:9090

which will apply to all of your instances.

If you only want to open port 9090 to the two instances that are serving your application, make sure that they have a tag like my-app, and then add a firewall like so:

gcutil addfirewall my-app-9090 --allowed=tcp:9090 --target_tags=my-app

You can read more about creating and managing firewalls in GCE here.

How can I check if my python object is a number?

Use Number from the numbers module to test isinstance(n, Number) (available since 2.6).

isinstance(n, numbers.Number)

Here it is in action with various kinds of numbers and one non-number:

>>> from numbers import Number
... from decimal import Decimal
... from fractions import Fraction
... for n in [2, 2.0, Decimal('2.0'), complex(2,0), Fraction(2,1), '2']:
...     print '%15s %s' % (n.__repr__(), isinstance(n, Number))
              2 True
            2.0 True
 Decimal('2.0') True
         (2+0j) True
 Fraction(2, 1) True
            '2' False

This is, of course, contrary to duck typing. If you are more concerned about how an object acts rather than what it is, perform your operations as if you have a number and use exceptions to tell you otherwise.

SQL Server Operating system error 5: "5(Access is denied.)"

For me it was solved in the following way with SQL Server Management studio -Log in as admin (I logged in as windows authentication) -Attach the mdf file (right click Database | attach | Add ) -Log out as admin -Log in as normal user

Difference between xcopy and robocopy

I have written lot of scripts to automate daily backups etc. Previously I used XCopy and then moved to Robocopy. Anyways Robocopy and XCopy both are frequently used in terms of file transfers in Windows. Robocopy stands for Robust File Copy. All type of huge file copying both these commands are used but Robocopy has added options which makes copying easier as well as for debugging purposes.

Having said that lets talk about features between these two.

  • Robocopy becomes handy for mirroring or synchronizing directories. It also checks the files in the destination directory against the files to be copied and doesn't waste time copying unchanged files.

  • Just like myself, if you are into automation to take daily backups etc, "Run Hours - /RH" becomes very useful without any interactions. This is supported by Robocopy. It allows you to set when copies should be done rather than the time of the command as with XCopy. You will see robocopy.exe process in task list since it will run background to monitor clock to execute when time is right to copy.

  • Robocopy supports file and directory monitoring with the "/MON" or "/MOT" commands.

  • Robocopy gives extra support for copying over the "archive" attribute on files, it supports copying over all attributes including timestamps, security, owner, and auditing information.

Hope this helps you.

How to stop VBA code running?

Add another button called "CancelButton" that sets a flag, and then check for that flag.

If you have long loops in the "stuff" then check for it there too and exit if it's set. Use DoEvents inside long loops to ensure that the UI works.

Bool Cancel
Private Sub CancelButton_OnClick()
    Cancel=True
End Sub
...
Private Sub SomeVBASub
    Cancel=False
    DoStuff
    If Cancel Then Exit Sub
    DoAnotherStuff
    If Cancel Then Exit Sub
    AndFinallyDothis
End Sub

rails 3 validation on uniqueness on multiple attributes

Dont work for me, need to put scope in plural

validates_uniqueness_of :teacher_id, :scopes => [:semester_id, :class_id]

How to handle authentication popup with Selenium WebDriver using Java

Try following solution and let me know in case of any issues:

driver.get('https://example.com/')
driver.switchTo().alert().sendKeys("username" + Keys.TAB + "password");
driver.switchTo().alert().accept();

This is working fine for me

How to ignore the first line of data when processing CSV data?

The documentation for the Python 3 CSV module provides this example:

with open('example.csv', newline='') as csvfile:
    dialect = csv.Sniffer().sniff(csvfile.read(1024))
    csvfile.seek(0)
    reader = csv.reader(csvfile, dialect)
    # ... process CSV file contents here ...

The Sniffer will try to auto-detect many things about the CSV file. You need to explicitly call its has_header() method to determine whether the file has a header line. If it does, then skip the first row when iterating the CSV rows. You can do it like this:

if sniffer.has_header():
    for header_row in reader:
        break
for data_row in reader:
    # do something with the row

Read XLSX file in Java

docx4j now covers xlsx as well.

"Why would you use docx4j to do this", I hear you ask, "rather than POI, which focuses on xlsx and binary xls?"

Probably because you like JAXB (as opposed to XML Beans), or you are already using docx4j for docx or pptx, and need to be able to do some stuff with xlsx as well.

Another possible reason is that the jar XML Beans generates from the OpenXML schemas is too big for your purposes. (To get around this, POI offers a 'lite' subset: the 'big' ooxml-schemas-1.0.jar is 14.5 MB! But if you need to support arbitrary spreadsheets, you'll probably need the complete jar). In contrast, the whole of docx4j/pptx4j/xlsx4j weighs in at about the same as POI's lite subset.

If you are processing spreadsheets only (ie not docx or pptx), and preceding paragraph is not a concern for you, then you would probably be best off using POI.

How to implement if-else statement in XSLT?

You have to reimplement it using <xsl:choose> tag:

       <xsl:choose>
         <xsl:when test="$CreatedDate > $IDAppendedDate">
           <h2> mooooooooooooo </h2>
         </xsl:when>
         <xsl:otherwise>
          <h2> dooooooooooooo </h2>
         </xsl:otherwise>
       </xsl:choose>

Key existence check in HashMap

Do you mean that you've got code like

if(map.containsKey(key)) doSomethingWith(map.get(key))

all over the place ? Then you should simply check whether map.get(key) returned null and that's it. By the way, HashMap doesn't throw exceptions for missing keys, it returns null instead. The only case where containsKey is needed is when you're storing null values, to distinguish between a null value and a missing value, but this is usually considered bad practice.

How can moment.js be imported with typescript?

You need to import moment() the function and Moment the class separately in TS.

I found a note in the typescript docs here.

/*~ Note that ES6 modules cannot directly export callable functions
*~ This file should be imported using the CommonJS-style:
*~ import x = require('someLibrary');

So the code to import moment js into typescript actually looks like this:

import { Moment } from 'moment'
....
let moment = require('moment');
...
interface SomeTime {
  aMoment: Moment,
}
...
fn() {
  ...
  someTime.aMoment = moment(...);
  ...
}

Difference between style = "position:absolute" and style = "position:relative"

Absolute places the object (div, span, etc.) at an absolute forced location (usually determined in pixels) and relative will place it a certain amount away from where it's location would normally be. For example:

position:relative; left:-20px;

Might make the left side of the text disappear if it was within 20px to the left edge of the screen.

Get list of data-* attributes using javascript / jQuery

A pure JavaScript solution ought to be offered as well, as the solution is not difficult:

var a = [].filter.call(el.attributes, function(at) { return /^data-/.test(at.name); });

This gives an array of attribute objects, which have name and value properties:

if (a.length) {
    var firstAttributeName = a[0].name;
    var firstAttributeValue = a[0].value;
}

Edit: To take it a step further, you can get a dictionary by iterating the attributes and populating a data object:

var data = {};
[].forEach.call(el.attributes, function(attr) {
    if (/^data-/.test(attr.name)) {
        var camelCaseName = attr.name.substr(5).replace(/-(.)/g, function ($0, $1) {
            return $1.toUpperCase();
        });
        data[camelCaseName] = attr.value;
    }
});

You could then access the value of, for example, data-my-value="2" as data.myValue;

jsfiddle.net/3KFYf/33

Edit: If you wanted to set data attributes on your element programmatically from an object, you could:

Object.keys(data).forEach(function(key) {
    var attrName = "data-" + key.replace(/[A-Z]/g, function($0) {
        return "-" + $0.toLowerCase();
    });
    el.setAttribute(attrName, data[key]);
});

jsfiddle.net/3KFYf/34

EDIT: If you are using babel or TypeScript, or coding only for es6 browsers, this is a nice place to use es6 arrow functions, and shorten the code a bit:

var a = [].filter.call(el.attributes, at => /^data-/.test(at.name));

Difference between View and table in sql

A table contains data, a view is just a SELECT statement which has been saved in the database (more or less, depending on your database).

The advantage of a view is that it can join data from several tables thus creating a new view of it. Say you have a database with salaries and you need to do some complex statistical queries on it.

Instead of sending the complex query to the database all the time, you can save the query as a view and then SELECT * FROM view

Disable scrolling in an iPhone web application?

I tried above answers and particularly Gajus's but none works. Finally I found the answer below to solve the problem such that only the main body doesn't scroll but other scrolling sections inside my web app all work fine. Simply set position fixed for your body:

body {

height: 100%;
overflow: hidden;
width: 100%;
position: fixed;
}

Full path from file input using jQuery

Well, getting full path is not possible but we can have a temporary path.

Try This:

It'll give you a temporary path not the accurate path, you can use this script if you want to show selected images as in this jsfiddle example(Try it by selectng images as well as other files):-

JSFIDDLE

Here is the code :-

HTML:-

<input type="file" id="i_file" value=""> 
<input type="button" id="i_submit" value="Submit">
    <br>
<img src="" width="200" style="display:none;" />
        <br>
<div id="disp_tmp_path"></div>

JS:-

$('#i_file').change( function(event) {
var tmppath = URL.createObjectURL(event.target.files[0]);
    $("img").fadeIn("fast").attr('src',URL.createObjectURL(event.target.files[0]));

    $("#disp_tmp_path").html("Temporary Path(Copy it and try pasting it in browser address bar) --> <strong>["+tmppath+"]</strong>");
});

Its not exactly what you were looking for, but may be it can help you somewhere.

How to getElementByClass instead of GetElementById with JavaScript?

My solution:

First create "<style>" tags with an ID.

<style id="YourID">
    .YourClass {background-color:red}
</style>

Then, I create a function in JavaScript like this:

document.getElementById('YourID').innerHTML = '.YourClass {background-color:blue}'

Worked like a charm for me.

How do I git rm a file without deleting it from disk?

I tried experimenting with the answers given. My personal finding came out to be:

git rm -r --cached .

And then

git add .

This seemed to make my working directory nice and clean. You can put your fileName in place of the dot.

There are no primary or candidate keys in the referenced table that match the referencing column list in the foreign key

Foreign keys work by joining a column to a unique key in another table, and that unique key must be defined as some form of unique index, be it the primary key, or some other unique index.

At the moment, the only unique index you have is a compound one on ISBN, Title which is your primary key.

There are a number of options open to you, depending on exactly what BookTitle holds and the relationship of the data within it.

I would hazard a guess that the ISBN is unique for each row in BookTitle. ON the assumption this is the case, then change your primary key to be only on ISBN, and change BookCopy so that instead of Title you have ISBN and join on that.

If you need to keep your primary key as ISBN, Title then you either need to store the ISBN in BookCopy as well as the Title, and foreign key on both columns, OR you need to create a unique index on BookTitle(Title) as a distinct index.

More generally, you need to make sure that the column or columns you have in your REFERENCES clause match exactly a unique index in the parent table: in your case it fails because you do not have a single unique index on Title alone.

Having the output of a console application in Visual Studio instead of the console

It's time to check the latest release/s for Visual Studio, folks. The most suggested solution that did not work for some of you before might work now.

In Visual Studio 2017 (Release Version 15.4.2 and above), going to Tools > Options > Debugging > General > (Check Box) Redirect all Output Window text to Immediate Window has worked for me.

Few Notes:

  1. To see the Immediate Window, make sure that you are in Debugging mode.
  2. There should now be 3 other debugging tools available at your disposal, namely, Call Stack, Breakpoints, and Command Window, as shown below:

enter image description here

Best wishes!

Java Reflection Performance

"Significant" is entirely dependent on context.

If you're using reflection to create a single handler object based on some configuration file, and then spending the rest of your time running database queries, then it's insignificant. If you're creating large numbers of objects via reflection in a tight loop, then yes, it's significant.

In general, design flexibility (where needed!) should drive your use of reflection, not performance. However, to determine whether performance is an issue, you need to profile rather than get arbitrary responses from a discussion forum.

How to print out more than 20 items (documents) in MongoDB's shell?

You can use it inside of the shell to iterate over the next 20 results. Just type it if you see "has more" and you will see the next 20 items.

.NET HttpClient. How to POST string value?

using System;
using System.Collections.Generic;
using System.Net.Http;

class Program
{
    static void Main(string[] args)
    {
        Task.Run(() => MainAsync());
        Console.ReadLine();
    }

    static async Task MainAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:6740");
            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("", "login")
            });
            var result = await client.PostAsync("/api/Membership/exists", content);
            string resultContent = await result.Content.ReadAsStringAsync();
            Console.WriteLine(resultContent);
        }
    }
}

Echo newline in Bash prints literal \n

One more entry here for those that didn't make it work with any of these solutions, and need to get a return value from their function:

function foo()
{
    local v="Dimi";
    local s="";
    .....
    s+="Some message here $v $1\n"
    .....
    echo $s
}

r=$(foo "my message");
echo -e $r;

Only this trick worked in a linux I was working on with this bash:

GNU bash, version 2.2.25(1)-release (x86_64-redhat-linux-gnu)

Hope it helps someone with similar problem.

How can I generate random alphanumeric strings?

Try to combine two parts: unique (sequence, counter or date ) and random

public class RandomStringGenerator
{
    public static string Gen()
    {
        return ConvertToBase(DateTime.UtcNow.ToFileTimeUtc()) + GenRandomStrings(5); //keep length fixed at least of one part
    }

    private static string GenRandomStrings(int strLen)
    {
        var result = string.Empty;

        using (var gen = new RNGCryptoServiceProvider())
        {
            var data = new byte[1];

            while (result.Length < strLen)
            {
                gen.GetNonZeroBytes(data);
                int code = data[0];
                if (code > 48 && code < 57 || // 0-9
                    code > 65 && code < 90 || // A-Z
                    code > 97 && code < 122   // a-z
                )
                {
                    result += Convert.ToChar(code);
                }
            }

            return result;
        }
    }

    private static string ConvertToBase(long num, int nbase = 36)
    {
        const string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //if you wish to make the algorithm more secure - change order of letter here

        // check if we can convert to another base
        if (nbase < 2 || nbase > chars.Length)
            return null;

        int r;
        var newNumber = string.Empty;

        // in r we have the offset of the char that was converted to the new base
        while (num >= nbase)
        {
            r = (int)(num % nbase);
            newNumber = chars[r] + newNumber;
            num = num / nbase;
        }
        // the last number to convert
        newNumber = chars[(int)num] + newNumber;

        return newNumber;
    }
}

Tests:

    [Test]
    public void Generator_Should_BeUnigue1()
    {
        //Given
        var loop = Enumerable.Range(0, 1000);
        //When
        var str = loop.Select(x=> RandomStringGenerator.Gen());
        //Then
        var distinct = str.Distinct();
        Assert.AreEqual(loop.Count(),distinct.Count()); // Or Assert.IsTrue(distinct.Count() < 0.95 * loop.Count())
    }

How to prevent tensorflow from allocating the totality of a GPU memory?

this code has worked for me:

import tensorflow as tf
config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
session = tf.compat.v1.InteractiveSession(config=config)

Is there a Python equivalent of the C# null-coalescing operator?

Regarding answers by @Hugh Bothwell, @mortehu and @glglgl.

Setup Dataset for testing

import random

dataset = [random.randint(0,15) if random.random() > .6 else None for i in range(1000)]

Define implementations

def not_none(x, y=None):
    if x is None:
        return y
    return x

def coalesce1(*arg):
  return reduce(lambda x, y: x if x is not None else y, arg)

def coalesce2(*args):
    return next((i for i in args if i is not None), None)

Make test function

def test_func(dataset, func):
    default = 1
    for i in dataset:
        func(i, default)

Results on mac i7 @2.7Ghz using python 2.7

>>> %timeit test_func(dataset, not_none)
1000 loops, best of 3: 224 µs per loop

>>> %timeit test_func(dataset, coalesce1)
1000 loops, best of 3: 471 µs per loop

>>> %timeit test_func(dataset, coalesce2)
1000 loops, best of 3: 782 µs per loop

Clearly the not_none function answers the OP's question correctly and handles the "falsy" problem. It is also the fastest and easiest to read. If applying the logic in many places, it is clearly the best way to go.

If you have a problem where you want to find the 1st non-null value in a iterable, then @mortehu's response is the way to go. But it is a solution to a different problem than OP, although it can partially handle that case. It cannot take an iterable AND a default value. The last argument would be the default value returned, but then you wouldn't be passing in an iterable in that case as well as it isn't explicit that the last argument is a default to value.

You could then do below, but I'd still use not_null for the single value use case.

def coalesce(*args, **kwargs):
    default = kwargs.get('default')
    return next((a for a in arg if a is not None), default)

Setting PHP tmp dir - PHP upload not working

My problem was selinux...

Go sestatus

If Current mode: enforcing

Then chcon -R -t httpd_sys_rw_content_t /var/www/html

Angular 2 / 4 / 5 - Set base href dynamically

In package.json set flag --base-href to relative path:

"script": {
    "build": "ng build --base-href ./"
}

Func delegate with no return type

Try System.Func<T> and System.Action

displaying a string on the textview when clicking a button in android

public void onCreate(Bundle savedInstanceState) 
{
    setContentView(R.layout.main);
    super.onCreate(savedInstanceState);

    mybtn = (Button)findViewById(R.id.mybtn);
    txtView=(TextView)findViewById(R.id.txtView);

    mybtn .setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            txtView.SetText("Your Message");
        }
    });
}

Where can I find a list of escape characters required for my JSON ajax return type?

Here is a list of special characters that you can escape when creating a string literal for JSON:

\b  Backspace (ASCII code 08)
\f  Form feed (ASCII code 0C)
\n  New line
\r  Carriage return
\t  Tab
\v  Vertical tab
\'  Apostrophe or single quote
\"  Double quote
\\  Backslash character

Reference: String literals

Some of these are more optional than others. For instance, your string should be perfectly valid whether you escape the tab character or leave in a tab literal. You should certainly be handling the backslash and quote characters, though.

How do you detect/avoid Memory leaks in your (Unmanaged) code?

If you are using Visual Studio, Microsoft provides some useful functions for detecting and debugging memory leaks.

I would start with this article: https://msdn.microsoft.com/en-us/library/x98tx3cf(v=vs.140).aspx

Here is the quick summary of those articles. First, include these headers:

#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>

Then you need to call this when your program exits:

_CrtDumpMemoryLeaks();

Alternatively, if your program does not exit in the same place every time, you can call this at the start of your program:

_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );

Now when the program exits all the allocations that were not free'd will be printed in the Output Window along with the file they were allocated in and the allocation occurrence.

This strategy works for most programs. However, it becomes difficult or impossible in certain cases. Using third party libraries that do some initialization on startup may cause other objects to appear in the memory dump and can make tracking down your leaks difficult. Also, if any of your classes have members with the same name as any of the memory allocation routines( such as malloc ), the CRT debug macros will cause problems.

There are other techniques explained in the MSDN link referenced above that could be used as well.

AngularJs ReferenceError: $http is not defined

Just to complete Amit Garg answer, there are several ways to inject dependencies in AngularJS.


You can also use $inject to add a dependency:

var MyController = function($scope, $http) {
  // ...
}
MyController.$inject = ['$scope', '$http'];

How to send redirect to JSP page in Servlet

Please use the below code and let me know

try{

            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con = DriverManager.getConnection(c, "root", "MyNewPass");
            System.out.println("connection done");


            PreparedStatement ps=con.prepareStatement(q);
            System.out.println(q);
            rs=ps.executeQuery();
            System.out.println("done2");
            while (rs.next()) {
               System.out.println(rs.getString(1));
               System.out.println(rs.getString(2));

            }

         response.sendRedirect("myfolder/welcome.jsp"); // wherever you wanna redirect this page.

        }
            catch (Exception e) {
                // TODO: handle exception
                System.out.println("Failed");
            }

myfolder/welcome.jsp is the relative path of your jsp page. So, change it as per your jsp page path.

Why declare unicode by string in python?

That doesn't set the format of the string; it sets the format of the file. Even with that header, "hello" is a byte string, not a Unicode string. To make it Unicode, you're going to have to use u"hello" everywhere. The header is just a hint of what format to use when reading the .py file.

How to use an arraylist as a prepared statement parameter

@JulienD Best way is to break above process into two steps.

Step 1 : Lets say 'rawList' as your list that you want to add as parameters in prepared statement.

Create another list :

ArrayList<String> listWithQuotes = new ArrayList<String>();

for(String element : rawList){
    listWithQuotes.add("'"+element+"'");
}

Step 2 : Make 'listWithQuotes' comma separated.

String finalString = StringUtils.join(listWithQuotes.iterator(),",");

'finalString' will be string parameters with each element as single quoted and comma separated.

What causes HttpHostConnectException?

In my case the issue was a missing 's' in the HTTP URL. Error was: "HttpHostConnectException: Connect to someendpoint.com:80 [someendpoint.com/127.0.0.1] failed: Connection refused" End point and IP obviously changed to protect the network.

How can I concatenate strings in VBA?

& is always evaluated in a string context, while + may not concatenate if one of the operands is no string:

"1" + "2" => "12"
"1" + 2   => 3
1 + "2"   => 3
"a" + 2   => type mismatch

This is simply a subtle source of potential bugs and therefore should be avoided. & always means "string concatenation", even if its arguments are non-strings:

"1" & "2" => "12"
"1" &  2  => "12"
 1  & "2" => "12"
 1  &  2  => "12"
"a" &  2  => "a2"

Using .Select and .Where in a single LINQ statement

Did you add the Select() after the Where() or before?

You should add it after, because of the concurrency logic:

 1 Take the entire table  
 2 Filter it accordingly  
 3 Select only the ID's  
 4 Make them distinct.  

If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.

Update: For clarity, this order of operators should work:

db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();

Probably want to add a .toList() at the end but that's optional :)

Docker compose port mapping

If you want to access redis from the host (127.0.0.1), you have to use the ports command.

redis:
  build:
    context: .
    dockerfile: Dockerfile-redis
    ports:
    - "6379:6379"

How to convert current date into string in java?

For time as YYYY-MM-dd

String time = new DateTime( yourData ).toString("yyyy-MM-dd");

And the Library of DateTime is:

import org.joda.time.DateTime;

How to update the value stored in Dictionary in C#?

This may work for you:

Scenario 1: primitive types

string keyToMatchInDict = "x";
int newValToAdd = 1;
Dictionary<string,int> dictToUpdate = new Dictionary<string,int>{"x",1};

if(!dictToUpdate.ContainsKey(keyToMatchInDict))
   dictToUpdate.Add(keyToMatchInDict ,newValToAdd );
else
   dictToUpdate[keyToMatchInDict] = newValToAdd; //or you can do operations such as ...dictToUpdate[keyToMatchInDict] += newValToAdd;

Scenario 2: The approach I used for a List as Value

int keyToMatch = 1;
AnyObject objInValueListToAdd = new AnyObject("something for the Ctor")
Dictionary<int,List<AnyObject> dictToUpdate = new Dictionary<int,List<AnyObject>(); //imagine this dict got initialized before with valid Keys and Values...

if(!dictToUpdate.ContainsKey(keyToMatch))
   dictToUpdate.Add(keyToMatch,new List<AnyObject>{objInValueListToAdd});
else
   dictToUpdate[keyToMatch] = objInValueListToAdd;

Hope it's useful for someone in need of help.

How to generate an entity-relationship (ER) diagram using Oracle SQL Developer

Oracle used to have a component in SQL Developer called Data Modeler. It no longer exists in the product since at least 3.2.20.10.

It's now a separate download that you can find here:

http://www.oracle.com/technetwork/developer-tools/datamodeler/overview/index.html

Best way to retrieve variable values from a text file?

Use ConfigParser.

Your config:

[myvars]
var_a: 'home'
var_b: 'car'
var_c: 15.5

Your python code:

import ConfigParser

config = ConfigParser.ConfigParser()
config.read("config.ini")
var_a = config.get("myvars", "var_a")
var_b = config.get("myvars", "var_b")
var_c = config.get("myvars", "var_c")

How to use filter, map, and reduce in Python 3

You can read about the changes in What's New In Python 3.0. You should read it thoroughly when you move from 2.x to 3.x since a lot has been changed.

The whole answer here are quotes from the documentation.

Views And Iterators Instead Of Lists

Some well-known APIs no longer return lists:

  • [...]
  • map() and filter() return iterators. If you really need a list, a quick fix is e.g. list(map(...)), but a better fix is often to use a list comprehension (especially when the original code uses lambda), or rewriting the code so it doesn’t need a list at all. Particularly tricky is map() invoked for the side effects of the function; the correct transformation is to use a regular for loop (since creating a list would just be wasteful).
  • [...]

Builtins

  • [...]
  • Removed reduce(). Use functools.reduce() if you really need it; however, 99 percent of the time an explicit for loop is more readable.
  • [...]

LaTeX "\indent" creating paragraph indentation / tabbing package requirement?

The first line of a paragraph is indented by default, thus whether or not you have \indent there won't make a difference. \indent and \noindent can be used to override default behavior. You can see this by replacing your line with the following:

Now we are engaged in a great civil war.\\
\indent this is indented\\
this isn't indented


\noindent override default indentation (not indented)\\
asdf 

jQuery's .click - pass parameters to user function

Yes, this is an old post. Regardless, someone may find it useful. Here is another way to send parameters to event handlers.

//click handler
function add_event(event, paramA, paramB)
{
    //do something with your parameters
    alert(paramA ? 'paramA:' + paramA : '' + paramB ? '  paramB:' + paramB : '');
}

//bind handler to click event
$('.leadtoscore').click(add_event);
...
//once you've processed some data and know your parameters, trigger a click event.
//In this case, we will send 'myfirst' and 'mysecond' as parameters
$('.leadtoscore').trigger('click', {'myfirst', 'mysecond'});

//or use variables
var a = 'first',
    b = 'second';

$('.leadtoscore').trigger('click', {a, b});
$('.leadtoscore').trigger('click', {a});

How to install package from github repo in Yarn

For ssh style urls just add ssh before the url:

yarn add ssh://<whatever>@<xxx>#<branch,tag,commit>

How to add a custom Ribbon tab using VBA?

AFAIK you cannot use VBA Excel to create custom tab in the Excel ribbon. You can however hide/make visible a ribbon component using VBA. Additionally, the link that you mentioned above is for MS Project and not MS Excel.

I create tabs for my Excel Applications/Add-Ins using this free utility called Custom UI Editor.


Edit: To accommodate new request by OP

Tutorial

Here is a short tutorial as promised:

  1. After you have installed the Custom UI Editor (CUIE), open it and then click on File | Open and select the relevant Excel File. Please ensure that the Excel File is closed before you open it via CUIE. I am using a brand new worksheet as an example.

    enter image description here

  2. Right click as shown in the image below and click on "Office 2007 Custom UI Part". It will insert the "customUI.xml"

    enter image description here

  3. Next Click on menu Insert | Sample XML | Custom Tab. You will notice that the basic code is automatically generated. Now you are all set to edit it as per your requirements.

    enter image description here

  4. Let's inspect the code

    enter image description here

    label="Custom Tab": Replace "Custom Tab" with the name which you want to give your tab. For the time being let's call it "Jerome".

    The below part adds a custom button.

    <button id="customButton" label="Custom Button" imageMso="HappyFace" size="large" onAction="Callback" />
    

    imageMso: This is the image that will display on the button. "HappyFace" is what you will see at the moment. You can download more image ID's here.

    onAction="Callback": "Callback" is the name of the procedure which runs when you click on the button.

Demo

With that, let's create 2 buttons and call them "JG Button 1" and "JG Button 2". Let's keep happy face as the image of the first one and let's keep the "Sun" for the second. The amended code now looks like this:

<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui">
<ribbon startFromScratch="false">
<tabs>
<tab id="MyCustomTab" label="Jerome" insertAfterMso="TabView">
<group id="customGroup1" label="First Tab">
<button id="customButton1" label="JG Button 1" imageMso="HappyFace" size="large" onAction="Callback1" />
<button id="customButton2" label="JG Button 2" imageMso="PictureBrightnessGallery" size="large" onAction="Callback2" />
</group>
</tab>
</tabs>
</ribbon>
</customUI>

Delete all the code which was generated in CUIE and then paste the above code in lieu of that. Save and close CUIE. Now when you open the Excel File it will look like this:

enter image description here

Now the code part. Open VBA Editor, insert a module, and paste this code:

Public Sub Callback1(control As IRibbonControl)

    MsgBox "You pressed Happy Face"

End Sub

Public Sub Callback2(control As IRibbonControl)

    MsgBox "You pressed the Sun"

End Sub

Save the Excel file as a macro enabled file. Now when you click on the Smiley or the Sun you will see the relevant message box:

enter image description here

Hope this helps!

How do I add a auto_increment primary key in SQL Server database?

You can also perform this action via SQL Server Management Studio.

Right click on your selected table -> Modify

Right click on the field you want to set as PK --> Set Primary Key

Under Column Properties set "Identity Specification" to Yes, then specify the starting value and increment value.

Then in the future if you want to be able to just script this kind of thing out you can right click on the table you just modified and select

"SCRIPT TABLE AS" --> CREATE TO

so that you can see for yourself the correct syntax to perform this action.

getFilesDir() vs Environment.getDataDirectory()

getFilesDir()

Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.

Environment.getDataDirectory()

Return the user data directory.

Insert, on duplicate update in PostgreSQL?

In PostgreSQL 9.5 and newer you can use INSERT ... ON CONFLICT UPDATE.

See the documentation.

A MySQL INSERT ... ON DUPLICATE KEY UPDATE can be directly rephrased to a ON CONFLICT UPDATE. Neither is SQL-standard syntax, they're both database-specific extensions. There are good reasons MERGE wasn't used for this, a new syntax wasn't created just for fun. (MySQL's syntax also has issues that mean it wasn't adopted directly).

e.g. given setup:

CREATE TABLE tablename (a integer primary key, b integer, c integer);
INSERT INTO tablename (a, b, c) values (1, 2, 3);

the MySQL query:

INSERT INTO tablename (a,b,c) VALUES (1,2,3)
  ON DUPLICATE KEY UPDATE c=c+1;

becomes:

INSERT INTO tablename (a, b, c) values (1, 2, 10)
ON CONFLICT (a) DO UPDATE SET c = tablename.c + 1;

Differences:

  • You must specify the column name (or unique constraint name) to use for the uniqueness check. That's the ON CONFLICT (columnname) DO

  • The keyword SET must be used, as if this was a normal UPDATE statement

It has some nice features too:

  • You can have a WHERE clause on your UPDATE (letting you effectively turn ON CONFLICT UPDATE into ON CONFLICT IGNORE for certain values)

  • The proposed-for-insertion values are available as the row-variable EXCLUDED, which has the same structure as the target table. You can get the original values in the table by using the table name. So in this case EXCLUDED.c will be 10 (because that's what we tried to insert) and "table".c will be 3 because that's the current value in the table. You can use either or both in the SET expressions and WHERE clause.

For background on upsert see How to UPSERT (MERGE, INSERT ... ON DUPLICATE UPDATE) in PostgreSQL?

@font-face not working

Using font-face requires a little understanding of browser inconsistencies and may require some changes on the web server itself. First thing you have to do is check the console to see if/what messages are being generated. Is it a permissions issue or resource not found....?

Secondly because each browser is expecting a different font type I would use Font Squirrel to upload your font and then generate the additional files and CSS needed. http://www.fontsquirrel.com/fontface/generator

And finally, versions of FireFox and IE will not allow fonts to be loaded cross domain. You may need to modify your Apache config or .htaccess (Header set Access-Control-Allow-Origin "*")

How to get a value of an element by name instead of ID

you can also use the class name.

$(".yourclass").val();

How can I align YouTube embedded video in the center in bootstrap

I set the max width for my video to be 100%. On phones the video automatically fits the width of the screen. Since the embedded video is only 560px wide, I just added a 10% left-margin to the iframe, and put a "0" back in for the margin for the mobile CSS (to allow the full width view). I did't want to bother putting a div around every video...

Desktop CSS:

_x000D_
_x000D_
iframe {_x000D_
  margin-left: 10%;_x000D_
 }
_x000D_
_x000D_
_x000D_

Mobile CSS:

_x000D_
_x000D_
iframe {_x000D_
  margin-left: 0;_x000D_
 }
_x000D_
_x000D_
_x000D_

Worked perfect for my blog (Botanical Amy).

How do I make a PHP form that submits to self?

Your submit button doesn't have a name. Add name="submit" to your submit button.

If you view source on the form in the browser, you'll see how it submits to self - the form's action attribute will contain the name of the current script - therefore when the form submits, it submits to itself. Edit for vanity sake!

Increment a value in Postgres

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill';

If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill'
  AND total = 203;

How can I check if character in a string is a letter? (Python)

str.isalpha()

Return true if all characters in the string are alphabetic and there is at least one character, false otherwise. Alphabetic characters are those characters defined in the Unicode character database as “Letter”, i.e., those with general category property being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is different from the “Alphabetic” property defined in the Unicode Standard.

In python2.x:

>>> s = u'a1??'
>>> for char in s: print char, char.isalpha()
...
a True
1 False
? True
? True
>>> s = 'a1??'
>>> for char in s: print char, char.isalpha()
...
a True
1 False
? False
? False
? False
? False
? False
? False
>>>

In python3.x:

>>> s = 'a1??'
>>> for char in s: print(char, char.isalpha())
...
a True
1 False
? True
? True
>>>

This code work:

>>> def is_alpha(word):
...     try:
...         return word.encode('ascii').isalpha()
...     except:
...         return False
...
>>> is_alpha('??')
False
>>> is_alpha(u'??')
False
>>>

>>> a = 'a'
>>> b = 'a'
>>> ord(a), ord(b)
(65345, 97)
>>> a.isalpha(), b.isalpha()
(True, True)
>>> is_alpha(a), is_alpha(b)
(False, True)
>>>

Using jQuery to see if a div has a child with a certain class

Use the children funcion of jQuery.

$("#text-field").keydown(function(event) {
    if($('#popup').children('p.filled-text').length > 0) {
        console.log("Found");
     }
});

$.children('').length will return the count of child elements which match the selector.

How do I remove the last comma from a string using PHP?

its as simple as:

$commaseparated_string = name,name2,name3,;
$result = rtrim($commaseparated_string,',');

Cannot implicitly convert type from Task<>

The main issue with your example that you can't implicitly convert Task<T> return types to the base T type. You need to use the Task.Result property. Note that Task.Result will block async code, and should be used carefully.

Try this instead:

public List<int> TestGetMethod()  
{  
    return GetIdList().Result;  
}

How to calculate age (in years) based on Date of Birth and getDate()

DECLARE @yourBirthDate DATETIME = '1987-05-25'
SELECT YEAR(DATEADD(DAY, DATEDIFF(DAY, @yourBirthDate, GETDATE()), CAST('0001-01-01' AS DATETIME2))) - 1

Twitter Bootstrap hide css class and jQuery

If an element has bootstrap's "hide" class and you want to display it with some sliding effect such as .slideDown(), you can cheat bootstrap like:

$('#hiddenElement').hide().removeClass('hide').slideDown('fast')

Converting string to integer

The function you need is CInt.

ie CInt(PrinterLabel)

See Type Conversion Functions (Visual Basic) on MSDN

Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!

GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()'

Qt C++ will show this error when you change a class such that it now inherits from QObject (ie so that it can now use signals/slots). Running qmake -r will call moc and fix this problem.

If you are working with others via some sort of version control, you will want to make some change to your .pro file (ie add/remove a blank line). When everyone else gets your changes and runs make, make will see that the .pro file has changed and automatically run qmake. This will save your teammates from repeating your frustration.

Cannot find java. Please use the --jdkhome switch

Try Java SE Runtime Environment 8. It fixed it for me.

How to get current location in Android

I'm using this tutorial and it works nicely for my application.

In my activity I put this code:

GPSTracker tracker = new GPSTracker(this);
    if (!tracker.canGetLocation()) {
        tracker.showSettingsAlert();
    } else {
        latitude = tracker.getLatitude();
        longitude = tracker.getLongitude();
    }

also check if your emulator runs with Google API

No submodule mapping found in .gitmodule for a path that's not a submodule

Scenario: changing the submodule from directory dirA-xxx to another directory dirB-xxx

  1. move the dirA-xxx to dirB-xxx
  2. modify entry in .gitmodules to use dirB-xxx
  3. modify entry in .git/config to use dirB-xxx
  4. modify .git/modules/dirA-xxx/config to reflect the correct directory
  5. modify dirA-xxx/.git to reflect the correct directory
  6. run git submodule status

    if return error: No submodule mapping found in .gitmodules for path dirA-xxx. This is due to dirA-xxx is not existing, yet it is still tracked by git. Update the git index by: git rm --cached dirA-xxx

    Try with git submodule foreach git pull. I didn't go through the actual study of git submodule structure, so above steps may break something. Nonetheless going through above steps, things look good at the moment. If you have any insight or proper steps to get thing done, do share it here. :)

Is jQuery $.browser Deprecated?

"The $.browser property is deprecated in jQuery 1.3, and its functionality may be moved to a team-supported plugin in a future release of jQuery."

From http://api.jquery.com/jQuery.browser/

Regexp Java for password validation

easy one

("^ (?=.* [0-9]) (?=.* [a-z]) (?=.* [A-Z]) (?=.* [\\W_])[\\S]{8,10}$")

  1. (?= anything ) ->means positive looks forward in all input string and make sure for this condition is written .sample(?=.*[0-9])-> means ensure one digit number is written in the all string.if not written return false .

  2. (?! anything ) ->(vise versa) means negative looks forward if condition is written return false.

    close meaning ^(condition)(condition)(condition)(condition)[\S]{8,10}$

How do I UPDATE from a SELECT in SQL Server?

The same solution can be written in a slightly different way as I would like to set the columns only once I have written about both the tables. Working in mysql.      

UPDATE Table t, 
(SELECT col1, col2 FROM other_table WHERE sql = 'cool' ) o
SET t.col1 = o.col1, t.col2=o.col2
WHERE t.id = o.id

How to set java.net.preferIPv4Stack=true at runtime?

I ran into this very problem trying to send mail with javax.mail from a web application in a web server running Java 7. Internal mail server destinations failed with "network unreachable", despite telnet and ping working from the same host, and while external mail servers worked. I tried

System.setProperty("java.net.preferIPv4Stack" , "true");

in the code, but that failed. So the parameter value was probably cached earlier by the system. Setting the VM argument

-Djava.net.preferIPv4Stack=true

in the web server startup script worked.

One further bit of evidence: in a very small targeted test program, setting the system property in the code did work. So the parameter is probably cached when the first Socket is used, probably not just as the JVM starts.

How to center a label text in WPF?

The Control class has HorizontalContentAlignment and VerticalContentAlignment properties. These properties determine how a control’s content fills the space within the control.
Set HorizontalContentAlignment and VerticalContentAlignment to Center.

How do you reinstall an app's dependencies using npm?

For Windows you can use

(if exist node_modules rmdir node_modules /q /s) && npm install

which removes node_modules directory and performs npm install then. Removal before install assures that all packages are reinstalled.

Angular JS: What is the need of the directive’s link function when we already had directive’s controller with scope?

Why controllers are needed

The difference between link and controller comes into play when you want to nest directives in your DOM and expose API functions from the parent directive to the nested ones.

From the docs:

Best Practice: use controller when you want to expose an API to other directives. Otherwise use link.

Say you want to have two directives my-form and my-text-input and you want my-text-input directive to appear only inside my-form and nowhere else.

In that case, you will say while defining the directive my-text-input that it requires a controller from the parent DOM element using the require argument, like this: require: '^myForm'. Now the controller from the parent element will be injected into the link function as the fourth argument, following $scope, element, attributes. You can call functions on that controller and communicate with the parent directive.

Moreover, if such a controller is not found, an error will be raised.

Why use link at all

There is no real need to use the link function if one is defining the controller since the $scope is available on the controller. Moreover, while defining both link and controller, one does need to be careful about the order of invocation of the two (controller is executed before).

However, in keeping with the Angular way, most DOM manipulation and 2-way binding using $watchers is usually done in the link function while the API for children and $scope manipulation is done in the controller. This is not a hard and fast rule, but doing so will make the code more modular and help in separation of concerns (controller will maintain the directive state and link function will maintain the DOM + outside bindings).

javascript password generator

Here's a free, configurable Javascript class generating random passwords: Javascript Random Password Generator.

Examples

Password consisting of Lower case + upper case + numbers, 8 characters long:

var randomPassword = new RandomPassword();
document.write(randomPassword.create());

Password consisting of Lower case + upper case + numbers, 20 characters long:

var randomPassword = new RandomPassword();
document.write(randomPassword.create(20));

Password consisting of Lower case + upper case + numbers + symbols, 20 characters long:

var randomPassword = new RandomPassword();
document.write(randomPassword.create(20,randomPassword.chrLower+randomPassword.chrUpper+randomPassword.chrNumbers+randomPassword.chrSymbols));  

Add a string of text into an input field when user clicks a button

Here it is: http://jsfiddle.net/tQyvp/

Here's the code if you don't like going to jsfiddle:

html

<input id="myinputfield" value="This is some text" type="button">?

Javascript:

$('body').on('click', '#myinputfield', function(){
    var textField = $('#myinputfield');
    textField.val(textField.val()+' after clicking')       
});?

Format specifier %02x

%x is a format specifier that format and output the hex value. If you are providing int or long value, it will convert it to hex value.

%02x means if your provided value is less than two digits then 0 will be prepended.

You provided value 16843009 and it has been converted to 1010101 which a hex value.

How to create a self-signed certificate with OpenSSL

One-liner version 2017:

CentOS:

openssl req -x509 -nodes -sha256 -newkey rsa:2048 \
-keyout localhost.key -out localhost.crt \
-days 3650 \
-subj "CN=localhost" \
-reqexts SAN -extensions SAN \
-config <(cat /etc/pki/tls/openssl.cnf <(printf "\n[SAN]\nsubjectAltName=IP:127.0.0.1,DNS:localhost"))

Ubuntu:

openssl req -x509 -nodes -sha256 -newkey rsa:2048 \
-keyout localhost.key -out localhost.crt \
-days 3650 \
-subj "/CN=localhost" \
-reqexts SAN -extensions SAN \
-config <(cat /etc/ssl/openssl.cnf <(printf "\n[SAN]\nsubjectAltName=IP:127.0.0.1,DNS:localhost"))

Edit: added prepending Slash to 'subj' option for Ubuntu.

How to check if a "lateinit" variable has been initialized?

There is a lateinit improvement in Kotlin 1.2 that allows to check the initialization state of lateinit variable directly:

lateinit var file: File    

if (this::file.isInitialized) { ... }

See the annoucement on JetBrains blog or the KEEP proposal.

UPDATE: Kotlin 1.2 has been released. You can find lateinit enhancements here:

How do I make a delay in Java?

I know this is a very old post but this may help someone: You can create a method, so whenever you need to pause you can type pause(1000) or any other millisecond value:

public static void pause(int ms) {
    try {
        Thread.sleep(ms);
    } catch (InterruptedException e) {
        System.err.format("IOException: %s%n", e);
    }
}

This is inserted just above the public static void main(String[] args), inside the class. Then, to call on the method, type pause(ms) but replace ms with the number of milliseconds to pause. That way, you don't have to insert the entire try-catch statement whenever you want to pause.

How to export data with Oracle SQL Developer?

In version 3, they changed "export" to "unload". It still functions more or less the same.

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

I get the same error on my JSP and the bad rated answer was correct

I had the folowing line:

<c:forEach var="agent" items=" ${userList}" varStatus="rowCounter">

and get the folowing error:

javax.el.PropertyNotFoundException: Property 'agent' not found on type java.lang.String

deleting the space before ${userList} solved my problem

If some have the same problem, he will find quickly this post and does not waste 3 days in googeling to find help.

How to get key names from JSON using jq

To get the keys on a deeper node in an JSON:

echo '{"data": "1", "user": { "name": 2, "phone": 3 } }' | jq '.user | keys[]'
"name"
"phone"

android: how to change layout on button click?

First I would suggest putting a Log in each case of your switch to be sure that your code is being called.

Then I would check that the layouts are actually different.

Convert Pandas Series to DateTime in a DataFrame

Some handy script:

hour = df['assess_time'].dt.hour.values[0]

Java List.add() UnsupportedOperationException

Form the Inheritance concept, If some perticular method is not available in the current class it will search for that method in super classes. If available it executes.

It executes AbstractList<E> class add() method which throws UnsupportedOperationException.


When you are converting from an Array to a Collection Obejct. i.e., array-based to collection-based API then it is going to provide you fixed-size collection object, because Array's behaviour is of Fixed size.

java.util.Arrays.asList( T... a )

Souce samples for conformation.

public class Arrays {
    public static <T> List<T> asList(T... a) {
        return new java.util.Arrays.ArrayList.ArrayList<>(a); // Arrays Inner Class ArrayList
    }
    //...
    private static class ArrayList<E> extends AbstractList<E> implements RandomAccess, java.io.Serializable {
        //...
    }
}
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
    public void add(int index, E element) {
        throw new UnsupportedOperationException();
    }
    public E set(int index, E element) {
        throw new UnsupportedOperationException();
    }
    public E remove(int index) {
        throw new UnsupportedOperationException();
    }

    public Iterator<E> iterator() {
        return new Itr();
    }
    private class Itr implements Iterator<E> {
        //...
    }

    public ListIterator<E> listIterator() {
        return listIterator(0);
    }
    private class ListItr extends Itr implements ListIterator<E> {
        //...
    }
}

Form the above Source you may observe that java.util.Arrays.ArrayList class doesn't @Override add(index, element), set(index, element), remove(index). So, From inheritance it executes super AbstractList<E> class add() function which throws UnsupportedOperationException.

As AbstractList<E> is an abstract class it provides the implementation to iterator() and listIterator(). So, that we can iterate over the list object.

List<String> list_of_Arrays = Arrays.asList(new String[] { "a", "b" ,"c"});

try {
    list_of_Arrays.add("Yashwanth.M");
} catch(java.lang.UnsupportedOperationException e) {
    System.out.println("List Interface executes AbstractList add() fucntion which throws UnsupportedOperationException.");
}
System.out.println("Arrays ? List : " + list_of_Arrays);

Iterator<String> iterator = list_of_Arrays.iterator();
while (iterator.hasNext()) System.out.println("Iteration : " + iterator.next() );

ListIterator<String> listIterator = list_of_Arrays.listIterator();
while (listIterator.hasNext())    System.out.println("Forward  iteration : " + listIterator.next() );
while(listIterator.hasPrevious()) System.out.println("Backward iteration : " + listIterator.previous());

You can even create Fixed-Size array form Collections class Collections.unmodifiableList(list);

Sample Source:

public class Collections {
    public static <T> List<T> unmodifiableList(List<? extends T> list) {
        return (list instanceof RandomAccess ?
                new UnmodifiableRandomAccessList<>(list) :
                new UnmodifiableList<>(list));
    }
}

A Collection — sometimes called a container — is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data.

@see also

How to open a link in new tab using angular?

I have just discovered an alternative way of opening a new tab with the Router.

On your template,

<a (click)="openNewTab()" >page link</a>

And on your component.ts, you can use serializeUrl to convert the route into a string, which can be used with window.open()

openNewTab() {
  const url = this.router.serializeUrl(
    this.router.createUrlTree(['/example'])
  );

  window.open(url, '_blank');
}

The remote server returned an error: (407) Proxy Authentication Required

Check with your firewall expert. They open the firewall for PROD servers so there is no need to use the Proxy.

Thanks your tip helped me solve my problem:

Had to to set the Credentials in two locations to get past the 407 error:

HttpWebRequest webRequest = WebRequest.Create(uirTradeStream) as HttpWebRequest;
webRequest.Proxy = WebRequest.DefaultWebProxy;
webRequest.Credentials = new NetworkCredential("user", "password", "domain");
webRequest.Proxy.Credentials = new NetworkCredential("user", "password", "domain");

and voila!

How to start an Intent by passing some parameters to it?

putExtra() : This method sends the data to another activity and in parameter, we have to pass key-value pair.

Syntax: intent.putExtra("key", value);

Eg: intent.putExtra("full_name", "Vishnu Sivan");

Intent intent=getIntent() : It gets the Intent from the previous activity.

fullname = intent.getStringExtra(“full_name”) : This line gets the string form previous activity and in parameter, we have to pass the key which we have mentioned in previous activity.

Sample Code:

Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("firstName", "Vishnu");
intent.putExtra("lastName", "Sivan");
startActivity(intent);

MySQL 1062 - Duplicate entry '0' for key 'PRIMARY'

Run the following query in the mysql console:

SHOW CREATE TABLE momento_distribution

Check for the line that looks something like

CONSTRAINT `momento_distribution_FK_1` FOREIGN KEY (`momento_id`) REFERENCES `momento` (`id`)

It may be different, I just put a guess as to what it could be. If you have a foreign key on both 'momento_id' & 'momento_idmember', you will get two foreign key names. The next step is to delete the foreign keys. Run the following queries:

ALTER TABLE momento_distribution DROP FOREIGN KEY momento_distribution_FK_1
ALTER TABLE momento_distribution DROP FOREIGN KEY momento_distribution_FK_2

Be sure to change the foreign key name to what you got from the CREATE TABLE query. Now you don't have any foreign keys so you can easily remove the primary key. Try the following:

ALTER TABLE  `momento_distribution` DROP PRIMARY KEY

Add the required column as follows:

ALTER TABLE  `momento_distribution` ADD  `id` INT( 11 ) NOT NULL  PRIMARY KEY AUTO_INCREMENT FIRST

This query also adds numbers so you won't need to depend on @rowid. Now you need to add the foreign key back to the earlier columns. For that, first make these indexes:

ALTER TABLE  `momento_distribution` ADD INDEX (  `momento_id` )
ALTER TABLE  `momento_distribution` ADD INDEX (  `momento_idmember` )

Now add the foreign keys. Change the Reference Table/column as you need:

ALTER TABLE  `momento_distribution` ADD FOREIGN KEY ( `momento_id`) REFERENCES  `momento` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT 
ALTER TABLE  `momento_distribution` ADD FOREIGN KEY ( `momento_idmember`) REFERENCES  `member` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT 

Hope that helps. If you get any errors, please edit the question with the structure of the reference tables & the error code(s) that you are getting.

IOException: read failed, socket might closed - Bluetooth on Android 4.3

On newer versions of Android, I was receiving this error because the adapter was still discovering when I attempted to connect to the socket. Even though I called the cancelDiscovery method on the Bluetooth adapter, I had to wait until the callback to the BroadcastReceiver's onReceive() method was called with the action BluetoothAdapter.ACTION_DISCOVERY_FINISHED.

Once I waited for the adapter to stop discovery, then the connect call on the socket succeeded.

Call to a member function on a non-object

function page_properties($objPortal) {    
    $objPage->set_page_title($myrow['title']);
}

looks like different names of variables $objPortal vs $objPage

Bash ignoring error for a particular command

More concisely:

! particular_script

From the POSIX specification regarding set -e (emphasis mine):

When this option is on, if a simple command fails for any of the reasons listed in Consequences of Shell Errors or returns an exit status value >0, and is not part of the compound list following a while, until, or if keyword, and is not a part of an AND or OR list, and is not a pipeline preceded by the ! reserved word, then the shell shall immediately exit.

How to create a DataFrame from a text file in Spark

You will not able to convert it into data frame until you use implicit conversion.

val sqlContext = new SqlContext(new SparkContext())

import sqlContext.implicits._

After this only you can convert this to data frame

case class Test(id:String,filed2:String)

val myFile = sc.textFile("file.txt")

val df= myFile.map( x => x.split(";") ).map( x=> Test(x(0),x(1)) ).toDF()

HTML5 pattern for formatting input box to take date mm/dd/yyyy?

Try to use:

pattern="(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/\d{4}"

File path issues in R using Windows ("Hex digits in character string" error)

replace all the \ with \\.

it's trying to escape the next character in this case the U so to insert a \ you need to insert an escaped \ which is \\

Visual Studio loading symbols

Unchecking "Enable JavaScript debugging for ASP.NET (Chrome and IE)" in Tools->Options->Debugging->General resolved my case with unavailability to launch VS2017 debugger with pre-set breakpoints.

typedef fixed length array

From R..'s answer:

However, this is probably a very bad idea, because the resulting type is an array type, but users of it won't see that it's an array type. If used as a function argument, it will be passed by reference, not by value, and the sizeof for it will then be wrong.

Users who don't see that it's an array will most likely write something like this (which fails):

#include <stdio.h>

typedef int twoInts[2];

void print(twoInts *twoIntsPtr);
void intermediate (twoInts twoIntsAppearsByValue);

int main () {
    twoInts a;
    a[0] = 0;
    a[1] = 1;
    print(&a);
    intermediate(a);
    return 0;
}
void intermediate(twoInts b) {
    print(&b);
}

void print(twoInts *c){
    printf("%d\n%d\n", (*c)[0], (*c)[1]);
}

It will compile with the following warnings:

In function ‘intermediate’:
warning: passing argument 1 of ‘print’ from incompatible pointer type [enabled by default]
    print(&b);
     ^
note: expected ‘int (*)[2]’ but argument is of type ‘int **’
    void print(twoInts *twoIntsPtr);
         ^

And produces the following output:

0
1
-453308976
32767

TortoiseGit-git did not exit cleanly (exit code 1)

I have faced this situation and in my case, I was using two git id's simultaneously. so what it does it will update the credentials in the credential Manager

Control Panel\User Accounts\Credential Manager

as shown here

inside Credential Manager, you will find the git hub credentials inside the Generic credentials there you have to update your git credentials.

How to connect TFS in Visual Studio code

Just as Daniel said "Git and TFVC are the two source control options in TFS". Fortunately both are supported for now in VS Code.

You need to install the Azure Repos Extension for Visual Studio Code. The process of installing is pretty straight forward.

  1. Search for Azure Repos in VS Code and select to install the one by Microsoft
  2. Open File -> Preferences -> Settings
  3. Add the following lines to your user settings

    If you have VS 2015 installed on your machine, your path to Team Foundation tool (tf.exe) may look like this:

    {
        "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\IDE\\tf.exe",
        "tfvc.restrictWorkspace": true
    }

    Or for VS 2017:

    {
        "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Enterprise\\Common7\\IDE\\CommonExtensions\\Microsoft\\TeamFoundation\\Team Explorer\\tf.exe",
        "tfvc.restrictWorkspace": true
    }
  4. Open a local folder (repository), From View -> Command Pallette ..., type team signin

  5. Provide user name --> Enter --> Provide password to connect to TFS.

Please refer to below links for more details:

Note that Server Workspaces are not supported:

"TFVC support is limited to Local workspaces":

on installing Azure extension, visual studio code warns you "It appears you are using a Server workspace. Currently, TFVC support is limited to Local workspaces"

python plot normal distribution

Unutbu answer is correct. But because our mean can be more or less than zero I would still like to change this :

x = np.linspace(-3 * sigma, 3 * sigma, 100)

to this :

x = np.linspace(-3 * sigma + mean, 3 * sigma + mean, 100)

How can I get dict from sqlite query?

Or you could convert the sqlite3.Rows to a dictionary as follows. This will give a dictionary with a list for each row.

    def from_sqlite_Row_to_dict(list_with_rows):
    ''' Turn a list with sqlite3.Row objects into a dictionary'''
    d ={} # the dictionary to be filled with the row data and to be returned

    for i, row in enumerate(list_with_rows): # iterate throw the sqlite3.Row objects            
        l = [] # for each Row use a separate list
        for col in range(0, len(row)): # copy over the row date (ie. column data) to a list
            l.append(row[col])
        d[i] = l # add the list to the dictionary   
    return d

Changing the interval of SetInterval while it's running

I had the same question as the original poster, did this as a solution. Not sure how efficient this is ....

interval = 5000; // initial condition
var run = setInterval(request , interval); // start setInterval as "run"

    function request() { 

        console.log(interval); // firebug or chrome log
        clearInterval(run); // stop the setInterval()

         // dynamically change the run interval
        if(interval>200 ){
          interval = interval*.8;
        }else{
          interval = interval*1.2;
        }

        run = setInterval(request, interval); // start the setInterval()

    }

Scanner is never closed

According to the Javadoc of Scanner, it closes the stream when you call it's close method. Generally speaking, the code that creates a resource is also responsible for closing it. System.in was not instantiated by by your code, but by the VM. So in this case it's safe to not close the Scanner, ignore the warning and add a comment why you ignore it. The VM will take care of closing it if needed.

(Offtopic: instead of "amount", the word "number" would be more appropriate to use for a number of players. English is not my native language (I'm Dutch) and I used to make exactly the same mistake.)

How to align the text middle of BUTTON

This is more predictable then "line-height"

_x000D_
_x000D_
.loginBtn {_x000D_
    background:url(images/loginBtn-center.jpg) repeat-x;_x000D_
    width:175px;_x000D_
    height:65px;_x000D_
    margin:20px auto;_x000D_
    border-radius:10px;_x000D_
    -webkit-border-radius:10px;_x000D_
    box-shadow:0 1px 2px #5e5d5b;_x000D_
}_x000D_
_x000D_
.loginBtn span {_x000D_
    display: block;_x000D_
    padding-top: 22px;_x000D_
    text-align: center;_x000D_
    line-height: 1em;_x000D_
}
_x000D_
<div id="loginBtn" class="loginBtn"><span>Log in</span></div>
_x000D_
_x000D_
_x000D_

EDIT (2018): use flexbox

.loginBtn {
    display: flex;
    align-items: center;
    justify-content: center;
}

constant pointer vs pointer on a constant value

The first is a constant pointer to a char and the second is a pointer to a constant char. You didn't touch all the cases in your code:

char * const pc1 = &a; /* You can't make pc1 point to anything else */
const char * pc2 = &a; /* You can't dereference pc2 to write. */

*pc1 = 'c' /* Legal. */
*pc2 = 'c' /* Illegal. */

pc1 = &b; /* Illegal, pc1 is a constant pointer. */
pc2 = &b; /* Legal, pc2 itself is not constant. */

Python3 integer division

Try this:

a = 1
b = 2
int_div  = a // b

How to store an output of shell script to a variable in Unix?

Two simple examples to capture output the pwd command:

$ b=$(pwd)
$ echo $b
/home/user1

or

$ a=`pwd`
$ echo $a
/home/user1

The first way is preferred. Note that there can't be any spaces after the = for this to work.

Example using a short script:

#!/bin/bash

echo "hi there"

then:

$ ./so.sh
hi there
$ a=$(so.sh)
$ echo $a
hi there

In general a more flexible approach would be to return an exit value from the command and use it for further processing, though sometimes we just may want to capture the simple output from a command.

Xcode 9 error: "iPhone has denied the launch request"

It may be code sign issue. Make sure you're signing with developer, not distribution.

Disabled form inputs do not appear in the request

If you absolutely have to have the field disabled and pass the data you could use a javascript to input the same data into a hidden field (or just set the hidden field too). This would allow you to have it disabled but still post the data even though you'd be posting to another page.

RESTful Authentication

To answer this question from my understanding...

An authentication system that uses REST so that you do not need to actually track or manage the users in your system. This is done by using the HTTP methods POST, GET, PUT, DELETE. We take these 4 methods and think of them in terms of database interaction as CREATE, READ, UPDATE, DELETE (but on the web we use POST and GET because that is what anchor tags support currently). So treating POST and GET as our CREATE/READ/UPDATE/DELETE (CRUD) then we can design routes in our web application that will be able to deduce what action of CRUD we are achieving.

For example, in a Ruby on Rails application we can build our web app such that if a user who is logged in visits http://store.com/account/logout then the GET of that page can viewed as the user attempting to logout. In our rails controller we would build an action in that logs the user out and sends them back to the home page.

A GET on the login page would yield a form. a POST on the login page would be viewed as a login attempt and take the POST data and use it to login.

To me, it is a practice of using HTTP methods mapped to their database meaning and then building an authentication system with that in mind you do not need to pass around any session id's or track sessions.

I'm still learning -- if you find anything I have said to be wrong please correct me, and if you learn more post it back here. Thanks.

What is the difference between Serialization and Marshaling?

My understanding of marshalling is different to the other answers.

Serialization:

To Produce or rehydrate a wire-format version of an object graph utilizing a convention.

Marshalling:

To Produce or rehydrate a wire-format version of an object graph by utilizing a mapping file, so that the results can be customized. The tool may start by adhering to a convention, but the important difference is the ability to customize results.

Contract First Development:

Marshalling is important within the context of contract first development.

  • Its possible to make changes to an internal object graph, while keeping the external interface stable over time. This way all of the service subscribers won't have to be modified for every trivial change.
  • Its possible to map the results across different languages. For example from the property name convention of one language ('property_name') to another ('propertyName').

Right align and left align text in same HTML table cell

Tor Valamo's answer with a little contribution form my side: use the attribute "nowrap" in the "td" element, and you can remove the "width" specification. Hope it helps.

<td nowrap>
  <div style="float:left;">this is left</div>
  <div style="float:right;">this is right</div>
</td>

linux shell script: split string, put them in an array then loop through them

Here's a variation on ashirazi's answer which doesn't rely on $IFS. It does have its own issues which I ouline below.

sentence="one;two;three"
sentence=${sentence//;/$'\n'}  # change the semicolons to white space
for word in $sentence
do
    echo "$word"
done

Here I've used a newline, but you could use a tab "\t" or a space. However, if any of those characters are in the text it will be split there, too. That's the advantage of $IFS - it can not only enable a separator, but disable the default ones. Just make sure you save its value before you change it - as others have suggested.

How to fix docker: Got permission denied issue

you can follow these steps and this will work for you:

  1. create a docker group sudo groupadd docker
  2. add your user to this group sudo usermod -aG docker $USER
  3. list the groups to make sure that docker group created successfully by running this command groups
  4. run the following command also to change the session for docker group newgrp docker
  5. change the group ownership for file docker.socksudo chown root:docker /var/run/docker.sock
  6. change the ownership for .docker directory sudo chown "$USER":"$USER" /home/"$USER"/.docker -R
  7. finally sudo chmod g+rwx "$HOME/.docker" -R

After that test you can run docker ps -a

Convert a Python list with strings all to lowercase or uppercase

For this sample the comprehension is fastest

$ python -m timeit -s 's=["one","two","three"]*1000' '[x.upper for x in s]'
1000 loops, best of 3: 809 usec per loop

$ python -m timeit -s 's=["one","two","three"]*1000' 'map(str.upper,s)'
1000 loops, best of 3: 1.12 msec per loop

$ python -m timeit -s 's=["one","two","three"]*1000' 'map(lambda x:x.upper(),s)'
1000 loops, best of 3: 1.77 msec per loop

changing permission for files and folder recursively using shell command in mac

The issue is that the * is getting interpreted by your shell and is expanding to a file named TEST_FILE that happens to be in your current working directory, so you're telling find to execute the command named TEST_FILE which doesn't exist. I'm not sure what you're trying to accomplish with that *, you should just remove it.

Furthermore, you should use the idiom -exec program '{}' \+ instead of -exec program '{}' \; so that find doesn't fork a new process for each file. With ;, a new process is forked for each file, whereas with +, it only forks one process and passes all of the files on a single command line, which for simple programs like chmod is much more efficient.

Lastly, chmod can do recursive changes on its own with the -R flag, so unless you need to search for specific files, just do this:

chmod -R 777 /Users/Test/Desktop/PATH

Escaping single quotes in JavaScript string for JavaScript evaluation

There are two ways to escaping the single quote in JavaScript.

1- Use double-quote or backticks to enclose the string.

Example: "fsdsd'4565sd" or `fsdsd'4565sd`.

2- Use backslash before any special character, In our case is the single quote

Example:strInputString = strInputString.replace(/ ' /g, " \\' ");

Note: use a double backslash.

Both methods work for me.