Programs & Examples On #Jquery cookie

A simple, lightweight jQuery plugin for reading, writing and deleting cookies.

jquery save json data object in cookie

It is not good practice to save the value that is returned from JSON.stringify(userData) to a cookie; it can lead to a bug in some browsers.

Before using it, you should convert it to base64 (using btoa), and when reading it, convert from base64 (using atob).

val = JSON.stringify(userData)
val = btoa(val)

write_cookie(val)

How to delete a cookie using jQuery?

You can try this:

$.removeCookie('the_cookie', { path: '/' });

source: https://github.com/carhartl/jquery-cookie#readme

How can I control the speed that bootstrap carousel slides in items?

In your main.js file or bootstrap.js, change the value of autoplayTimeout

_x000D_
_x000D_
    $('.carousel').each(function () {
        $(this).owlCarousel({
            nav: $(this).data('nav'),
            dots: $(this).data('dots'),
            loop: $(this).data('loop'),
            margin: $(this).data('space'),
            center: $(this).data('center'),
            dotsSpeed: $(this).data('speed'),
            autoplay: $(this).data('autoplay'),
            transitionStyle: $(this).data('transition'),
            animateOut: $(this).data('animate-out'),
            animateIn: $(this).data('animate-in'),
            autoplayTimeout: 3000,
            responsive: {
                0: {
                    items: 1,
                },
                400: {
                    items: $(this).data('slide-sm'),
                },
                700: {
                    items: $(this).data('slide-md'),
                },
                1000: {
                    items: $(this).data('slide'),
                }
            }
        });
    });
_x000D_
_x000D_
_x000D_

How to auto-format code in Eclipse?

On Windows and Linux : Ctrl + Shift + F

On Mac : ? + ? + F

(Alternatively you can press Format in Main Menu > Source)

How to show a dialog to confirm that the user wishes to exit an Android Activity?

Have modified @user919216 code .. and made it compatible with WebView

@Override
public void onBackPressed() {
    if (webview.canGoBack()) {
        webview.goBack();

    }
    else
    {
     AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
       .setCancelable(false)
       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                finish();
           }
       })
       .setNegativeButton("No", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
           }
       });
AlertDialog alert = builder.create();
alert.show();
    }

}

Which is better: <script type="text/javascript">...</script> or <script>...</script>

You need to use <script type="text/javascript"> </script> unless you're using html5. In that case you are encouraged to prefer <script> ... </script> (because type attribute is specified by default to that value)

Javascript - removing undefined fields from an object

One could also use the JQuery filter for objects

var newobj = $(obj).filter(function(key) {
    return $(this)[key]!== undefined;
  })[0];

Demo here

How to download all dependencies and packages to directory

This will download all packages and dependencies (no already installed) to a directory of your choice:

sudo apt-get install -d -o Dir::Cache=/path-to/directory/apt/cache -o Dir::State::Lists=/path-to/directory/apt/lists packages

Make sure /path-to/directory/apt/cache and /path-to/directory/apt/lists exist. If you don't set -o Dir::Cache it points to /var/cache/apt, Dir::State::Lists points to /var/lib/apt/lists (which keeps the index files of available packages)

Both -o options can be used with update and upgrade instead of install.

On different machine run the same command without '-d'

How do I change button size in Python?

I've always used .place() for my tkinter widgets. place syntax

You can specify the size of it just by changing the keyword arguments!

Of course, you will have to call .place() again if you want to change it.

Works in python 3.8.2, if you're wondering.

Change R default library path using .libPaths in Rprofile.site fails to work

getwd()
# [1] "C:/Users/..../software/My R studio"

copy the above link with double inverted comma

.libPaths(new="C:/Users/..../software/My R studio")

Your default path will change for installing pakages

How to Create a Form Dynamically Via Javascript

some thing as follows ::

Add this After the body tag

This is a rough sketch, you will need to modify it according to your needs.

<script>
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");

var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");

var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");

f.appendChild(i);
f.appendChild(s);

//and some more input elements here
//and dont forget to add a submit button

document.getElementsByTagName('body')[0].appendChild(f);

</script>

Getting a machine's external IP address with Python

Use requests module:

import requests

myip = requests.get('https://www.wikipedia.org').headers['X-Client-IP']

print("\n[+] Public IP: "+myip)

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!

Passing multiple values for same variable in stored procedure

Your stored procedure is designed to accept a single parameter, Arg1List. You can't pass 4 parameters to a procedure that only accepts one.

To make it work, the code that calls your procedure will need to concatenate your parameters into a single string of no more than 3000 characters and pass it in as a single parameter.

An existing connection was forcibly closed by the remote host

I had this issue when i tried to connect to postgresql while i'm using microsoft sutdio for mssql :)

How do I write a compareTo method which compares objects?

Listen to @milkplusvellocet, I'd recommend you to implement the Comparable interface to your class as well.

Just contributing to the answers of others:

String.compareTo() will tell you how different a string is from another.

e.g. System.out.println( "Test".compareTo("Tesu") ); will print -1 and System.out.println( "Test".compareTo("Tesa") ); will print 19

and nerdy and geeky one-line solution to this task would be:

return this.lastName.equals(s.getLastName()) ? this.lastName.compareTo(s.getLastName()) : this.firstName.compareTo(s.getFirstName());

Explanation:

this.lastName.equals(s.getLastName()) checks whether lastnames are the same or not this.lastName.compareTo(s.getLastName()) if yes, then returns comparison of last name. this.firstName.compareTo(s.getFirstName()) if not, returns the comparison of first name.

typeof operator in C

Since typeof is a compiler extension, there is not really a definition for it, but in the tradition of C it would be an operator, e.g sizeof and _Alignof are also seen as an operators.

And you are mistaken, C has dynamic types that are only determined at run time: variable modified (VM) types.

size_t n = strtoull(argv[1], 0, 0);
double A[n][n];
typeof(A) B;

can only be determined at run time.

How to access accelerometer/gyroscope data from Javascript?

Can't add a comment to the excellent explanation in the other post but wanted to mention that a great documentation source can be found here.

It is enough to register an event function for accelerometer like so:

if(window.DeviceMotionEvent){
  window.addEventListener("devicemotion", motion, false);
}else{
  console.log("DeviceMotionEvent is not supported");
}

with the handler:

function motion(event){
  console.log("Accelerometer: "
    + event.accelerationIncludingGravity.x + ", "
    + event.accelerationIncludingGravity.y + ", "
    + event.accelerationIncludingGravity.z
  );
}

And for magnetometer a following event handler has to be registered:

if(window.DeviceOrientationEvent){
  window.addEventListener("deviceorientation", orientation, false);
}else{
  console.log("DeviceOrientationEvent is not supported");
}

with a handler:

function orientation(event){
  console.log("Magnetometer: "
    + event.alpha + ", "
    + event.beta + ", "
    + event.gamma
  );
}

There are also fields specified in the motion event for a gyroscope but that does not seem to be universally supported (e.g. it didn't work on a Samsung Galaxy Note).

There is a simple working code on GitHub

phpMyAdmin access denied for user 'root'@'localhost' (using password: NO)

You may had set different passwords for user 'root' or have been changed your password. I had same error as :

mysqli_real_connect(): (HY000/1045): Access denied for user 'root'@'localhost' (using password: YES)

and I found that my root password for phpmyAdmin is not same on both 'mysql' and 'phpmyadmin' databases, so I updated my password for 'phpmyadmin' database same as 'mysql' database as follow:

sudo gedit /etc/phpmyadmin/config-db.php

and update the fields

$dbuser='root';

$dbpass='myNewPassword'; <-- update your new password here

Best wishes!

is there any IE8 only css hack?

Doing something like this should work for you.

<!--[if IE 8]> 
<div id="IE8">
<![endif]--> 

*Your content* 

<!--[if IE 8]> 
</div>
<![endif]--> 

Then your CSS can look like this:

#IE8 div.something
{ 
    color: purple; 
}

Passing arguments to "make run"

TL;DR don't try to do this

$ make run arg

instead create script:

#! /bin/sh
# rebuild prog if necessary
make prog
# run prog with some arguments
./prog "$@"

and do this:

$ ./buildandrunprog.sh arg

answer to the stated question:

you can use a variable in the recipe

run: prog
    ./prog $(var)

then pass a variable assignment as an argument to make

$ make run var=arg

this will execute ./prog arg.

but beware of pitfalls. i will elaborate about the pitfalls of this method and other methods further down.


answer to the assumed intention behind the question:

the assumption: you want to run prog with some arguments but have it rebuild before running if necessary.

the answer: create a script which rebuilds if necessary then runs prog with args

#! /bin/sh
# rebuild prog if necessary
make prog
# run prog with some arguments
./prog "$@"

this script makes the intention very clear. it uses make to do what it is good for: building. it uses a shell script to do what it is good for: batch processing.

plus you can do whatever else you might need with the full flexibility and expressiveness of a shell script without all the caveats of a makefile.

also the calling syntax is now practically identical:

$ ./buildandrunprog.sh foo "bar baz"

compare to:

$ ./prog foo "bar baz"

contrast to

$ make run var="foo bar\ baz"

background:

make is not designed to pass arguments to a target. all arguments on the command line are interpreted either as a goal (a.k.a. target), as an option, or as a variable assignment.

so if you run this:

$ make run foo --wat var=arg

make will interpret run and foo as goals (targets) to update according to their recipes. --wat as an option for make. and var=arg as a variable assignment.

for more details see: https://www.gnu.org/software/make/manual/html_node/Goals.html#Goals

for the terminology see: https://www.gnu.org/software/make/manual/html_node/Rule-Introduction.html#Rule-Introduction


about the variable assignment method and why i recommend against it

$ make run var=arg

and the variable in the recipe

run: prog
    ./prog $(var)

this is the most "correct" and straightforward way to pass arguments to a recipe. but while it can be used to run a program with arguments it is certainly not designed to be used that way. see https://www.gnu.org/software/make/manual/html_node/Overriding.html#Overriding

in my opinion this has one big disadvantage: what you want to do is run prog with argument arg. but instead of writing:

$ ./prog arg

you are writing:

$ make run var=arg

this gets even more awkward when trying to pass multiple arguments or arguments containing spaces:

$ make run var="foo bar\ baz"
./prog foo bar\ baz
argcount: 2
arg: foo
arg: bar baz

compare to:

$ ./prog foo "bar baz"
argcount: 2
arg: foo
arg: bar baz

for the record this is what my prog looks like:

#! /bin/sh
echo "argcount: $#"
for arg in "$@"; do
  echo "arg: $arg"
done

also note that you should not put $(var) in quotes in the makefile:

run: prog
    ./prog "$(var)"

because then prog will always get just one argument:

$ make run var="foo bar\ baz"
./prog "foo bar\ baz"
argcount: 1
arg: foo bar\ baz

all this is why i recommend against this route.


for completeness here are some other methods to "pass arguments to make run".

method 1:

run: prog
    ./prog $(filter-out $@, $(MAKECMDGOALS))

%:
    @true

super short explanation: filter out current goal from list of goals. create catch all target (%) which does nothing to silently ignore the other goals.

method 2:

ifeq (run, $(firstword $(MAKECMDGOALS)))
  runargs := $(wordlist 2, $(words $(MAKECMDGOALS)), $(MAKECMDGOALS))
  $(eval $(runargs):;@true)
endif

run:
    ./prog $(runargs)

super short explanation: if the target is run then remove the first goal and create do nothing targets for the remaining goals using eval.

both will allow you to write something like this

$ make run arg1 arg2

for deeper explanation study the manual of make: https://www.gnu.org/software/make/manual/html_node/index.html

problems of method 1:

  • arguments that start with a dash will be interpreted by make and not passed as a goal.

    $ make run --foo --bar
    

    workaround

    $ make run -- --foo --bar
    
  • arguments with an equal sign will be interpreted by make and not passed

    $ make run foo=bar
    

    no workaround

  • arguments with spaces is awkward

    $ make run foo "bar\ baz"
    

    no workaround

  • if an argument happens to be run (equal to the target) it will also be removed

    $ make run foo bar run
    

    will run ./prog foo bar instead of ./prog foo bar run

    workaround possible with method 2

  • if an argument is a legitimate target it will also be run.

    $ make run foo bar clean
    

    will run ./prog foo bar clean but also the recipe for the target clean (assuming it exists).

    workaround possible with method 2

  • when you mistype a legitimate target it will be silently ignored because of the catch all target.

    $ make celan
    

    will just silently ignore celan.

    workaround is to make everything verbose. so you see what happens. but that creates a lot of noise for the legitimate output.

problems of method 2:

  • if an argument has same name as an existing target then make will print a warning that it is being overwritten.

    no workaround that i know of

  • arguments with an equal sign will still be interpreted by make and not passed

    no workaround

  • arguments with spaces is still awkward

    no workaround

  • arguments with space breaks eval trying to create do nothing targets.

    workaround: create the global catch all target doing nothing as above. with the problem as above that it will again silently ignore mistyped legitimate targets.

  • it uses eval to modify the makefile at runtime. how much worse can you go in terms of readability and debugability and the Principle of least astonishment.

    workaround: don't do this!!1 instead write a shell script that runs make and then runs prog.

i have only tested using gnu make. other makes may have different behaviour.


TL;DR don't try to do this

$ make run arg

instead create script:

#! /bin/sh
# rebuild prog if necessary
make prog
# run prog with some arguments
./prog "$@"

and do this:

$ ./buildandrunprog.sh arg

Force file download with php using header()

Based on Farhan Sahibole's answer:

        header('Content-Disposition: attachment; filename=Image.png');
        header('Content-Type: application/octet-stream'); // Downloading on Android might fail without this
        ob_clean();

        readfile($file);

This is all I needed for this to work. I stripped off anything that isn't required for this to work.

Key is to use ob_clean();

How to keep a Python script output window open?

You can just write

input()

at the end of your code

therefore when you run you script it will wait for you to enter something

{ENTER for example}

Android: Color To Int conversion

I think it should be R.color.black

Also take a look at Converting android color string in runtime into int

How to add a boolean datatype column to an existing table in sql?

Below query worked for me with default value false;

ALTER TABLE cti_contract_account ADD ready_to_audit BIT DEFAULT 0 NOT NULL;

SQL count rows in a table

Why don't you just right click on the table and then properties -> Storage and it would tell you the row count. You can use the below for row count in a view

SELECT SUM (row_count) 
FROM sys.dm_db_partition_stats 
WHERE object_id=OBJECT_ID('Transactions')    
AND (index_id=0 or index_id=1)`

How to create a .jar file or export JAR in IntelliJ IDEA (like Eclipse Java archive export)?

You didn't specify your IDEA version. Before 9.0 use Build | Build Jars, in IDEA 9.0 use Project Structure | Artifacts.

Java getHours(), getMinutes() and getSeconds()

For a time difference, note that the calendar starts at 01.01.1970, 01:00, not at 00:00. If you're using java.util.Date and java.text.SimpleDateFormat, you will have to compensate for 1 hour:

long start = System.currentTimeMillis();
long end = start + (1*3600 + 23*60 + 45) * 1000 + 678; // 1 h 23 min 45.678 s
Date timeDiff = new Date(end - start - 3600000); // compensate for 1h in millis
SimpleDateFormat timeFormat = new SimpleDateFormat("H:mm:ss.SSS");
System.out.println("Duration: " + timeFormat.format(timeDiff));

This will print:

Duration: 1:23:45.678

How to add dll in c# project

The DLL must be present at all times - as the name indicates, a reference only tells VS that you're trying to use stuff from the DLL. In the project file, VS stores the actual path and file name of the referenced DLL. If you move or delete it, VS is not able to find it anymore.

I usually create a libs folder within my project's folder where I copy DLLs that are not installed to the GAC. Then, I actually add this folder to my project in VS (show hidden files in VS, then right-click and "Include in project"). I then reference the DLLs from the folder, so when checking into source control, the library is also checked in. This makes it much easier when more than one developer will have to change the project.

(Please make sure to set the build type to "none" and "don't copy to output folder" for the DLL in your project.)

PS: I use a German Visual Studio, so the captions I quoted may not exactly match the English version...

How to set the component size with GridLayout? Is there a better way?

You need to try one of the following:

  1. GridBagLayout
  2. MigLayout
  3. SpringLayout

They offer many more features and will be easier to get what you are looking for.

jQuery get values of checked checkboxes into array

var idsArr = [];

$('#tableID').find('input[type=checkbox]:checked').each(function() {
    idsArr .push(this.value);
});

console.log(idsArr);

Java optional parameters

Overloading is fine, but if there's a lot of variables that needs default value, you will end up with :

public void methodA(A arg1) {  }
public void methodA( B arg2,) {  }
public void methodA(C arg3) {  }
public void methodA(A arg1, B arg2) {  }
public void methodA(A arg1, C arg3) {  }
public void methodA( B arg2, C arg3) {  }
public void methodA(A arg1, B arg2, C arg3) {  }

So I would suggest use the Variable Argument provided by Java. Here's a link for explanation.

How do I minimize the command prompt from my bat file

One way to 'minimise' the cmd window is to reduce the size of the console using something like...

echo DO NOT CLOSE THIS WINDOW
MODE CON COLS=30 LINES=2

You can reduce the COLS to about 18 and the LINES to 1 if you wish. The advantage is that it works under WinPE, 32-bit or 64-bit, and does not require any 3rd party utility.

How to check command line parameter in ".bat" file?

In addition to the other answers, which I subscribe, you may consider using the /I switch of the IF command.

... the /I switch, if specified, says to do case insensitive string compares.

it may be of help if you want to give case insensitive flexibility to your users to specify the parameters.

IF /I "%1"=="-b" GOTO SPECIFIC

Best way to format if statement with multiple conditions

Other answers explain why the first option is normally the best. But if you have multiple conditions, consider creating a separate function (or property) doing the condition checks in option 1. This makes the code much easier to read, at least when you use good method names.

if(MyChecksAreOk()) { Code to execute }

...

private bool MyChecksAreOk()
{ 
    return ConditionOne && ConditionTwo && ConditionThree;
}

It the conditions only rely on local scope variables, you could make the new function static and pass in everything you need. If there is a mix, pass in the local stuff.

jquery datatables default sort

I had this problem too. I had used stateSave option and that made this problem.
Remove this option and problem is solved.

Remove a HTML tag but keep the innerHtml

Another native solution (in coffee):

el = document.getElementsByTagName 'b'

docFrag = document.createDocumentFragment()
docFrag.appendChild el.firstChild while el.childNodes.length

el.parentNode.replaceChild docFrag, el

I don't know if it's faster than user113716's solution, but it might be easier to understand for some.

How to avoid Python/Pandas creating an index in a saved csv?

If you want a good format the next statement is the best:

dataframe_prediction.to_csv('filename.csv', sep=',', encoding='utf-8', index=False)

In this case you have got a csv file with ',' as separate between columns and utf-8 format. In addition, numerical index won't appear.

Tree implementation in Java (root, parents and children)

import java.util.ArrayList;
import java.util.List;

public class Node<T> {
    private List<Node<T>> children = new ArrayList<Node<T>>();
    private Node<T> parent = null;
    private T data = null;

    public Node(T data) {
        this.data = data;
    }

    public Node(T data, Node<T> parent) {
        this.data = data;
        this.parent = parent;
    }

    public List<Node<T>> getChildren() {
        return children;
    }

    public void setParent(Node<T> parent) {
        parent.addChild(this);
        this.parent = parent;
    }

    public void addChild(T data) {
        Node<T> child = new Node<T>(data);
        child.setParent(this);
        this.children.add(child);
    }

    public void addChild(Node<T> child) {
        child.setParent(this);
        this.children.add(child);
    }

    public T getData() {
        return this.data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public boolean isRoot() {
        return (this.parent == null);
    }

    public boolean isLeaf() {
        return this.children.size == 0;
    }

    public void removeParent() {
        this.parent = null;
    }
}

Example:

import java.util.List;

Node<String> parentNode = new Node<String>("Parent"); 
Node<String> childNode1 = new Node<String>("Child 1", parentNode);
Node<String> childNode2 = new Node<String>("Child 2");     

childNode2.setParent(parentNode); 

Node<String> grandchildNode = new Node<String>("Grandchild of parentNode. Child of childNode1", childNode1); 
List<Node<String>> childrenNodes = parentNode.getChildren();

How to show progress dialog in Android?

when you call in oncreate()

new LoginAsyncTask ().execute();

Here how to use in flow..

ProgressDialog progressDialog;

  private class LoginAsyncTask extends AsyncTask<Void, Void, Void> {
  @Override
    protected void onPreExecute() {
        progressDialog= new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Please wait...");
        progressDialog.show();
        super.onPreExecute();
    }

     protected Void doInBackground(Void... args) {
        // Parsse response data
        return null;
     }

     protected void onPostExecute(Void result) {
        if (progressDialog.isShowing())
                        progressDialog.dismiss();
        //move activity
        super.onPostExecute(result);
     }
 }

How to add footnotes to GitHub-flavoured Markdown?

GitHub Flavored Markdown doesn't support footnotes, but you can manually fake it¹ with Unicode characters or superscript tags, e.g. <sup>1</sup>.

¹Of course this isn't ideal, as you are now responsible for maintaining the numbering of your footnotes. It works reasonably well if you only have one or two, though.

Fuzzy matching using T-SQL

Regarding de-duping things your string split and match is great first cut. If there are known items about the data that can be leveraged to reduce workload and/or produce better results, it is always good to take advantage of them. Bear in mind that often for de-duping it is impossible to entirely eliminate manual work, although you can make that much easier by catching as much as you can automatically and then generating reports of your "uncertainty cases."

Regarding name matching: SOUNDEX is horrible for quality of matching and especially bad for the type of work you are trying to do as it will match things that are too far from the target. It's better to use a combination of double metaphone results and the Levenshtein distance to perform name matching. With appropriate biasing this works really well and could probably be used for a second pass after doing a cleanup on your knowns.

You may also want to consider using an SSIS package and looking into Fuzzy Lookup and Grouping transformations (http://msdn.microsoft.com/en-us/library/ms345128(SQL.90).aspx).

Using SQL Full-Text Search (http://msdn.microsoft.com/en-us/library/cc879300.aspx) is a possibility as well, but is likely not appropriate to your specific problem domain.

How do I use the lines of a file as arguments of a command?

command `< file`

will pass file contents to the command on stdin, but will strip newlines, meaning you couldn't iterate over each line individually. For that you could write a script with a 'for' loop:

for line in `cat input_file`; do some_command "$line"; done

Or (the multi-line variant):

for line in `cat input_file`
do
    some_command "$line"
done

Or (multi-line variant with $() instead of ``):

for line in $(cat input_file)
do
    some_command "$line"
done

References:

  1. For loop syntax: https://www.cyberciti.biz/faq/bash-for-loop/

What programming languages can one use to develop iPhone, iPod Touch and iPad (iOS) applications?

What programming languages can one use to develop iPhone, iPod Touch and iPad (iOs) applications?

Ruby, Python, Lua, Scheme, Lisp, Smalltalk, C#, Haskell, ActionScript, JavaScript, Objective-C, C++, C. That's just the ones that pop into my head right now. I'm sure there's hundreds if not thousands of others. (E.g. there's no reason why you couldn't use any .NET language with MonoTouch, i.e. VB.NET, F#, Nemerle, Boo, Cobra, ...)

Also are there plans in the future to expand the amount of programming languages that iOs will support?

Sure. Pretty much every programming language community on this planet is currently working on getting their language to run on iOS.

Also, a lot of people are working on programming languages specifically designed for touch devices such as iPod touch, iPhone and iPad, e.g. Phil Mercurio's Thyrd language.

How to plot time series in python

Convert your x-axis data from text to datetime.datetime, use datetime.strptime:

>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
 datetime.datetime(2012, 5, 31, 19, 0)

This is an example of how to plot data once you have an array of datetimes:

import matplotlib.pyplot as plt
import datetime
import numpy as np

x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)

plt.plot(x,y)
plt.show()

enter image description here

How to convert string to integer in C#

int a = int.Parse(myString);

or better yet, look into int.TryParse(string)

How to pass a form input value into a JavaScript function

There are several ways to approach this. Personally, I would avoid in-line scripting. Since you've tagged jQuery, let's use that.

HTML:

<form>
    <input type="text" id="formValueId" name="valueId"/>
    <input type="button" id="myButton" />
</form>

JavaScript:

$(document).ready(function() {
    $('#myButton').click(function() {
      foo($('#formValueId').val());
    });
});

Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>

First Install Dynamic Tools --> NuGet Package Manager --> Package Manager Console

install-package System.Linq.Dynamic

Add Namespace using System.Linq.Dynamic;

Now you can use OrderBy("Name, Age DESC")

ImportError: No module named PytQt5

After getting the help from @Blender, @ekhumoro and @Dan, I understand the Linux and Python more than before. Thank you. I got the an idea by @ekhumoro, it is I didn't install PyQt5 correctly. So I delete PyQt5 folder and download again. And redo everything from very start.

After redoing, I got the error as my last update at my question. So, when I search at stack, I got the following solution from here

sudo ln -s /usr/include/python2.7 /usr/local/include/python2.7

And then, I did "sudo make" and "sudo make install" step by step. After "sudo make install", I got the following error. But I ignored it and I created a simple design with qt designer. And I converted it into python file by pyuic5. Everything are going well.

install -m 755 -p /home/thura/PyQt/pyuic5 /usr/bin/
strip /usr/bin/pyuic5
strip:/usr/bin/pyuic5: File format not recognized
make: [install_pyuic5] Error 1 (ignored)

null vs empty string in Oracle

In oracle an empty varchar2 and null are treated the same, and your observations show that.

when you write:

select * from table where a = '';

its the same as writing

select * from table where a = null;

and not a is null

which will never equate to true, so never return a row. same on the insert, a NOT NULL means you cant insert a null or an empty string (which is treated as a null)

Detecting iOS / Android Operating system

For this and other kind of client detections I suggest this js library: http://hictech.github.io/navJs/tester/index.html

For your specific answer use:

navJS.isIOS() || navJS.isAndroid()

C++ printing boolean, what is displayed?

0 will get printed.

As in C++ true refers to 1 and false refers to 0.

In case, you want to print false instead of 0,then you have to sets the boolalpha format flag for the str stream.

When the boolalpha format flag is set, bool values are inserted/extracted by their textual representation: either true or false, instead of integral values.

#include <iostream>
int main()
{
  std::cout << std::boolalpha << false << std::endl;
}

output:

false

IDEONE

(13: Permission denied) while connecting to upstream:[nginx]

13-permission-denied-while-connecting-to-upstreamnginx on centos server -

setsebool -P httpd_can_network_connect 1

How do I manage conflicts with git submodules?

I have not seen that exact error before. But I have a guess about the trouble you are encountering. It looks like because the master and one.one branches of supery contain different refs for the subby submodule, when you merge changes from master git does not know which ref - v1.0 or v1.1 - should be kept and tracked by the one.one branch of supery.

If that is the case, then you need to select the ref that you want and commit that change to resolve the conflict. Which is exactly what you are doing with the reset command.

This is a tricky aspect of tracking different versions of a submodule in different branches of your project. But the submodule ref is just like any other component of your project. If the two different branches continue to track the same respective submodule refs after successive merges, then git should be able to work out the pattern without raising merge conflicts in future merges. On the other hand you if switch submodule refs frequently you may have to put up with a lot of conflict resolving.

Javascript - check array for value

This should do it:

for (var i = 0; i < bank_holidays.length; i++) {
    if (bank_holidays[i] === '06/04/2012') {
        alert('LOL');
    }
}

jsFiddle

Cannot find "Package Explorer" view in Eclipse

The simplest, and best long-term solution

Go to the main menu on top of Eclipse and locate Window next to Run and expand it.

 Window->Reset Perspective... to restore all views to their defaults

It will reset the default setting.

Javascript onHover event

Can you clarify your question? What is "ohHover" in this case and how does it correspond to a delay in hover time?

That said, I think what you probably want is...

var timeout;
element.onmouseover = function(e) {
    timeout = setTimeout(function() {
        // ...
    }, delayTimeMs)
};
element.onmouseout = function(e) {
    if(timeout) {
        clearTimeout(timeout);
    }
};

Or addEventListener/attachEvent or your favorite library's event abstraction method.

Why are static variables considered evil?

There are two main questions in your post.

First, about static variables. Static variables are completelly unnecesary and it's use can be avoided easily. In OOP languajes in general, and in Java particularlly, function parameters are pased by reference, this is to say, if you pass an object to a funciont, you are passing a pointer to the object, so you dont need to define static variables since you can pass a pointer to the object to any scope that needs this information. Even if this implies that yo will fill your memory with pointers, this will not necesary represent a poor performance because actual memory pagging systems are optimized to handle with this, and they will maintain in memory the pages referenced by the pointers you passed to the new scope; usage of static variables may cause the system to load the memory page where they are stored when they need to be accessed (this will happen if the page has not been accesed in a long time). A good practice is to put all that static stuf together in some little "configuration clases", this will ensure the system puts it all in the same memory page.

Second, about static methods. Static methods are not so bad, but they can quickly reduce performance. For example, think about a method that compares two objects of a class and returns a value indicating which of the objects is bigger (tipical comparison method) this method can be static or not, but when invoking it the non static form will be more eficient since it will have to solve only two references (one for each object) face to the three references that will have to solve the static version of the same method (one for the class plus two, one for each object). But as I say, this is not so bad, if we take a look at the Math class, we can find a lot of math functions defined as static methods. This is really more eficient than putting all these methods in the class defining the numbers, because most of them are rarelly used and including all of them in the number class will cause the class to be very complex and consume a lot of resources unnecesarilly.

In concluson: Avoid the use of static variables and find the correct performance equilibrium when dealing with static or non static methods.

PS: Sorry for my english.

PHP parse/syntax errors; and how to solve them

Unexpected T_VARIABLE

An "unexpected T_VARIABLE" means that there's a literal $variable name, which doesn't fit into the current expression/statement structure.

purposefully abstract/inexact operator+$variable diagram

  1. Missing semicolon

    It most commonly indicates a missing semicolon in the previous line. Variable assignments following a statement are a good indicator where to look:

            ?
     func1()
     $var = 1 + 2;     # parse error in line +2
    
  2. String concatenation

    A frequent mishap are string concatenations with forgotten . operator:

                                    ?
     print "Here comes the value: "  $value;
    

    Btw, you should prefer string interpolation (basic variables in double quotes) whenever that helps readability. Which avoids these syntax issues.

    String interpolation is a scripting language core feature. No shame in utilizing it. Ignore any micro-optimization advise about variable . concatenation being faster. It's not.

  3. Missing expression operators

    Of course the same issue can arise in other expressions, for instance arithmetic operations:

                ?
     print 4 + 7 $var;
    

    PHP can't guess here if the variable should have been added, subtracted or compared etc.

  4. Lists

    Same for syntax lists, like in array populations, where the parser also indicates an expected comma , for example:

                                           ?
     $var = array("1" => $val, $val2, $val3 $val4);
    

    Or functions parameter lists:

                                     ?
     function myfunc($param1, $param2 $param3, $param4)
    

    Equivalently do you see this with list or global statements, or when lacking a ; semicolon in a for loop.

  5. Class declarations

    This parser error also occurs in class declarations. You can only assign static constants, not expressions. Thus the parser complains about variables as assigned data:

     class xyz {      ?
         var $value = $_GET["input"];
    

    Unmatched } closing curly braces can in particular lead here. If a method is terminated too early (use proper indentation!), then a stray variable is commonly misplaced into the class declaration body.

  6. Variables after identifiers

    You can also never have a variable follow an identifier directly:

                  ?
     $this->myFunc$VAR();
    

    Btw, this is a common example where the intention was to use variable variables perhaps. In this case a variable property lookup with $this->{"myFunc$VAR"}(); for example.

    Take in mind that using variable variables should be the exception. Newcomers often try to use them too casually, even when arrays would be simpler and more appropriate.

  7. Missing parentheses after language constructs

    Hasty typing may lead to forgotten opening or closing parenthesis for if and for and foreach statements:

            ?
     foreach $array as $key) {
    

    Solution: add the missing opening ( between statement and variable.

                           ?
     if ($var = pdo_query($sql) {
          $result = …
    

    The curly { brace does not open the code block, without closing the if expression with the ) closing parenthesis first.

  8. Else does not expect conditions

         ?
    else ($var >= 0)
    

    Solution: Remove the conditions from else or use elseif.

  9. Need brackets for closure

         ?
    function() use $var {}
    

    Solution: Add brackets around $var.

  10. Invisible whitespace

    As mentioned in the reference answer on "Invisible stray Unicode" (such as a non-breaking space), you might also see this error for unsuspecting code like:

    <?php
                              ?
    $var = new PDO(...);
    

    It's rather prevalent in the start of files and for copy-and-pasted code. Check with a hexeditor, if your code does not visually appear to contain a syntax issue.

See also

Waiting for another flutter command to release the startup lock

If you are using Windows, you can open the task manager and under the 'Processes' tab search for processes named 'dart'. End all those tasks.

Get the cartesian product of a series of lists?

Just to add a bit to what has already been said: if you use sympy, you can use symbols rather than strings which makes them mathematically useful.

import itertools
import sympy

x, y = sympy.symbols('x y')

somelist = [[x,y], [1,2,3], [4,5]]
somelist2 = [[1,2], [1,2,3], [4,5]]

for element in itertools.product(*somelist):
  print element

About sympy.

Python popen command. Wait until the command is finished

I think process.communicate() would be suitable for output having small size. For larger output it would not be the best approach.

How can I set the opacity or transparency of a Panel in WinForms?

Panel with opacity:

public class GlassyPanel : Panel
{
    const int WS_EX_TRANSPARENT = 0x20;  

    int opacity = 50;

    public int Opacity
    {
        get
        {
            return opacity;
        }
        set
        {
            if (value < 0 || value > 100) throw new ArgumentException("Value must be between 0 and 100");
            opacity = value;
        }
    }

    protected override CreateParams CreateParams
    {
        get
        {
            var cp = base.CreateParams;
            cp.ExStyle = cp.ExStyle | WS_EX_TRANSPARENT;

            return cp;
        }
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        using (var b = new SolidBrush(Color.FromArgb(opacity * 255 / 100, BackColor)))
        {
            e.Graphics.FillRectangle(b, ClientRectangle);
        }

        base.OnPaint(e);
    }
}

How to use private Github repo as npm dependency

I wasn't able to make the accepted answer work in a Docker container.

What worked for me was to set the Personal Access Token from github in a file .nextrc

ARG GITHUB_READ_TOKEN
RUN echo -e "machine github.com\n  login $GITHUB_READ_TOKEN" > ~/.netrc 
RUN npm install --only=production --force \
  && npm cache clean --force
RUN rm ~/.netrc

in package.json

"my-lib": "github:username/repo",

fatal error C1010 - "stdafx.h" in Visual Studio how can this be corrected?

Look at https://stackoverflow.com/a/4726838/2963099

Turn off pre compiled headers:

Project Properties -> C++ -> Precompiled Headers

set Precompiled Header to "Not Using Precompiled Header".

Split comma-separated input box values into array in jquery, and loop through it

var array = searchTerms.split(",");

for (var i in array){
     alert(array[i]);
}

Transactions in .net

You could also wrap the transaction up into it's own stored procedure and handle it that way instead of doing transactions in C# itself.

Change IPython/Jupyter notebook working directory

This question keeps coming up when I search for ipython change pwd even though I am not interested in a notebook, but a terminal or qtconsole. Not finding a relevant config entry I tried:

# lines of code to run at IPython startup.
c.InteractiveShellApp.exec_lines = ['%cd /home/paul/mypy']

This is the base level shell class; there are Terminal and Console (and probably notebook) entries that could further customize the action.

From the docs it looks like import statements are most common in the entry, but it appears that many magic commands work as well.

Changing permissions via chmod at runtime errors with "Operation not permitted"

In order to perform chmod, you need to be owner of the file you are trying to modify, or the root user.

Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone

Make sure that your time is in this format HH:MM:SS(PM/AM)

function timeConversion(s) {

    s = s.split(':');
    var time = s[2];
    if(time.charAt(2) === 'A' && parseInt(s[0]) == 12) s[0] = '00';
    if(time.charAt(2) === 'P' && parseInt(s[0]) <12) s[0] = parseInt(s[0])+12;
    if(s[0] >=24) s[0]-=24;
    var x = time.split('').slice(0,2);
    s[2] = x.join('');
    console.log(s.join(':'));
}

jQuery hover and class selector

Since this is a menu, might as well take it to the next level, and clean up the HTML, and make it more semantic by using a list element:

HTML:

  <ul id="menu">
    <li><a href="#">Bla</a></li>
    <li><a href="#">Bla</a></li>
    <li><a href="#">Bla</a></li>
  </ul>

CSS:

#menu {
  margin: 0;
}
#menu li {
  float: left;
  list-style: none;
  margin: 0;
}
#menu li a {
  display: block;
  line-height:30px;
  width:100px;
  background-color:#000;
}
#menu li a:hover {
  background-color:#F00;
}

Adding background image to div using CSS

It is happening because .header-shadow is empty.

Add height to it:

.header-shadow{
    background-image: url('../images/header-shade.jpg');
    background-color: red;
    height: 50px;
}

Fiddle here.

Clear Application's Data Programmatically

I'm just putting the tutorial from the link ihrupin posted here in this post.

package com.hrupin.cleaner;

import java.io.File;

import android.app.Application;
import android.util.Log;

public class MyApplication extends Application {

    private static MyApplication instance;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }

    public static MyApplication getInstance() {
        return instance;
    }

    public void clearApplicationData() {
        File cacheDirectory = getCacheDir();
        File applicationDirectory = new File(cacheDirectory.getParent());
        if (applicationDirectory.exists()) {
            String[] fileNames = applicationDirectory.list();
            for (String fileName : fileNames) {
                if (!fileName.equals("lib")) {
                    deleteFile(new File(applicationDirectory, fileName));
                }
            }
        }
    }

    public static boolean deleteFile(File file) {
        boolean deletedAll = true;
        if (file != null) {
            if (file.isDirectory()) {
                String[] children = file.list();
                for (int i = 0; i < children.length; i++) {
                    deletedAll = deleteFile(new File(file, children[i])) && deletedAll;
                }
            } else {
                deletedAll = file.delete();
            }
        }

        return deletedAll;
    }
}

So if you want a button to do this you need to call MyApplication.getInstance(). clearApplicationData() from within an onClickListener

Update: Your SharedPreferences instance might hold onto your data and recreate the preferences file after you delete it. So your going to want to get your SharedPreferences object and

prefs.edit().clear().commit();

Update:

You need to add android:name="your.package.MyApplication" to the application tag inside AndroidManifest.xml if you had not done so. Else, MyApplication.getInstance() returns null, resulting a NullPointerException.

DSO missing from command line

DSO here means Dynamic Shared Object; since the error message says it's missing from the command line, I guess you have to add it to the command line.

That is, try adding -lpthread to your command line.

Are static methods inherited in Java?

All the public and protected members can be inherited from any class while the default or package members can also be inherited from the class within the same package as that of the superclass. It does not depend whether it is static or non static member.

But it is also true that static member function do not take part in dynamic binding. If the signature of that static method is same in both parent and child class then concept of Shadowing applies, not polymorphism.

Replace text in HTML page with jQuery

Like others mentioned in this thread, replacing the entire body HTML is a bad idea because it reinserts the entire DOM and can potentially break any other javascript that was acting on those elements.

Instead, replace just the text on your page and not the DOM elements themselves using jQuery filter:

  $('body :not(script)').contents().filter(function() {
    return this.nodeType === 3;
  }).replaceWith(function() {
      return this.nodeValue.replace('-9o0-9909','The new string');
  });

this.nodeType is the type of node we are looking to replace the contents of. nodeType 3 is text. See the full list here.

How to generate a HTML page dynamically using PHP?

I'll just update the code to contain the changes, and comment it to so that you can see what's going on clearly...

<?php   
include("templates/header.htm");   

// Set the default name 
$action = 'index'; 
// Specify some disallowed paths 
$disallowed_paths = array('header', 'footer'); 
if (!empty($_GET['action'])) { 
    $tmp_action = basename($_GET['action']); 
    // If it's not a disallowed path, and if the file exists, update $action 
    if (!in_array($tmp_action, $disallowed_paths) && file_exists("templates/{$tmp_action}.htm")) 
        $action = $tmp_action; 
} 
// Include $action 
include("templates/$action.htm"); 

include("templates/footer.htm");

What is the most efficient/elegant way to parse a flat table into a tree?

If elements are in tree order, as shown in your example, you can use something like the following Python example:

delimiter = '.'
stack = []
for item in items:
  while stack and not item.startswith(stack[-1]+delimiter):
    print "</div>"
    stack.pop()
  print "<div>"
  print item
  stack.append(item)

What this does is maintain a stack representing the current position in the tree. For each element in the table, it pops stack elements (closing the matching divs) until it finds the parent of the current item. Then it outputs the start of that node and pushes it to the stack.

If you want to output the tree using indenting rather than nested elements, you can simply skip the print statements to print the divs, and print a number of spaces equal to some multiple of the size of the stack before each item. For example, in Python:

print "  " * len(stack)

You could also easily use this method to construct a set of nested lists or dictionaries.

Edit: I see from your clarification that the names were not intended to be node paths. That suggests an alternate approach:

idx = {}
idx[0] = []
for node in results:
  child_list = []
  idx[node.Id] = child_list
  idx[node.ParentId].append((node, child_list))

This constructs a tree of arrays of tuples(!). idx[0] represents the root(s) of the tree. Each element in an array is a 2-tuple consisting of the node itself and a list of all its children. Once constructed, you can hold on to idx[0] and discard idx, unless you want to access nodes by their ID.

Current time formatting with Javascript

Using Moment.

I can't recommend the use of Moment enough. If you are able to use third-party libraries, I highly recommend doing so. Beyond just formatting, it deals with timezones, parsing, durations and time travel extremely well and will pay dividends in simplicity and time (at the small expense of size, abstraction and performance).

Usage

You wanted something that looked like this:

Friday 2:00pm 1 Feb 2013

Well, with Moment all you need you to do is this:

import Moment from "moment";

Moment().format( "dddd h:mma D MMM YYYY" ); //=> "Wednesday 9:20am 9 Dec 2020"

And if you wanted to match that exact date and time, all you would need to do is this:

import Moment from "moment";

Moment( "2013-2-1 14:00:00" ).format( "dddd h:mma D MMM YYYY" ) ); //=> "Friday 2:00pm 1 Feb 2013"

There's a myriad of other formatting options that can be found here.

Install

Go to their home page to see more detailed instructions, but if you're using npm or yarn it's as simple as:

npm install moment --save

or

yarn add moment

How to scroll to an element?

Just a heads up, I couldn't get these solutions to work on Material UI components. Looks like they don't have the current property.

I just added an empty div amongst my components and set the ref prop on that.

Int or Number DataType for DataAnnotation validation attribute

public class IsNumericAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            decimal val;
            var isNumeric = decimal.TryParse(value.ToString(), out val);

            if (!isNumeric)
            {                   
                return new ValidationResult("Must be numeric");                    
            }
        }

        return ValidationResult.Success;
    }
}

In Bootstrap open Enlarge image in modal

I know your question is tagged as boostrap-modal (althought you didn't mentioned Bootstrap explicity neither), but I loved to see the simple way W3.CSS solved this and I think is good to share it.

  <img src="/myImage.png" style="width:30%;cursor:zoom-in"
  onclick="document.getElementById('modal01').style.display='block'">

  <div id="modal01" class="w3-modal" onclick="this.style.display='none'">
    <div class="w3-modal-content w3-animate-zoom">
      <img src="/myImage.png" style="width:100%">
    </div>
  </div>

I let you a link to the W3School modal image example to see the headers to make W3.CSS work.

Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

I am creating custom textField to make it reusable component for SwiftUI

SwiftUI

struct CustomTextField: View {
    var placeHolder: String
    @Binding var value: String
    
    var lineColor: Color
    var width: CGFloat
    
    var body: some View {
        VStack {
            TextField(self.placeHolder, text: $value)
            .padding()
            .font(.title)
            
            Rectangle().frame(height: self.width)
                .padding(.horizontal, 20).foregroundColor(self.lineColor)
        }
    }
}

Usage:

@Binding var userName: String
@Binding var password: String

var body: some View {
    VStack(alignment: .center) {
        CustomTextField(placeHolder: "Username", value: $userName, lineColor: .white, width: 2)
        CustomTextField(placeHolder: "Password", value: $password, lineColor: .white, width: 2)
    }
}


Swift 5.0

I am using Visual Formatting Language (VFL) here, This will allow adding a line to any UIControl.

You can create a UIView extension class like UIView+Extention.swift

import UIKit

enum LinePosition {
    case top
    case bottom
}

extension UIView {
    func addLine(position: LinePosition, color: UIColor, width: Double) {
        let lineView = UIView()
        lineView.backgroundColor = color
        lineView.translatesAutoresizingMaskIntoConstraints = false // This is important!
        self.addSubview(lineView)

        let metrics = ["width" : NSNumber(value: width)]
        let views = ["lineView" : lineView]
        self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[lineView]|", options:NSLayoutConstraint.FormatOptions(rawValue: 0), metrics:metrics, views:views))

        switch position {
        case .top:
            self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[lineView(width)]", options:NSLayoutConstraint.FormatOptions(rawValue: 0), metrics:metrics, views:views))
            break
        case .bottom:
            self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[lineView(width)]|", options:NSLayoutConstraint.FormatOptions(rawValue: 0), metrics:metrics, views:views))
            break
        }
    }
}

Usage:

textField.addLine(position: .LINE_POSITION_BOTTOM, color: .darkGray, width: 0.5)

Objective C:

You can add this helper method to your global helper class(I used global class method) or in the same view controller(using an instance method).

typedef enum : NSUInteger {
    LINE_POSITION_TOP,
    LINE_POSITION_BOTTOM
} LINE_POSITION;


- (void) addLine:(UIView *)view atPosition:(LINE_POSITION)position withColor:(UIColor *)color lineWitdh:(CGFloat)width {
    // Add line
    UIView *lineView = [[UIView alloc] init];
    [lineView setBackgroundColor:color];
    [lineView setTranslatesAutoresizingMaskIntoConstraints:NO];
    [view addSubview:lineView];
    
    NSDictionary *metrics = @{@"width" : [NSNumber numberWithFloat:width]};
    NSDictionary *views = @{@"lineView" : lineView};
    [view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[lineView]|" options: 0 metrics:metrics views:views]];
    
    switch (position) {
        case LINE_POSITION_TOP:
            [view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[lineView(width)]" options: 0 metrics:metrics views:views]];
            break;
            
        case LINE_POSITION_BOTTOM:
            [view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[lineView(width)]|" options: 0 metrics:metrics views:views]];
            break;
        default: break;
    }
}

Usage:

[self addLine:self.textField atPosition:LINE_POSITION_TOP withColor:[UIColor darkGrayColor] lineWitdh:0.5];

Xamarin code:

 var border = new CALayer();
 nfloat width = 2;
 border.BorderColor = UIColor.Black.CGColor;
 border.Frame = new CoreGraphics.CGRect(0, textField.Frame.Size.Height - width, textField.Frame.Size.Width, textField.Frame.Size.Height);
 border.BorderWidth = width;
 textField.Layer.AddSublayer(border);
 textField.Layer.MasksToBounds = true;

How to convert a String to Bytearray

The easiest way in 2018 should be TextEncoder but the returned element is not byte array, it is Uint8Array. (And not all browsers support it)

let utf8Encode = new TextEncoder();
utf8Encode.encode("eee")
> Uint8Array [ 101, 101, 101 ]

vuejs update parent data from child component

Another way is to pass a reference of your setter from the parent as a prop to the child component, similar to how they do it in React. Say, you have a method updateValue on the parent to update the value, you could instantiate the child component like so: <child :updateValue="updateValue"></child>. Then on the child you will have a corresponding prop: props: {updateValue: Function}, and in the template call the method when the input changes: <input @input="updateValue($event.target.value)">.

Disable future dates in jQuery UI Datepicker

Yes, datepicker supports max date property.

 $("#datepickeraddcustomer").datepicker({  
             dateFormat: "yy-mm-dd",  
             maxDate: new Date()  
        });

TypeError: 'function' object is not subscriptable - Python

It is so simple, you have 2 objects with the same name and when you say: bank_holiday[month] python thinks you wanna run your function and got ERROR.

Just rename your array to bank_holidays <--- add a 's' at the end! like this:

bank_holidays= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month

def bank_holiday(month):
   if month <1 or month > 12:
       print("Error: Out of range")
       return
   print(bank_holidays[month-1],"holiday(s) in this month ")

bank_holiday(int(input("Which month would you like to check out: ")))

How do I convert a PDF document to a preview image in PHP?

You can also get the page count using

$im->getNumberImages();

Then you can can create thumbs of all the pages using a loop, eg.

'file.pdf['.$x.']'

if (boolean == false) vs. if (!boolean)

- Here its more about the coding style than being the functionality....

- The 1st option is very clear, but then the 2nd one is quite elegant... no offense, its just my view..

Show Console in Windows Application?

And yet another belated answer. I couldn't get any output to the console created with AllocConsole as per earlier suggestions, so instead I'm starting with Console application. Then, if the console is not needed:

        [DllImport("kernel32.dll")]
        private static extern IntPtr GetConsoleWindow();

        [DllImport("user32.dll")]
        private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        private const int SW_HIDE = 0;
        private const int SW_SHOW = 5;

        [DllImport("user32.dll", SetLastError = true)]
        static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);

        public static bool HideConsole()
        {
            var hwnd = GetConsoleWindow();
            GetWindowThreadProcessId(hwnd, out var pid);

            if (pid != Process.GetCurrentProcess().Id) // It's not our console - don't mess with it.
                return false;

            ShowWindow(hwnd, SW_HIDE);

            return true;
        }

Inner join with 3 tables in mysql

SELECT
  student.firstname,
  student.lastname,
  exam.name,
  exam.date,
  grade.grade
FROM grade
 INNER JOIN student
   ON student.studentId = grade.fk_studentId
 INNER JOIN exam
   ON exam.examId = grade.fk_examId
 GROUP BY grade.gradeId
 ORDER BY exam.date

How to enable LogCat/Console in Eclipse for Android?

In Eclipse, Goto Window-> Show View -> Other -> Android-> Logcat.

Logcat is nothing but a console of your Emulator or Device.

System.out.println does not work in Android. So you have to handle every thing in Logcat. More Info Look out this Documentation.

Edit 1: System.out.println is working on Logcat. If you use that the Tag will be like System.out and Message will be your message.

How to read integer value from the standard input in Java

check this one:

import java.io.*;
public class UserInputInteger
{
        public static void main(String args[])throws IOException
        {
        InputStreamReader read = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(read);
        int number;
                System.out.println("Enter the number");
                number = Integer.parseInt(in.readLine());
    }
}

When & why to use delegates?

Say you want to write a procedure to integrate some real-valued function f (x) over some interval [a, b]. Say we want to use the 3-Point Gaussian method to do this (any will do, of course).

Ideally we want some function that looks like:

// 'f' is the integrand we want to integrate over [a, b] with 'n' subintervals.
static double Gauss3(Integrand f, double a, double b, int n) {
  double res = 0;

  // compute result
  // ...

  return res;
}

So we can pass in any Integrand, f, and get its definite integral over the closed interval.

Just what type should Integrand be?

Without Delegates

Well, without delegates, we'd need some sort of interface with a single method, say eval declared as follows:

// Interface describing real-valued functions of one variable.
interface Integrand {
  double eval(double x);
}

Then we'd need to create a whole bunch of classes implementing this interface, as follows:

// Some function
class MyFunc1 : Integrand {
  public double eval(double x) {
    return /* some_result */ ;
  }
}

// Some other function
class MyFunc2 : Integrand {
  public double eval(double x) {
    return /* some_result */ ;
  }
}

// etc

Then to use them in our Gauss3 method, we need to invoke it as follows:

double res1 = Gauss3(new MyFunc1(), -1, 1, 16);
double res2 = Gauss3(new MyFunc2(), 0, Math.PI, 16);

And Gauss3 needs to do the look like the following:

static double Gauss3(Integrand f, double a, double b, int n) {
  // Use the integrand passed in:
  f.eval(x);
}

So we need to do all that just to use our arbitrary functions in Guass3.

With Delegates

public delegate double Integrand(double x);

Now we can define some static (or not) functions adhering to that prototype:

class Program {
   public delegate double Integrand(double x);   
   // Define implementations to above delegate 
   // with similar input and output types
   static double MyFunc1(double x) { /* ... */ }
   static double MyFunc2(double x) { /* ... */ }
   // ... etc ...

   public static double Gauss3(Integrand f, ...) { 
      // Now just call the function naturally, no f.eval() stuff.
      double a = f(x); 
      // ...
   }

   // Let's use it
   static void Main() {
     // Just pass the function in naturally (well, its reference).
     double res = Gauss3(MyFunc1, a, b, n);
     double res = Gauss3(MyFunc2, a, b, n);    
   }
}

No interfaces, no clunky .eval stuff, no object instantiation, just simple function-pointer like usage, for a simple task.

Of course, delegates are more than just function pointers under the hood, but that's a separate issue (function chaining and events).

Reset textbox value in javascript

Use it like this:

$("#searchField").focus(function() {
    $(this).val("");
});

It has to work. Otherwise it probably never gets focused.

Angular is automatically adding 'ng-invalid' class on 'required' fields

Try to add the class for validation dynamically, when the form has been submitted or the field is invalid. Use the form name and add the 'name' attribute to the input. Example with Bootstrap:

<div class="form-group" ng-class="{'has-error': myForm.$submitted && (myForm.username.$invalid && !myForm.username.$pristine)}">
    <label class="col-sm-2 control-label" for="username">Username*</label>
    <div class="col-sm-10 col-md-9">
        <input ng-model="data.username" id="username" name="username" type="text" class="form-control input-md" required>
    </div>
</div>

It is also important, that your form has the ng-submit="" attribute:

<form name="myForm" ng-submit="checkSubmit()" novalidate>
 <!-- input fields here -->
 ....

  <button type="submit">Submit</button>
</form>

You can also add an optional function for validation to the form:

//within your controller (some extras...)

$scope.checkSubmit = function () {

   if ($scope.myForm.$valid) {
        alert('All good...'); //next step!

   }
   else {
        alert('Not all fields valid! Do something...');
    }

 }

Now, when you load your app the class 'has-error' will only be added when the form is submitted or the field has been touched. Instead of:
!myForm.username.$pristine

You could also use:
myForm.username.$dirty

The type initializer for 'Oracle.DataAccess.Client.OracleConnection' threw an exception

Ok, when you know for sure other applications that used the same process worked; on your new application make sure you have the data access reference and the three dll files...

I downloaded ODAC1120320Xcopy_32bit this from the Oracle site:

http://www.oracle.com/technetwork/database/windows/downloads/utilsoft-087491.html

Reference: Oracle.DataAccess.dll (ODAC1120320Xcopy_32bit\odp.net4\odp.net\bin\4\Oracle.DataAccess.dll)

Include these 3 files within your project:

  • oci.dll (ODAC1120320Xcopy_32bit\instantclient_11_2\oci.dll)
  • oraociei11.dll (ODAC1120320Xcopy_32bit\instantclient_11_2\oraociei11.dll)
  • OraOps11w.dll (ODAC1120320Xcopy_32bit\odp.net4\bin\OraOps11w.dll)

When I tried to create another application with the correct reference and files I would receive that error message.

The fix: Highlighted all three of the files and selected "Copy To Output" = Copy if newer. I did copy if newer since one of the dll's is above 100MB and any updates I do will not copy those files again.

I also ran into a registry error, this fixed it.

public void updateRegistryForOracleNLS()
{
    RegistryKey oracle = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\ORACLE");
    oracle.SetValue("NLS_LANG", "AMERICAN_AMERICA.WE8MSWIN1252");
}

For the Oracle nls_lang list, see this site: https://docs.oracle.com/html/B13804_02/gblsupp.htm

After that, everything worked smooth.

I hope it helps.

PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client

@mohammed, this is usually attributed to the authentication plugin that your mysql database is using.

By default and for some reason, mysql 8 default plugin is auth_socket. Applications will most times expect to log in to your database using a password.

If you have not yet already changed your mysql default authentication plugin, you can do so by:
1. Log in as root to mysql
2. Run this sql command:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password
BY 'password';  

Replace 'password' with your root password. In case your application does not log in to your database with the root user, replace the 'root' user in the above command with the user that your application uses.

Digital ocean expounds some more on this here Installing Mysql

How to perform OR condition in django queryset?

Because QuerySets implement the Python __or__ operator (|), or union, it just works. As you'd expect, the | binary operator returns a QuerySet so order_by(), .distinct(), and other queryset filters can be tacked on to the end.

combined_queryset = User.objects.filter(income__gte=5000) | User.objects.filter(income__isnull=True)
ordered_queryset = combined_queryset.order_by('-income')

Update 2019-06-20: This is now fully documented in the Django 2.1 QuerySet API reference. More historic discussion can be found in DjangoProject ticket #21333.

How to make an embedded video not autoplay

fenomas's answer was really good...it got me off of looking into the HTML code. I know that jb was looking for something that works in Captivate, but the question is broad enough to include people working out of Flash (I'm using CS5), so I thought I'd throw in the specific answer to my situation here.

If you're using the stock Adobe FLVPlayback component in Flash (you probably are if you used File > Import > Import Video...), there's an option in the Properties panel, under Component Parameters. Look for 'autoPlay' and uncheck it. That'll stop autoplay when the page loads!

JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?

If you have Underscore.js installed, you could:

$(window).resize(_.debounce(function(){
    alert("Resized");
},500));

Does VBA have Dictionary Structure?

VBA does not have an internal implementation of a dictionary, but from VBA you can still use the dictionary object from MS Scripting Runtime Library.

Dim d
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "aaa"
d.Add "b", "bbb"
d.Add "c", "ccc"

If d.Exists("c") Then
    MsgBox d("c")
End If

java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0)

This is an issue with the jdbc Driver version. I had this issue when I was using mysql-connector-java-commercial-5.0.3-bin.jar but when I changed to a later driver version mysql-connector-java-5.1.22.jar, the issue was fixed.

how to File.listFiles in alphabetical order?

In Java 8:

Arrays.sort(files, (a, b) -> a.getName().compareTo(b.getName()));

Reverse order:

Arrays.sort(files, (a, b) -> -a.getName().compareTo(b.getName()));

How to upload & Save Files with Desired name

use this for target path for uploading

<?php
$file_name = $_FILES["csvFile"]["name"];
$target_path = $dir = plugin_dir_path( __FILE__ )."\\upload\\". $file_name;
echo $target_path;
move_uploaded_file($_FILES["csvFile"]["tmp_name"],$target_path. $file_name);
?>

PHP simple foreach loop with HTML

This will work although when embedding PHP in HTML it is better practice to use the following form:

<table>
    <?php foreach($array as $key=>$value): ?>
    <tr>
        <td><?= $key; ?></td>
    </tr>
    <?php endforeach; ?>
</table>

You can find the doc for the alternative syntax on PHP.net

How to find a parent with a known class in jQuery?

Use .parentsUntil()

$(".d").parentsUntil(".a");

How to for each the hashmap?

I know I'm a bit late for that one, but I'll share what I did too, in case it helps someone else :

HashMap<String, HashMap> selects = new HashMap<String, HashMap>();

for(Map.Entry<String, HashMap> entry : selects.entrySet()) {
    String key = entry.getKey();
    HashMap value = entry.getValue();

    // do what you have to do here
    // In your case, another loop.
}

HTML table needs spacing between columns, not rows

This can be achieved by putting padding between the columns using CSS. You can either add padding to the left of all columns except the first, or add padding to the right of all columns except the last. You should avoid adding padding to the right of the last column or to the left of the first as this will insert redundant white space. You should also avoid being too prescriptive with classes to specify which columns should have the additional padding as this will make maintenance harder if you later add a new column.

The 'lobotomised owl selector' allows you to select all siblings, regardless of if they are a th, td or something else.

_x000D_
_x000D_
tr > * + * {
  padding-left: 4em;
}
_x000D_
<table>
  <thead>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
      <th>Column 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Data 1</td>
      <td>Data 2</td>
      <td>Data 3</td>
    </tr>
  </tbody>
</table>
_x000D_
_x000D_
_x000D_

How to get file creation & modification date/times in Python?

>>> import os
>>> os.stat('feedparser.py').st_mtime
1136961142.0
>>> os.stat('feedparser.py').st_ctime
1222664012.233
>>> 

What is IPV6 for localhost and 0.0.0.0?

As we all know that IPv4 address for localhost is 127.0.0.1 (loopback address).

Actually, any IPv4 address in 127.0.0.0/8 is a loopback address.

In IPv6, the direct analog of the loopback range is ::1/128. So ::1 (long form 0:0:0:0:0:0:0:1) is the one and only IPv6 loopback address.


While the hostname localhost will normally resolve to 127.0.0.1 or ::1, I have seen cases where someone has bound it to an IP address that is not a loopback address. This is a bit crazy ... but sometimes people do it.

I say "this is crazy" because you are liable to break applications assumptions by doing this; e.g. an application may attempt to do a reverse lookup on the loopback IP and not get the expected result. In the worst case, an application may end up sending sensitive traffic over an insecure network by accident ... though you probably need to make other mistakes as well to "achieve" that.


Blocking 0.0.0.0 makes no sense. In IPv4 it is never routed. The equivalent in IPv6 is the :: address (long form 0:0:0:0:0:0:0:0) ... which is also never routed.

The 0.0.0.0 and :: addresses are reserved to mean "any address". So, for example a program that is providing a web service may bind to 0.0.0.0 port 80 to accept HTTP connections via any of the host's IPv4 addresses. These addresses are not valid as a source or destination address for an IP packet.


Finally, some comments were asking about ::/128 versus ::/0 versus ::.

What is this difference?

Strictly speaking, the first two are CIDR notation not IPv6 addresses. They are actually specifying a range of IP addresses. A CIDR consists of a IP address and an additional number that specifies the number of bits in a netmask. The two together specify a range of addresses; i.e. the set of addresses formed by ignoring the bits masked out of the given address.

So:

  • :: means just the IPv6 address 0:0:0:0:0:0:0:0
  • ::/128 means 0:0:0:0:0:0:0:0 with a netmask consisting of 128 bits. This gives a network range with exactly one address in it.
  • ::/0 means 0:0:0:0:0:0:0:0 with a netmask consisting of 0 bits. This gives a network range with 2128 addresses in it.; i.e. it is the entire IPv6 address space!

For more information, read the Wikipedia pages on IPv4 & IPv6 addresses, and CIDR notation:

Change GridView row color based on condition

\\loop throgh all rows of the grid view  

if (GridView1.Rows[i - 1].Cells[4].Text.ToString() == "value1")
{
   GridView1.Rows[i - 1].ForeColor = Color.Black;
}
else if (GridView1.Rows[i - 1].Cells[4].Text.ToString() == "value2")
{
   GridView1.Rows[i - 1].ForeColor = Color.Blue;
}
else if (GridView1.Rows[i - 1].Cells[4].Text.ToString() == "value3")
{
   GridView1.Rows[i - 1].ForeColor = Color.Red;
}
else if (GridView1.Rows[i - 1].Cells[4].Text.ToString() == "value4")
{
   GridView1.Rows[i - 1].ForeColor = Color.Green;
}

How do negative margins in CSS work and why is (margin-top:-5 != margin-bottom:5)?

Just to phrase things differently from the great answers above, as that has helped me get an intuitive understanding of negative margins:

A negative margin on an element allows it to eat up the space of its parent container.

Adding a (positive) margin on the bottom doesn't allow the element to do that - it only pushes back whatever element is below.

WCF Service Returning "Method Not Allowed"

Only methods with WebGet can be accessed from browser IE ; you can access other http verbs by just typing address

You can either try Restful service startup kit of codeples or use fiddler to test your other http verbs

How can I set a dynamic model name in AngularJS?

You can use something like this scopeValue[field], but if your field is in another object you will need another solution.

To solve all kind of situations, you can use this directive:

this.app.directive('dynamicModel', ['$compile', '$parse', function ($compile, $parse) {
    return {
        restrict: 'A',
        terminal: true,
        priority: 100000,
        link: function (scope, elem) {
            var name = $parse(elem.attr('dynamic-model'))(scope);
            elem.removeAttr('dynamic-model');
            elem.attr('ng-model', name);
            $compile(elem)(scope);
        }
    };
}]);

Html example:

<input dynamic-model="'scopeValue.' + field" type="text">

Postgresql : syntax error at or near "-"

I have reproduced the issue in my system,

postgres=# alter user my-sys with password 'pass11';
ERROR:  syntax error at or near "-"
LINE 1: alter user my-sys with password 'pass11';
                       ^

Here is the issue,

psql is asking for input and you have given again the alter query see postgres-#That's why it's giving error at alter

postgres-# alter user "my-sys" with password 'pass11';
ERROR:  syntax error at or near "alter"
LINE 2: alter user "my-sys" with password 'pass11';
        ^

Solution is as simple as the error,

postgres=# alter user "my-sys" with password 'pass11';
ALTER ROLE

round a single column in pandas

Use the pandas.DataFrame.round() method like this:

df = df.round({'value1': 0})

Any columns not included will be left as is.

How to normalize a histogram in MATLAB?

hist can not only plot an histogram but also return you the count of elements in each bin, so you can get that count, normalize it by dividing each bin by the total and plotting the result using bar. Example:

Y = rand(10,1);
C = hist(Y);
C = C ./ sum(C);
bar(C)

or if you want a one-liner:

bar(hist(Y) ./ sum(hist(Y)))

Documentation:

Edit: This solution answers the question How to have the sum of all bins equal to 1. This approximation is valid only if your bin size is small relative to the variance of your data. The sum used here correspond to a simple quadrature formula, more complex ones can be used like trapz as proposed by R. M.

Making heatmap from pandas DataFrame

If you don't need a plot per say, and you're simply interested in adding color to represent the values in a table format, you can use the style.background_gradient() method of the pandas data frame. This method colorizes the HTML table that is displayed when viewing pandas data frames in e.g. the JupyterLab Notebook and the result is similar to using "conditional formatting" in spreadsheet software:

import numpy as np 
import pandas as pd


index= ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
cols = ['A', 'B', 'C', 'D']
df = pd.DataFrame(abs(np.random.randn(5, 4)), index=index, columns=cols)
df.style.background_gradient(cmap='Blues')

enter image description here

For detailed usage, please see the more elaborate answer I provided on the same topic previously and the styling section of the pandas documentation.

How to use OKHTTP to make a post request?

   protected Void doInBackground(String... movieIds) {
                for (; count <= 1; count++) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                Resources res = getResources();
                String web_link = res.getString(R.string.website);

                OkHttpClient client = new OkHttpClient();

                RequestBody formBody = new FormBody.Builder()
                        .add("name", name)
                        .add("bsname", bsname)
                        .add("email", email)
                        .add("phone", phone)
                        .add("whatsapp", wapp)
                        .add("location", location)
                        .add("country", country)
                        .add("state", state)
                        .add("city", city)
                        .add("zip", zip)
                        .add("fb", fb)
                        .add("tw", tw)
                        .add("in", in)
                        .add("age", age)
                        .add("gender", gender)
                        .add("image", encodeimg)
                        .add("uid", user_id)
                        .build();
                Request request = new Request.Builder()
                        .url(web_link+"edit_profile.php")
                        .post(formBody)
                        .build();

                try {
                    Response response = client.newCall(request).execute();

                    JSONArray array = new JSONArray(response.body().string());
                    JSONObject object = array.getJSONObject(0);

                    hashMap.put("msg",object.getString("msgtype"));
                    hashMap.put("msg",object.getString("msg"));
                    // Do something with the response.
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }



                return null;
            }

How to convert (transliterate) a string from utf8 to ASCII (single byte) in c#?

For anyone who likes Extension methods, this one does the trick for us.

using System.Text;

namespace System
{
    public static class StringExtension
    {
        private static readonly ASCIIEncoding asciiEncoding = new ASCIIEncoding();

        public static string ToAscii(this string dirty)
        {
            byte[] bytes = asciiEncoding.GetBytes(dirty);
            string clean = asciiEncoding.GetString(bytes);
            return clean;
        }
    }
}

(System namespace so it's available pretty much automatically for all of our strings.)

Get current date, given a timezone in PHP?

<?php
date_default_timezone_set('GMT-5');//Set New York timezone
$today = date("F j, Y")
?>

How to "fadeOut" & "remove" a div in jQuery?

If you're using it in several different places, you should turn it into a plugin.

jQuery.fn.fadeOutAndRemove = function(speed){
    $(this).fadeOut(speed,function(){
        $(this).remove();
    })
}

And then:

// Somewhere in the program code.
$('div').fadeOutAndRemove('fast');

From ND to 1D arrays

For list of array with different size use following:

import numpy as np

# ND array list with different size
a = [[1],[2,3,4,5],[6,7,8]]

# stack them
b = np.hstack(a)

print(b)

Output:

[1 2 3 4 5 6 7 8]

How to handle-escape both single and double quotes in an SQL-Update statement

In C# and VB the SqlCommand object implements the Parameter.AddWithValue method which handles this situation

Font size relative to the user's screen resolution?

I've created a variant of https://stackoverflow.com/a/17845473/189411

where you can set min and max text size in relation of min and max size of box that you want "check" size. In addition you can check size of dom element different than box where you want apply text size.

You resize text between 19px and 25px on #size-2 element, based on 500px and 960px width of #size-2 element

resizeTextInRange(500,960,19,25,'#size-2');

You resize text between 13px and 20px on #size-1 element, based on 500px and 960px width of body element

resizeTextInRange(500,960,13,20,'#size-1','body');

complete code are there https://github.com/kiuz/sandbox-html-js-css/tree/gh-pages/text-resize-in-range-of-text-and-screen/src

function inRange (x,min,max) {
    return Math.min(Math.max(x, min), max);
}

function resizeTextInRange(minW,maxW,textMinS,textMaxS, elementApply, elementCheck=0) {

    if(elementCheck==0){elementCheck=elementApply;}

    var ww = $(elementCheck).width();
    var difW = maxW-minW;
    var difT = textMaxS- textMinS;
    var rapW = (ww-minW);
    var out=(difT/100)*(rapW/(difW/100))+textMinS;
    var normalizedOut = inRange(out, textMinS, textMaxS);
    $(elementApply).css('font-size',normalizedOut+'px');

    console.log(normalizedOut);

}

$(function () {
    resizeTextInRange(500,960,19,25,'#size-2');
    resizeTextInRange(500,960,13,20,'#size-1','body');
    $(window).resize(function () {
        resizeTextInRange(500,960,19,25,'#size-2');
        resizeTextInRange(500,960,13,20,'#size-1','body');
    });
});

How to temporarily disable a click handler in jQuery?

Try utilizing .one()

_x000D_
_x000D_
var button = $("#button"),_x000D_
  result = $("#result"),_x000D_
  buttonHandler = function buttonHandler(e) {_x000D_
    result.html("processing...");_x000D_
    $(this).fadeOut(1000, function() {_x000D_
      // do stuff_x000D_
      setTimeout(function() {_x000D_
        // reset `click` event at `button`_x000D_
        button.fadeIn({_x000D_
          duration: 500,_x000D_
          start: function() {_x000D_
            result.html("done at " + $.now());_x000D_
          }_x000D_
        }).one("click", buttonHandler);_x000D_
_x000D_
      }, 5000)_x000D_
    })_x000D_
  };_x000D_
_x000D_
button.one("click", buttonHandler);
_x000D_
#button {_x000D_
  width: 50px;_x000D_
  height: 50px;_x000D_
  background: olive;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">_x000D_
</script>_x000D_
<div id="result"></div>_x000D_
<div id="button">click</div>
_x000D_
_x000D_
_x000D_

CSS Disabled scrolling

overflow-x: hidden;
would hide any thing on the x-axis that goes outside of the element, so there would be no need for the horizontal scrollbar and it get removed.

overflow-y: hidden;
would hide any thing on the y-axis that goes outside of the element, so there would be no need for the vertical scrollbar and it get removed.

overflow: hidden;
would remove both scrollbars

PHP Get Highest Value from Array

Try it.

$data = array("a"=>1,"b"=>2,"c"=>4,"d"=>5); $maxKey = current(array_keys($data, max($data))); var_dump($maxKey);

mingw-w64 threads: posix vs win32

Parts of the GCC runtime (the exception handling, in particular) are dependent on the threading model being used. So, if you're using the version of the runtime that was built with POSIX threads, but decide to create threads in your own code with the Win32 APIs, you're likely to have problems at some point.

Even if you're using the Win32 threading version of the runtime you probably shouldn't be calling the Win32 APIs directly. Quoting from the MinGW FAQ:

As MinGW uses the standard Microsoft C runtime library which comes with Windows, you should be careful and use the correct function to generate a new thread. In particular, the CreateThread function will not setup the stack correctly for the C runtime library. You should use _beginthreadex instead, which is (almost) completely compatible with CreateThread.

Sublime 3 - Set Key map for function Goto Definition

I'm using Sublime portable version (for Windows) and this (placing the mousemap in SublimeText\Packages\User folder) did not work for me.

I had to place the mousemap file in SublimeText\Data\Packages\User folder to get it to work where SublimeText is the installation directory for my portable version. Data\Packages\User is where I found the keymap file as well.

How do I Sort a Multidimensional Array in PHP

Introducing: a very generalized solution for PHP 5.3+

I 'd like to add my own solution here, since it offers features that other answers do not.

Specifically, advantages of this solution include:

  1. It's reusable: you specify the sort column as a variable instead of hardcoding it.
  2. It's flexible: you can specify multiple sort columns (as many as you want) -- additional columns are used as tiebreakers between items that initially compare equal.
  3. It's reversible: you can specify that the sort should be reversed -- individually for each column.
  4. It's extensible: if the data set contains columns that cannot be compared in a "dumb" manner (e.g. date strings) you can also specify how to convert these items to a value that can be directly compared (e.g. a DateTime instance).
  5. It's associative if you want: this code takes care of sorting items, but you select the actual sort function (usort or uasort).
  6. Finally, it does not use array_multisort: while array_multisort is convenient, it depends on creating a projection of all your input data before sorting. This consumes time and memory and may be simply prohibitive if your data set is large.

The code

function make_comparer() {
    // Normalize criteria up front so that the comparer finds everything tidy
    $criteria = func_get_args();
    foreach ($criteria as $index => $criterion) {
        $criteria[$index] = is_array($criterion)
            ? array_pad($criterion, 3, null)
            : array($criterion, SORT_ASC, null);
    }

    return function($first, $second) use (&$criteria) {
        foreach ($criteria as $criterion) {
            // How will we compare this round?
            list($column, $sortOrder, $projection) = $criterion;
            $sortOrder = $sortOrder === SORT_DESC ? -1 : 1;

            // If a projection was defined project the values now
            if ($projection) {
                $lhs = call_user_func($projection, $first[$column]);
                $rhs = call_user_func($projection, $second[$column]);
            }
            else {
                $lhs = $first[$column];
                $rhs = $second[$column];
            }

            // Do the actual comparison; do not return if equal
            if ($lhs < $rhs) {
                return -1 * $sortOrder;
            }
            else if ($lhs > $rhs) {
                return 1 * $sortOrder;
            }
        }

        return 0; // tiebreakers exhausted, so $first == $second
    };
}

How to use

Throughout this section I will provide links that sort this sample data set:

$data = array(
    array('zz', 'name' => 'Jack', 'number' => 22, 'birthday' => '12/03/1980'),
    array('xx', 'name' => 'Adam', 'number' => 16, 'birthday' => '01/12/1979'),
    array('aa', 'name' => 'Paul', 'number' => 16, 'birthday' => '03/11/1987'),
    array('cc', 'name' => 'Helen', 'number' => 44, 'birthday' => '24/06/1967'),
);

The basics

The function make_comparer accepts a variable number of arguments that define the desired sort and returns a function that you are supposed to use as the argument to usort or uasort.

The simplest use case is to pass in the key that you 'd like to use to compare data items. For example, to sort $data by the name item you would do

usort($data, make_comparer('name'));

See it in action.

The key can also be a number if the items are numerically indexed arrays. For the example in the question, this would be

usort($data, make_comparer(0)); // 0 = first numerically indexed column

See it in action.

Multiple sort columns

You can specify multiple sort columns by passing additional parameters to make_comparer. For example, to sort by "number" and then by the zero-indexed column:

usort($data, make_comparer('number', 0));

See it in action.

Advanced features

More advanced features are available if you specify a sort column as an array instead of a simple string. This array should be numerically indexed, and must contain these items:

0 => the column name to sort on (mandatory)
1 => either SORT_ASC or SORT_DESC (optional)
2 => a projection function (optional)

Let's see how we can use these features.

Reverse sort

To sort by name descending:

usort($data, make_comparer(['name', SORT_DESC]));

See it in action.

To sort by number descending and then by name descending:

usort($data, make_comparer(['number', SORT_DESC], ['name', SORT_DESC]));

See it in action.

Custom projections

In some scenarios you may need to sort by a column whose values do not lend well to sorting. The "birthday" column in the sample data set fits this description: it does not make sense to compare birthdays as strings (because e.g. "01/01/1980" comes before "10/10/1970"). In this case we want to specify how to project the actual data to a form that can be compared directly with the desired semantics.

Projections can be specified as any type of callable: as strings, arrays, or anonymous functions. A projection is assumed to accept one argument and return its projected form.

It should be noted that while projections are similar to the custom comparison functions used with usort and family, they are simpler (you only need to convert one value to another) and take advantage of all the functionality already baked into make_comparer.

Let's sort the example data set without a projection and see what happens:

usort($data, make_comparer('birthday'));

See it in action.

That was not the desired outcome. But we can use date_create as a projection:

usort($data, make_comparer(['birthday', SORT_ASC, 'date_create']));

See it in action.

This is the correct order that we wanted.

There are many more things that projections can achieve. For example, a quick way to get a case-insensitive sort is to use strtolower as a projection.

That said, I should also mention that it's better to not use projections if your data set is large: in that case it would be much faster to project all your data manually up front and then sort without using a projection, although doing so will trade increased memory usage for faster sort speed.

Finally, here is an example that uses all the features: it first sorts by number descending, then by birthday ascending:

usort($data, make_comparer(
    ['number', SORT_DESC],
    ['birthday', SORT_ASC, 'date_create']
));

See it in action.

C free(): invalid pointer

You can't call free on the pointers returned from strsep. Those are not individually allocated strings, but just pointers into the string s that you've already allocated. When you're done with s altogether, you should free it, but you do not have to do that with the return values of strsep.

How to code a modulo (%) operator in C/C++/Obj-C that handles negative numbers

Here is a C function that handles positive OR negative integer OR fractional values for BOTH OPERANDS

#include <math.h>
float mod(float a, float N) {return a - N*floor(a/N);} //return in range [0, N)

This is surely the most elegant solution from a mathematical standpoint. However, I'm not sure if it is robust in handling integers. Sometimes floating point errors creep in when converting int -> fp -> int.

I am using this code for non-int s, and a separate function for int.

NOTE: need to trap N = 0!

Tester code:

#include <math.h>
#include <stdio.h>

float mod(float a, float N)
{
    float ret = a - N * floor (a / N);

    printf("%f.1 mod %f.1 = %f.1 \n", a, N, ret);

    return ret;
}

int main (char* argc, char** argv)
{
    printf ("fmodf(-10.2, 2.0) = %f.1  == FAIL! \n\n", fmodf(-10.2, 2.0));

    float x;
    x = mod(10.2f, 2.0f);
    x = mod(10.2f, -2.0f);
    x = mod(-10.2f, 2.0f);
    x = mod(-10.2f, -2.0f);

    return 0;
}

(Note: You can compile and run it straight out of CodePad: http://codepad.org/UOgEqAMA)

Output:

fmodf(-10.2, 2.0) = -0.20 == FAIL!

10.2 mod 2.0 = 0.2
10.2 mod -2.0 = -1.8
-10.2 mod 2.0 = 1.8
-10.2 mod -2.0 = -0.2

Excel: Searching for multiple terms in a cell

Another way

=IF(SUMPRODUCT(--(NOT(ISERR(SEARCH({"Gingrich","Obama","Romney"},C1)))))>0,"1","")

Also, if you keep a list of values in, say A1 to A3, then you can use

=IF(SUMPRODUCT(--(NOT(ISERR(SEARCH($A$1:$A$3,C1)))))>0,"1","")

The wildcards are not necessary at all in the Search() function, since Search() returns the position of the found string.

displayname attribute vs display attribute

I think the current answers are neglecting to highlight the actual important and significant differences and what that means for the intended usage. While they might both work in certain situations because the implementer built in support for both, they have different usage scenarios. Both can annotate properties and methods but here are some important differences:

DisplayAttribute

  • defined in the System.ComponentModel.DataAnnotations namespace in the System.ComponentModel.DataAnnotations.dll assembly
  • can be used on parameters and fields
  • lets you set additional properties like Description or ShortName
  • can be localized with resources

DisplayNameAttribute

  • DisplayName is in the System.ComponentModel namespace in System.dll
  • can be used on classes and events
  • cannot be localized with resources

The assembly and namespace speaks to the intended usage and localization support is the big kicker. DisplayNameAttribute has been around since .NET 2 and seems to have been intended more for naming of developer components and properties in the legacy property grid, not so much for things visible to end users that may need localization and such.

DisplayAttribute was introduced later in .NET 4 and seems to be designed specifically for labeling members of data classes that will be end-user visible, so it is more suitable for DTOs, entities, and other things of that sort. I find it rather unfortunate that they limited it so it can't be used on classes though.

EDIT: Looks like latest .NET Core source allows DisplayAttribute to be used on classes now as well.

How to remove a newline from a string in Bash

If you are using bash with the extglob option enabled, you can remove just the trailing whitespace via:

shopt -s extglob
COMMAND=$'\nRE BOOT\r   \n'
echo "|${COMMAND%%*([$'\t\r\n '])}|"

This outputs:

|
RE BOOT|

Or replace %% with ## to replace just the leading whitespace.

How to check for an empty struct?

As an alternative to the other answers, it's possible to do this with a syntax similar to the way you originally intended if you do it via a case statement rather than an if:

session := Session{}
switch {
case Session{} == session:
    fmt.Println("zero")
default:
    fmt.Println("not zero")
}

playground example

How to set height property for SPAN

Another option of course is to use Javascript (Jquery here):

$('.box1,.box2').each(function(){
    $(this).height($(this).parent().height());
})

Switch focus between editor and integrated terminal in Visual Studio Code

A little late to the game but I configured mine as the following in the keybindings.json:

{
    "key": "ctrl+`",
    "command": "workbench.action.terminal.focus",
    "when": "editorTextFocus"
},
{
    "key": "ctrl+`",
    "command": "workbench.action.focusActiveEditorGroup",
    "when": "terminalFocus"
},
{
    "key": "alt+`",
    "command": "workbench.action.terminal.toggleTerminal"
}

I wanted separate keys for opening/closing terminal and switching focus back and forth between the windows.

Detect if an element is visible with jQuery

You're looking for:

.is(':visible')

Although you should probably change your selector to use jQuery considering you're using it in other places anyway:

if($('#testElement').is(':visible')) {
    // Code
}

It is important to note that if any one of a target element's parent elements are hidden, then .is(':visible') on the child will return false (which makes sense).

jQuery 3

:visible has had a reputation for being quite a slow selector as it has to traverse up the DOM tree inspecting a bunch of elements. There's good news for jQuery 3, however, as this post explains (Ctrl + F for :visible):

Thanks to some detective work by Paul Irish at Google, we identified some cases where we could skip a bunch of extra work when custom selectors like :visible are used many times in the same document. That particular case is up to 17 times faster now!

Keep in mind that even with this improvement, selectors like :visible and :hidden can be expensive because they depend on the browser to determine whether elements are actually displaying on the page. That may require, in the worst case, a complete recalculation of CSS styles and page layout! While we don’t discourage their use in most cases, we recommend testing your pages to determine if these selectors are causing performance issues.


Expanding even further to your specific use case, there is a built in jQuery function called $.fadeToggle():

function toggleTestElement() {
    $('#testElement').fadeToggle('fast');
}

Getting values from query string in an url using AngularJS $location

Angular does not support this kind of query string.

The query part of the URL is supposed to be a &-separated sequence of key-value pairs, thus perfectly interpretable as an object.

There is no API at all to manage query strings that do not represent sets of key-value pairs.

Bash script error [: !=: unary operator expected

Or for what seems like rampant overkill, but is actually simplistic ... Pretty much covers all of your cases, and no empty string or unary concerns.

In the case the first arg is '-v', then do your conditional ps -ef, else in all other cases throw the usage.

#!/bin/sh
case $1 in
  '-v') if [ "$1" = -v ]; then
         echo "`ps -ef | grep -v '\['`"
        else
         echo "`ps -ef | grep '\[' | grep root`"
        fi;;
     *) echo "usage: $0 [-v]"
        exit 1;; #It is good practice to throw a code, hence allowing $? check
esac

If one cares not where the '-v' arg is, then simply drop the case inside a loop. The would allow walking all the args and finding '-v' anywhere (provided it exists). This means command line argument order is not important. Be forewarned, as presented, the variable arg_match is set, thus it is merely a flag. It allows for multiple occurrences of the '-v' arg. One could ignore all other occurrences of '-v' easy enough.

#!/bin/sh

usage ()
 {
  echo "usage: $0 [-v]"
  exit 1
 }

unset arg_match

for arg in $*
 do
  case $arg in
    '-v') if [ "$arg" = -v ]; then
           echo "`ps -ef | grep -v '\['`"
          else
           echo "`ps -ef | grep '\[' | grep root`"
          fi
          arg_match=1;; # this is set, but could increment.
       *) ;;
  esac
done

if [ ! $arg_match ]
 then
  usage
fi

But, allow multiple occurrences of an argument is convenient to use in situations such as:

$ adduser -u:sam -s -f -u:bob -trace -verbose

We care not about the order of the arguments, and even allow multiple -u arguments. Yes, it is a simple matter to also allow:

$ adduser -u sam -s -f -u bob -trace -verbose

Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION]

For all the python3 and pip3 users out there:

curl https://bootstrap.pypa.io/get-pip.py | sudo python3

and then assume you want to install pandas

pip3 install pandas --user

What does principal end of an association means in 1:1 relationship in Entity framework

This is with reference to @Ladislav Mrnka's answer on using fluent api for configuring one-to-one relationship.

Had a situation where having FK of dependent must be it's PK was not feasible.

E.g., Foo already has one-to-many relationship with Bar.

public class Foo {
   public Guid FooId;
   public virtual ICollection<> Bars; 
}
public class Bar {
   //PK
   public Guid BarId;
   //FK to Foo
   public Guid FooId;
   public virtual Foo Foo;
}

Now, we had to add another one-to-one relationship between Foo and Bar.

public class Foo {
   public Guid FooId;
   public Guid PrimaryBarId;// needs to be removed(from entity),as we specify it in fluent api
   public virtual Bar PrimaryBar;
   public virtual ICollection<> Bars;
}
public class Bar {
   public Guid BarId;
   public Guid FooId;
   public virtual Foo PrimaryBarOfFoo;
   public virtual Foo Foo;
}

Here is how to specify one-to-one relationship using fluent api:

modelBuilder.Entity<Bar>()
            .HasOptional(p => p.PrimaryBarOfFoo)
            .WithOptionalPrincipal(o => o.PrimaryBar)
            .Map(x => x.MapKey("PrimaryBarId"));

Note that while adding PrimaryBarId needs to be removed, as we specifying it through fluent api.

Also note that method name [WithOptionalPrincipal()][1] is kind of ironic. In this case, Principal is Bar. WithOptionalDependent() description on msdn makes it more clear.

How to add url parameter to the current url?

In case you want to add the URL parameter in JavaScript, see this answer. As suggested there, you can use the URLSeachParams API in modern browsers as follows:

<script>
function addUrlParameter(name, value) {
  var searchParams = new URLSearchParams(window.location.search)
  searchParams.set(name, value)
  window.location.search = searchParams.toString()
}
</script>

<body>
...
  <a onclick="addUrlParameter('like', 'like')">Like this page</a>
...
</body>

Unable to make the session state request to the session state server

I've had the same issue when some ASP.NET installation was corrupted. In that case they suggest running aspnet_regiis -i -enable

How to use youtube-dl from a python program?

I would like this

from subprocess import call

command = "youtube-dl https://www.youtube.com/watch?v=NG3WygJmiVs -c"
call(command.split(), shell=False)

Read a text file line by line in Qt

Since Qt 5.5 you can use QTextStream::readLineInto. It behaves similar to std::getline and is maybe faster as QTextStream::readLine, because it reuses the string:

QIODevice* device;
QTextStream in(&device);

QString line;
while (in.readLineInto(&line)) {
  // ...
}

What is the difference between a JavaBean and a POJO?

According to Martin Fowler a POJO is an object which encapsulates Business Logic while a Bean (except for the definition already stated in other answers) is little more than a container for holding data and the operations available on the object merely set and get data.

The term was coined while Rebecca Parsons, Josh MacKenzie and I were preparing for a talk at a conference in September 2000. In the talk we were pointing out the many benefits of encoding business logic into regular java objects rather than using Entity Beans. We wondered why people were so against using regular objects in their systems and concluded that it was because simple objects lacked a fancy name. So we gave them one, and it's caught on very nicely.

http://www.martinfowler.com/bliki/POJO.html

Adding line break in C# Code behind page

If I am understanding this correctly, you should be able to break the string into substrings to accomplish this.

i.e.:

string s = "this is a really long string" +
"and this is the rest of it";

ios simulator: how to close an app

Double click on the home button and then click and hold the icon like a normal phone and then click close I believe.

CSS '>' selector; what is it?

> selects immediate children

For example, if you have nested divs like such:

<div class='outer'>
    <div class="middle">
        <div class="inner">...</div>
    </div>
    <div class="middle">
        <div class="inner">...</div>
    </div>
</div>

and you declare a css rule in your stylesheet like such:

.outer > div {
    ...
}

your rules will apply only to those divs that have a class of "middle" since those divs are direct descendants (immediate children) of elements with class "outer" (unless, of course, you declare other, more specific rules overriding these rules). See fiddle.

_x000D_
_x000D_
div {_x000D_
  border: 1px solid black;_x000D_
  padding: 10px;_x000D_
}_x000D_
.outer > div {_x000D_
  border: 1px solid orange;_x000D_
}
_x000D_
<div class='outer'>_x000D_
  div.outer - This is the parent._x000D_
  <div class="middle">_x000D_
    div.middle - This is an immediate child of "outer". This will receive the orange border._x000D_
    <div class="inner">div.inner - This is an immediate child of "middle". This will not receive the orange border.</div>_x000D_
  </div>_x000D_
  <div class="middle">_x000D_
    div.middle - This is an immediate child of "outer". This will receive the orange border._x000D_
    <div class="inner">div.inner - This is an immediate child of "middle". This will not receive the orange border.</div>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<p>Without Words</p>_x000D_
_x000D_
<div class='outer'>_x000D_
  <div class="middle">_x000D_
    <div class="inner">...</div>_x000D_
  </div>_x000D_
  <div class="middle">_x000D_
    <div class="inner">...</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Side note

If you, instead, had a space between selectors instead of >, your rules would apply to both of the nested divs. The space is much more commonly used and defines a "descendant selector", which means it looks for any matching element down the tree rather than just immediate children as the > does.

NOTE: The > selector is not supported by IE6. It does work in all other current browsers though, including IE7 and IE8.

If you're looking into less-well-used CSS selectors, you may also want to look at +, ~, and [attr] selectors, all of which can be very useful.

This page has a full list of all available selectors, along with details of their support in various browsers (its mainly IE that has problems), and good examples of their usage.

Converting pfx to pem using openssl

You can use the OpenSSL Command line tool. The following commands should do the trick

openssl pkcs12 -in client_ssl.pfx -out client_ssl.pem -clcerts

openssl pkcs12 -in client_ssl.pfx -out root.pem -cacerts

If you want your file to be password protected etc, then there are additional options.

You can read the entire documentation here.

Posting a File and Associated Data to a RESTful WebService preferably as JSON

You can send the file and data over in one request using the multipart/form-data content type:

In many applications, it is possible for a user to be presented with a form. The user will fill out the form, including information that is typed, generated by user input, or included from files that the user has selected. When the form is filled out, the data from the form is sent from the user to the receiving application.

The definition of MultiPart/Form-Data is derived from one of those applications...

From http://www.faqs.org/rfcs/rfc2388.html:

"multipart/form-data" contains a series of parts. Each part is expected to contain a content-disposition header [RFC 2183] where the disposition type is "form-data", and where the disposition contains an (additional) parameter of "name", where the value of that parameter is the original field name in the form. For example, a part might contain a header:

Content-Disposition: form-data; name="user"

with the value corresponding to the entry of the "user" field.

You can include file information or field information within each section between boundaries. I've successfully implemented a RESTful service that required the user to submit both data and a form, and multipart/form-data worked perfectly. The service was built using Java/Spring, and the client was using C#, so unfortunately I don't have any Grails examples to give you concerning how to set up the service. You don't need to use JSON in this case since each "form-data" section provides you a place to specify the name of the parameter and its value.

The good thing about using multipart/form-data is that you're using HTTP-defined headers, so you're sticking with the REST philosophy of using existing HTTP tools to create your service.

jQuery jump or scroll to certain position, div or target on the page from button onclick

I would style a link to look like a button, because that way there is a no-js fallback.


So this is how you could animate the jump using jquery. No-js fallback is a normal jump without animation.

Original example:

jsfiddle

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $(".jumper").on("click", function( e ) {_x000D_
_x000D_
    e.preventDefault();_x000D_
_x000D_
    $("body, html").animate({ _x000D_
      scrollTop: $( $(this).attr('href') ).offset().top _x000D_
    }, 600);_x000D_
_x000D_
  });_x000D_
});
_x000D_
#long {_x000D_
  height: 500px;_x000D_
  background-color: blue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!-- Links that trigger the jumping -->_x000D_
<a class="jumper" href="#pliip">Pliip</a>_x000D_
<a class="jumper" href="#ploop">Ploop</a>_x000D_
<div id="long">...</div>_x000D_
<!-- Landing elements -->_x000D_
<div id="pliip">pliip</div>_x000D_
<div id="ploop">ploop</div>
_x000D_
_x000D_
_x000D_


New example with actual button styles for the links, just to prove a point.

Everything is essentially the same, except that I changed the class .jumper to .button and I added css styling to make the links look like buttons.

Button styles example

How to reverse an std::string?

Try

string reversed(temp.rbegin(), temp.rend());

EDIT: Elaborating as requested.

string::rbegin() and string::rend(), which stand for "reverse begin" and "reverse end" respectively, return reverse iterators into the string. These are objects supporting the standard iterator interface (operator* to dereference to an element, i.e. a character of the string, and operator++ to advance to the "next" element), such that rbegin() points to the last character of the string, rend() points to the first one, and advancing the iterator moves it to the previous character (this is what makes it a reverse iterator).

Finally, the constructor we are passing these iterators into is a string constructor of the form:

template <typename Iterator>
string(Iterator first, Iterator last);

which accepts a pair of iterators of any type denoting a range of characters, and initializes the string to that range of characters.

Find a private field with Reflection?

One thing that you need to be aware of when reflecting on private members is that if your application is running in medium trust (as, for instance, when you are running on a shared hosting environment), it won't find them -- the BindingFlags.NonPublic option will simply be ignored.

HTML: Select multiple as dropdown

Because you're using multiple. Despite it still technically being a dropdown, it doesn't look or act like a standard dropdown. Rather, it populates a list box and lets them select multiple options.

Size determines how many options appear before they have to click down or up to see the other options.

I have a feeling what you want to achieve is only going to be possible with a JavaScript plugin.

Some examples:

jQuery multiselect drop down menu

http://labs.abeautifulsite.net/archived/jquery-multiSelect/demo/

How to save password when using Subversion from the console

In ~/.subversion/config, you probably have store-passwords = no. Change it to yes (or just comment it out because it defaults to yes), and the next time you give Subversion your password it should save it.

You might want to ensure that the owner and permissions of ~/.subversion/config are correct (no public or group access; 600).

Disable back button in android

if you are using FragmentActivity. then do like this

first call This inside your Fragment.

public void callParentMethod(){
    getActivity().onBackPressed();
}

and then Call onBackPressed method in side your parent FragmentActivity class.

@Override
public void onBackPressed() {
  //super.onBackPressed();
  //create a dialog to ask yes no question whether or not the user wants to exit
  ...
}

Regex match digits, comma and semicolon?

word.matches("^[0-9,;]+$"); you were almost there

How to preview selected image in input type="file" in popup using jQuery?

Demo

HTML:

 <form id="form1" runat="server">
   <input type='file' id="imgInp" />
   <img id="blah" src="#" alt="your image" />
</form>

jQuery

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#blah').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$("#imgInp").change(function(){
    readURL(this);
});

Reference

How to link to apps on the app store

At least iOS 9 and above

  • Open directly in the App Store

An app

itms-apps://itunes.apple.com/app/[appName]/[appID]

List of developer's apps

itms-apps://itunes.apple.com/developer/[developerName]/[developerID]

bower command not found

This turned out to NOT be a bower problem, though it showed up for me with bower.

It seems to be a node-which problem. If a file is in the path, but has the setuid/setgid bit set, which will not find it.

Here is a files with the s bit set: (unix 'which' will find it with no problems).

ls -al /usr/local/bin -rwxrwsr-- 110 root nmt 5535636 Jul 17 2012 git

Here is a node-which attempt:

> which.sync('git')
Error: not found: git

I change the permissions (chomd 755 git). Now node-which can find it.

> which.sync('git')
'/usr/local/bin/git'

Hope this helps.

successful/fail message pop up box after submit?

You are echoing outside the body tag of your HTML. Put your echos there, and you should be fine.

Also, remove the onclick="alert()" from your submit. This is the cause for your first undefined message.

<?php
  $posted = false;
  if( $_POST ) {
    $posted = true;

    // Database stuff here...
    // $result = mysql_query( ... )
    $result = $_POST['name'] == "danny"; // Dummy result
  }
?>

<html>
  <head></head>
  <body>

  <?php
    if( $posted ) {
      if( $result ) 
        echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
      else
        echo "<script type='text/javascript'>alert('failed!')</script>";
    }
  ?>
    <form action="" method="post">
      Name:<input type="text" id="name" name="name"/>
      <input type="submit" value="submit" name="submit"/>
    </form>
  </body>
</html>

Creating email templates with Django

Django Mail Templated is a feature-rich Django application to send emails with Django template system.

Installation:

pip install django-mail-templated

Configuration:

INSTALLED_APPS = (
    ...
    'mail_templated'
)

Template:

{% block subject %}
Hello {{ user.name }}
{% endblock %}

{% block body %}
{{ user.name }}, this is the plain text part.
{% endblock %}

Python:

from mail_templated import send_mail
send_mail('email/hello.tpl', {'user': user}, from_email, [user.email])

More info: https://github.com/artemrizhov/django-mail-templated

I get conflicting provisioning settings error when I try to archive to submit an iOS app

Go to build settings, search for code signing identity, and set Any iOS SDK value for iOS Developer:

enter image description here

Reloading the page gives wrong GET request with AngularJS HTML5 mode

I have resolved the issue by adding below code snippet into node.js file.

app.get("/*", function (request, response) {
    console.log('Unknown API called');
    response.redirect('/#' + request.url);
});

Note : when we refresh the page, it will look for the API instead of Angular page (Because of no # tag in URL.) . Using the above code, I am redirecting to the url with #

Git fatal: protocol 'https' is not supported

Just use double quotes with URL, like: git clone "https://yourRepoUrl"

(It somehow sees that you are using 2 quote marks on start, don't know why).

I was getting the same error => fatal: protocol ''https' is not supported (you can see 2 quote marks on https).

How to search for a string in an arraylist

 List <String> list = new ArrayList();  
           list.add("behold"); 
           list.add("bend"); 
           list.add("bet"); 
           list.add("bear"); 
           list.add("beat"); 
           list.add("become"); 
           list.add("begin");

           List <String> listClone = new ArrayList<String>(); 
           for (String string : list) {
               if(string.matches("(?i)(bea).*")){
                   listClone.add(string);
               }
           }
        System.out.println(listClone);

PHP Configuration: It is not safe to rely on the system's timezone settings

Obviously I'm a little out of season on this question but for the benefit of the next sufferer: I just had this problem and in my case (in contrast to OP who tried the same without success) the fix was to revise php.ini, changing

date.timezone = America/New York

to

date.timezone = America/New_York

That is adding the underscore.

RabbitMQ / AMQP: single queue, multiple consumers for same message?

Fan out was clearly what you wanted. fanout

read rabbitMQ tutorial: https://www.rabbitmq.com/tutorials/tutorial-three-javascript.html

here's my example:

Publisher.js:

amqp.connect('amqp://<user>:<pass>@<host>:<port>', async (error0, connection) => {
    if (error0) {
      throw error0;
    }
    console.log('RabbitMQ connected')
    try {
      // Create exchange for queues
      channel = await connection.createChannel()
      await channel.assertExchange(process.env.EXCHANGE_NAME, 'fanout', { durable: false });
      await channel.publish(process.env.EXCHANGE_NAME, '', Buffer.from('msg'))
    } catch(error) {
      console.error(error)
    }
})

Subscriber.js:

amqp.connect('amqp://<user>:<pass>@<host>:<port>', async (error0, connection) => {
    if (error0) {
      throw error0;
    }
    console.log('RabbitMQ connected')
    try {
      // Create/Bind a consumer queue for an exchange broker
      channel = await connection.createChannel()
      await channel.assertExchange(process.env.EXCHANGE_NAME, 'fanout', { durable: false });
      const queue = await channel.assertQueue('', {exclusive: true})
      channel.bindQueue(queue.queue, process.env.EXCHANGE_NAME, '')

      console.log(" [*] Waiting for messages in %s. To exit press CTRL+C");
      channel.consume('', consumeMessage, {noAck: true});
    } catch(error) {
      console.error(error)
    }
});

here is an example i found in the internet. maybe can also help. https://www.codota.com/code/javascript/functions/amqplib/Channel/assertExchange

Socket accept - "Too many open files"

There are multiple places where Linux can have limits on the number of file descriptors you are allowed to open.

You can check the following:

cat /proc/sys/fs/file-max

That will give you the system wide limits of file descriptors.

On the shell level, this will tell you your personal limit:

ulimit -n

This can be changed in /etc/security/limits.conf - it's the nofile param.

However, if you're closing your sockets correctly, you shouldn't receive this unless you're opening a lot of simulataneous connections. It sounds like something is preventing your sockets from being closed appropriately. I would verify that they are being handled properly.

Set environment variables from file of key/value pairs

Here's my variant:

  with_env() {
    (set -a && . ./.env && "$@")
  }

compared with the previous solutions:

  • it does not leak variables outside scope (values from .env are not exposed to caller)
  • does not clobber set options
  • returns exit code of the executed command
  • uses posix compatible set -a
  • uses . instead of source to avoid bashism
  • command is not invoked if .env loading fails
with_env rails console

npm install doesn't create node_modules directory

If you have a package-lock.json file, you may have to delete that file then run npm i. That worked for me

How to combine two strings together in PHP?

Concatenate them with the . operator:

$result = $data1 . " " . $data2;

Or use string interpolation:

$result = "$data1 $data2";

How to use Python requests to fake a browser visit a.k.a and generate User Agent?

Provide a User-Agent header:

import requests

url = 'http://www.ichangtou.com/#company:data_000008.html'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}

response = requests.get(url, headers=headers)
print(response.content)

FYI, here is a list of User-Agent strings for different browsers:


As a side note, there is a pretty useful third-party package called fake-useragent that provides a nice abstraction layer over user agents:

fake-useragent

Up to date simple useragent faker with real world database

Demo:

>>> from fake_useragent import UserAgent
>>> ua = UserAgent()
>>> ua.chrome
u'Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36'
>>> ua.random
u'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.67 Safari/537.36'

VBScript: Using WScript.Shell to Execute a Command Line Program That Accesses Active Directory

The issue turned out to be certificate-related. The WCF service called by the console app uses an X509 cert for authentication, which is installed on the servers that this script is hosted and run from.

On other servers, where the same services are consumed, the certificates were configured as follows:

winhttpcertcfg.exe -g -c LOCAL_MACHINE\My -s "certificate-name" -a "NETWORK SERVICE"

As they ran within the context of IIS. However, when the script was being run as it would in production, it's under the context of the user themselves. So, the script needed to be modified to the following:

winhttpcertcfg.exe -g -c LOCAL_MACHINE\My -s "certificate-name" -a "USERS"

Once that change was made, all was well. Thanks to everyone who offered assistance.

Parse v. TryParse

TryParse does not return the value, it returns a status code to indicate whether the parse succeeded (and doesn't throw an exception).

Reason for Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

Suppose I have the following table T:

a   b
--------
1   abc
1   def
1   ghi
2   jkl
2   mno
2   pqr

And I do the following query:

SELECT a, b
FROM T
GROUP BY a

The output should have two rows, one row where a=1 and a second row where a=2.

But what should the value of b show on each of these two rows? There are three possibilities in each case, and nothing in the query makes it clear which value to choose for b in each group. It's ambiguous.

This demonstrates the single-value rule, which prohibits the undefined results you get when you run a GROUP BY query, and you include any columns in the select-list that are neither part of the grouping criteria, nor appear in aggregate functions (SUM, MIN, MAX, etc.).

Fixing it might look like this:

SELECT a, MAX(b) AS x
FROM T
GROUP BY a

Now it's clear that you want the following result:

a   x
--------
1   ghi
2   pqr

Installing J2EE into existing eclipse IDE

You could install Web Tool Platform on top of your current installation to help you learn about Java EE. Download the Web Tools Platform by using Eclipse Software Update (Instruction at http://download.eclipse.org/webtools/updates/). It has features to get you going with learning Java EE. You could learn more about Web Tools Platform at http://www.eclipse.org/webtools/

Why does writeObject throw java.io.NotSerializableException and how do I fix it?

java.io.NotSerializableException can occur when you serialize an inner class instance because:

serializing such an inner class instance will result in serialization of its associated outer class instance as well

Serialization of inner classes (i.e., nested classes that are not static member classes), including local and anonymous classes, is strongly discouraged

Ref: The Serializable Interface

Running Git through Cygwin from Windows

I can tell you from personal experience this is a bad idea. Native Windows programs cannot accept Cygwin paths. For example with Cygwin you might run a command

grep -r --color foo /opt

with no issue. With Cygwin / represents the root directory. Native Windows programs have no concept of this, and will likely fail if invoked this way. You should not mix Cygwin and Native Windows programs unless you have no other choice.

Uninstall what Git you have and install the Cygwin git package, save yourself the headache.

jQuery Clone table row

Here you go:

$( table ).delegate( '.tr_clone_add', 'click', function () {
    var thisRow = $( this ).closest( 'tr' )[0];
    $( thisRow ).clone().insertAfter( thisRow ).find( 'input:text' ).val( '' );
});

Live demo: http://jsfiddle.net/RhjxK/4/


Update: The new way of delegating events in jQuery is

$(table).on('click', '.tr_clone_add', function () { … });

Detect click outside element

There are already many answers to this question, and most of them are based on the similar custom directive idea. The problem with this approach is that one have to pass a method function to the directive, and cannot directly write code as in other events.

I created a new package vue-on-clickout that is different. Check it out at:

It allows one to write v-on:clickout just like any other events. For example, you can write

<div v-on:clickout="myField=value" v-on:click="myField=otherValue">...</div>

and it works.

Update

vue-on-clickout now supports Vue 3!

Update 2

vue-on-clickout is now replaced by a new package Clickout-Event which works for any front-end framework (or vanilla)!

Visual Studio 2008 Product Key in Registry?

For 32 bit Windows:


Visual Studio 2003:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\7.0\Registration\PIDKEY

Visual Studio 2005:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\8.0\Registration\PIDKEY

Visual Studio 2008:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\Registration\PIDKEY


For 64 bit Windows:


Visual Studio 2003:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\7.0\Registration\PIDKEY

Visual Studio 2005:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\8.0\Registration\PIDKEY

Visual Studio 2008:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\9.0\Registration\PIDKEY


Notes:

  • Data is a GUID without dashes. Put a dash ( – ) after every 5 characters to convert to product key.
  • If PIDKEY value is empty try to look at the subfolders e.g.

    ...\Registration\1000.0x0000\PIDKEY

    or

    ...\Registration\2000.0x0000\PIDKEY

What is an .axd file?

An AXD file is a file used by ASP.NET applications for handling embedded resource requests. It contains instructions for retrieving embedded resources, such as images, JavaScript (.JS) files, and.CSS files. AXD files are used for injecting resources into the client-side webpage and access them on the server in a standard way.

MVC Calling a view from a different controller

You can move you read.aspx view to Shared folder. It is standard way in such circumstances

Joining Spark dataframes on the key

Let me explain with an example

  1. create emp DataFrame

    import spark.sqlContext.implicits._ val emp = Seq((1,"Smith",-1,"2018","10","M",3000), (2,"Rose",1,"2010","20","M",4000), (3,"Williams",1,"2010","10","M",1000), (4,"Jones",2,"2005","10","F",2000), (5,"Brown",2,"2010","40","",-1), (6,"Brown",2,"2010","50","",-1) ) val empColumns = Seq("emp_id","name","superior_emp_id","year_joined", "emp_dept_id","gender","salary")

    val empDF = emp.toDF(empColumns:_*)

  2. Create dept DataFrame

    val dept = Seq(("Finance",10), ("Marketing",20), ("Sales",30), ("IT",40) )

    val deptColumns = Seq("dept_name","dept_id") val deptDF = dept.toDF(deptColumns:_*)

Now let's join emp.emp_dept_id with dept.dept_id

empDF.join(deptDF,empDF("emp_dept_id") ===  deptDF("dept_id"),"inner")
    .show(false)

This results below

+------+--------+---------------+-----------+-----------+------+------+---------+-------+
|emp_id|name    |superior_emp_id|year_joined|emp_dept_id|gender|salary|dept_name|dept_id|
+------+--------+---------------+-----------+-----------+------+------+---------+-------+
|1     |Smith   |-1             |2018       |10         |M     |3000  |Finance  |10     |
|2     |Rose    |1              |2010       |20         |M     |4000  |Marketing|20     |
|3     |Williams|1              |2010       |10         |M     |1000  |Finance  |10     |
|4     |Jones   |2              |2005       |10         |F     |2000  |Finance  |10     |
|5     |Brown   |2              |2010       |40         |      |-1    |IT       |40     |
+------+--------+---------------+-----------+-----------+------+------+---------+-------+

If you are looking in python PySpark Join with example and also find the complete Scala example at Spark Join

Django request get parameters

You may also use:

request.POST.get('section','') # => [39]
request.POST.get('MAINS','') # => [137] 
request.GET.get('section','') # => [39]
request.GET.get('MAINS','') # => [137]

Using this ensures that you don't get an error. If the POST/GET data with any key is not defined then instead of raising an exception the fallback value (second argument of .get() will be used).

Count the number of occurrences of each letter in string

After Accept Answer

A method that meets these specs: (IMO, the other answers do not meet all)

  1. It is practical/efficient when char has a wide range. Example: CHAR_BIT is 16 or 32, so no use of bool Used[1 << CHAR_BIT];

  2. Works for very long strings (use size_t rather than int).

  3. Does not rely on ASCII. ( Use Upper[] )

  4. Defined behavior when a char < 0. is...() functions are defined for EOF and unsigned char

    static const char Upper[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    static const char Lower[] = "abcdefghijklmnopqrstuvwxyz";
    
    void LetterOccurrences(size_t *Count, const char *s) {
      memset(Count, 0, sizeof *Count * 26);
      while (*s) {
        unsigned char ch = *s;
        if (isalpha(ch)) {
          const char *caseset = Upper;
          char *p = strchr(caseset, ch);
          if (p == NULL) {
            caseset = Lower;
            p = strchr(caseset, ch);
          }
          if (p != NULL) {
            Count[p - caseset]++;
          }
        }
      }
    }
    
    // sample usage
    char *s = foo();
    size_t Count[26];
    LetterOccurrences(Count, s);
    for (int i=0; i<26; i++)
      printf("%c : %zu\n", Upper[i], Count[i]);
    }
    

converting a javascript string to a html object

Had the same issue. I used a dirty trick like so:

var s = '<div id="myDiv"></div>';
var temp = document.createElement('div');
temp.innerHTML = s;
var htmlObject = temp.firstChild;

Now, you can add styles the way you like:

htmlObject.style.marginTop = something;

How to search for a part of a word with ElasticSearch

Nevermind.

I had to look at the Lucene documentation. Seems I can use wildcards! :-)

curl http://localhost:9200/my_idx/my_type/_search?q=*Doe*

does the trick!

How to compile Tensorflow with SSE4.2 and AVX instructions?

Let's start with the explanation of why do you see these warnings in the first place.


Most probably you have not installed TF from source and instead of it used something like pip install tensorflow. That means that you installed pre-built (by someone else) binaries which were not optimized for your architecture. And these warnings tell you exactly this: something is available on your architecture, but it will not be used because the binary was not compiled with it. Here is the part from documentation.

TensorFlow checks on startup whether it has been compiled with the optimizations available on the CPU. If the optimizations are not included, TensorFlow will emit warnings, e.g. AVX, AVX2, and FMA instructions not included.

Good thing is that most probably you just want to learn/experiment with TF so everything will work properly and you should not worry about it


What are SSE4.2 and AVX?

Wikipedia has a good explanation about SSE4.2 and AVX. This knowledge is not required to be good at machine-learning. You may think about them as a set of some additional instructions for a computer to use multiple data points against a single instruction to perform operations which may be naturally parallelized (for example adding two arrays).

Both SSE and AVX are implementation of an abstract idea of SIMD (Single instruction, multiple data), which is

a class of parallel computers in Flynn's taxonomy. It describes computers with multiple processing elements that perform the same operation on multiple data points simultaneously. Thus, such machines exploit data level parallelism, but not concurrency: there are simultaneous (parallel) computations, but only a single process (instruction) at a given moment

This is enough to answer your next question.


How do these SSE4.2 and AVX improve CPU computations for TF tasks

They allow a more efficient computation of various vector (matrix/tensor) operations. You can read more in these slides


How to make Tensorflow compile using the two libraries?

You need to have a binary which was compiled to take advantage of these instructions. The easiest way is to compile it yourself. As Mike and Yaroslav suggested, you can use the following bazel command

bazel build -c opt --copt=-mavx --copt=-mavx2 --copt=-mfma --copt=-mfpmath=both --copt=-msse4.2 --config=cuda -k //tensorflow/tools/pip_package:build_pip_package

How to import a new font into a project - Angular 5

the answer is already exist above, but I would like to add some thing.. you can specify the following in your @font-face

@font-face {
  font-family: 'Name You Font';
  src: url('assets/font/xxyourfontxxx.eot');
  src: local('Cera Pro Medium'), local('CeraPro-Medium'),
  url('assets/font/xxyourfontxxx.eot?#iefix') format('embedded-opentype'),
  url('assets/font/xxyourfontxxx.woff') format('woff'),
  url('assets/font/xxyourfontxxx.ttf') format('truetype');
  font-weight: 500;
  font-style: normal;
}

So you can just indicate your fontfamily name that you already choosed

NOTE: the font-weight and font-style depend on your .woff .ttf ... files

how to align text vertically center in android

The problem is the padding of the font on the textview. Just add to your textview:

android:includeFontPadding="false"

RuntimeWarning: DateTimeField received a naive datetime

make sure settings.py has USE_TZ = True

In your python file:

from django.utils import timezone

timezone.now() # use its value in model field

How do I set specific environment variables when debugging in Visual Studio?

If you can't use bat files to set up your environment, then your only likely option is to set up a system wide environment variable. You can find these by doing

  1. Right click "My Computer"
  2. Select properties
  3. Select the "advanced" tab
  4. Click the "environment variables" button
  5. In the "System variables" section, add the new environment variable that you desire
  6. "Ok" all the way out to accept your changes

I don't know if you'd have to restart visual studio, but seems unlikely. HTH

Is there a command like "watch" or "inotifywait" on the Mac?

watchdog is a cross-platform python API for watching files / directories, and it has builtin "tricks" tool that allows you to trigger actions (including shell commands) when events occur (including new added file, removed file and changed file).

Android: Unable to add window. Permission denied for this window type

The Main Reason for the denying permission is that we don’t have permission for drawing over another apps,We have to provide the permission for the Drawing over other apps that can be done by the following code

Request code for Permission

    public static int ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE = 5469;

add this in your MainActivity


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
            askPermission();
}


private void askPermission() {
        Intent intent= new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:"+getPackageName()));
        startActivityForResult(intent,ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE);
}

Add this also

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE){
            if(!Settings.canDrawOverlays(this)){
                askPermission();
            }
        }
    }