Programs & Examples On #Pygraphviz

PyGraphviz is a Python interface to Graphviz. With PyGraphviz it is possible to create, read, write and draw graphs with Python utilizing the Graphviz `dot`language and its layout algorithms.

Why is pydot unable to find GraphViz's executables in Windows 8?

Some things to know about graphviz:

  1. graphviz is not only a python module, it's also a standalone program. I believe you need both to make graphviz to work.
  2. The standalone graphviz program was originally developed by AT&T, open sourced, then abandoned. The current maintainers of the package forgot to include Windows registry entries so Python can find the program executable.
  3. Line 620 of pydotplus\graphviz.py includes a backup path to look for graphviz if it isn't found in the registry. It uses the old ATT file path. Update the file path to what is on your machine (you will need to have administrator privileges) and graphviz should work with pydotplus.

Example:

# Just in case, try the default... path = r"C:\Program Files (x86)\Graphviz2.38\bin"

Java: parse int value from a char

String element = "el5";
int x = element.charAt(2) - 48;

Subtracting ascii value of '0' = 48 from char

How can I add "href" attribute to a link dynamically using JavaScript?

var a = document.getElementById('yourlinkId'); //or grab it by tagname etc
a.href = "somelink url"

Check if a string contains another string

There is also the InStrRev function which does the same type of thing, but starts searching from the end of the text to the beginning.

Per @rene's answer...

Dim pos As Integer
pos = InStrRev("find the comma, in the string", ",")

...would still return 15 to pos, but if the string has more than one of the search string, like the word "the", then:

Dim pos As Integer
pos = InStrRev("find the comma, in the string", "the")

...would return 20 to pos, instead of 6.

How to check if a variable is not null?

  • code inside your if(myVar) { code } will be NOT executed only when myVar is equal to: false, 0, "", null, undefined, NaN or you never defined variable myVar (then additionally code stop execution and throw exception).
  • code inside your if(myVar !== null) {code} will be NOT executed only when myVar is equal to null or you never defined it (throws exception).

Here you have all (src)

if

enter image description here

== (its negation !=)

enter image description here

=== (its negation !==)

enter image description here

Plotting of 1-dimensional Gaussian distribution function

With the excellent matplotlib and numpy packages

from matplotlib import pyplot as mp
import numpy as np

def gaussian(x, mu, sig):
    return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))

x_values = np.linspace(-3, 3, 120)
for mu, sig in [(-1, 1), (0, 2), (2, 3)]:
    mp.plot(x_values, gaussian(x_values, mu, sig))

mp.show()

will produce something like plot showing one-dimensional gaussians produced by matplotlib

Find TODO tags in Eclipse

  1. Push Ctrl+H
  2. Got to File Search tab
  3. Enter "// TODO Auto-generated method stub" in Containing Text field
  4. Enter "*.java" in Filename patterns field
  5. Select proper scope

How to iterate through a list of objects in C++

You're close.

std::list<Student>::iterator it;
for (it = data.begin(); it != data.end(); ++it){
    std::cout << it->name;
}

Note that you can define it inside the for loop:

for (std::list<Student>::iterator it = data.begin(); it != data.end(); ++it){
    std::cout << it->name;
}

And if you are using C++11 then you can use a range-based for loop instead:

for (auto const& i : data) {
    std::cout << i.name;
}

Here auto automatically deduces the correct type. You could have written Student const& i instead.

How to check if object has any properties in JavaScript?

for(var memberName in ad)
{
  //Member Name: memberName
  //Member Value: ad[memberName]
}

Member means Member property, member variable, whatever you want to call it >_>

The above code will return EVERYTHING, including toString... If you only want to see if the object's prototype has been extended:

var dummyObj = {};  
for(var memberName in ad)
{
  if(typeof(dummyObj[memberName]) == typeof(ad[memberName])) continue; //note A
  //Member Name: memberName
  //Member Value: ad[memberName]

}

Note A: We check to see if the dummy object's member has the same type as our testing object's member. If it is an extend, dummyobject's member type should be "undefined"

Using the && operator in an if statement

So to make your expression work, changing && for -a will do the trick.

It is correct like this:

 if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
 then  ....

or like

 if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
 then  ....

or even

 if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
 then  ....

You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.

fatal: The current branch master has no upstream branch

You fixed the push, but, independently of that push issue (which I explained in "Why do I need to explicitly push a new branch?": git push -u origin master or git push -u origin --all), you need now to resolve the authentication issue.

That depends on your url (ssh as in '[email protected]/yourRepo, or https as in https://github.com/You/YourRepo)

For https url:

If your account is protected by the two-factor authentication, your regular password won't work (for https url), as explained here or here.

Same problem if your password contains special character (as in this answer)

If https doesn't work (because you don't want to generate a secondary key, a PAT: personal Access Token), then you can switch to ssh, as I have shown here.


As noted by qwerty in the comments, you can automatically create the branch of same name on the remote with:

git push -u origin head 

Why?

  • HEAD (see your .git\HEAD file) has the refspec of the currently checked out branch (for example: ref: refs/heads/master)
  • the default push policy is simple

Since the refpec used for this push is head: (no destination), a missing :<dst> means to update the same ref as the <src> (head, which is a branch).

That won't work if HEAD is detached though.

How to Execute stored procedure from SQL Plus?

You forgot to put z as an bind variable.

The following EXECUTE command runs a PL/SQL statement that references a stored procedure:

SQL> EXECUTE -
> :Z := EMP_SALE.HIRE('JACK','MANAGER','JONES',2990,'SALES')

Note that the value returned by the stored procedure is being return into :Z

Artisan, creating tables in database

Migration files must match the pattern *_*.php, or else they won't be found. Since users.php does not match this pattern (it has no underscore), this file will not be found by the migrator.

Ideally, you should be creating your migration files using artisan:

php artisan make:migration create_users_table

This will create the file with the appropriate name, which you can then edit to flesh out your migration. The name will also include the timestamp, to help the migrator determine the order of migrations.

You can also use the --create or --table switches to add a little bit more boilerplate to help get you started:

php artisan make:migration create_users_table --create=users

The documentation on migrations can be found here.

Running code after Spring Boot starts

Best way you use CommandLineRunner or ApplicationRunner The only difference between is run() method CommandLineRunner accepts array of string and ApplicationRunner accepts ApplicationArugument.

Clean up a fork and restart it from the upstream

How to do it 100% through the Sourcetree GUI

(Not everyone likes doing things through the git command line interface)

Once this has been set up, you only need to do steps 7-13 from then on.

Fetch > checkout master branch > reset to their master > Push changes to server

Steps

  1. In the menu toolbar at the top of the screen: "Repository" > "Repository settings"

"Repository" highlighted in the top menu bar

  1. "Add"

"Add" button at the bottom of the dialog

  1. Go back to GitHub and copy the clone URL.

"Clone or Download" button on the Github website followed by the git url

  1. Paste the url into the "URL / Path" field then give it a name that makes sense. I called it "master". Do not check the "Default remote" checkbox. You will not be able to push directly to this repository.

"Remote name" and "URL / Path" fields highlighted in the"Remote details" dialog

  1. Press "OK" and you should see it appear in your list of repositories now.

"master" repository added to the list of repositories in the "Repository settings" dialog

  1. Press "OK" again and you should see it appear in your list of "Remotes".

"master" repository highlighted in remotes list in side bar

  1. Click the "Fetch" button (top left of the Source tree header area)

"Fetch" button in the header area

  1. Make sure the "Fetch from all remotes" checkbox is checked and press "ok"

"Fetch from all remotes" checkbox highlighted in the "Fetch" dialog

  1. Double click on your "master" branch to check it out if it is not checked out already.

  2. Find the commit that you want to reset to, if you called the repo "master" you will most likely want to find the commit with the "master/master" tag on it.

Example of a commit with a "master/master" tag on it

  1. Right click on the commit > "Reset current branch to this commit".

  2. In the dialog, set the "Using mode:" field to "Hard - discard all working copy changes" then press "OK" (make sure to put any changes that you don't want to lose onto a separate branch first).

"Using mode" field highlighted in the "Reset to commit" dialog. It is set to "discard all working copy changes"

  1. Click the "Push" button (top left of the Source tree header area) to upload the changes to your copy of the repo.

"Push" button in the header area

Your Done!

Pass variables by reference in JavaScript

I know exactly what you mean. The same thing in Swift will be no problem. The bottom line is use let, not var.

The fact that primitives are passed by value, but the fact that the value of var i at the point of iteration is not copied into the anonymous function is quite surprising to say the least.

for (let i = 0; i < boxArray.length; i++) {
  boxArray[i].onclick = function() { console.log(i) }; // Correctly prints the index
}

Installation Issue with matplotlib Python

Problem Cause

In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.

Solution

  • I assume you have installed the pip matplotlib, there is a directory in your root called ~/.matplotlib.
  • Create a file ~/.matplotlib/matplotlibrc there and add the following code: backend: TkAgg

From this link you can try different diagrams.

Ruby: How to turn a hash into HTTP parameters?

If you are in the context of a Faraday request, you can also just pass the params hash as the second argument and faraday takes care of making proper param URL part out of it:

faraday_instance.get(url, params_hsh)

Facebook Android Generate Key Hash

In order to generate key hash you need to follow some easy steps.

1) Download Openssl from: here.

2) Make a openssl folder in C drive

3) Extract Zip files into this openssl folder created in C Drive.

4) Copy the File debug.keystore from .android folder in my case (C:\Users\SYSTEM.android) and paste into JDK bin Folder in my case (C:\Program Files\Java\jdk1.6.0_05\bin)

5) Open command prompt and give the path of JDK Bin folder in my case (C:\Program Files\Java\jdk1.6.0_05\bin).

6) Copy the following code and hit enter

keytool -exportcert -alias androiddebugkey -keystore debug.keystore > c:\openssl\bin\debug.txt

7) Now you need to enter password, Password = android.

8) If you see in openssl Bin folder, you will get a file with the name of debug.txt

9) Now either you can restart command prompt or work with existing command prompt

10) get back to C drive and give the path of openssl Bin folder

11) copy the following code and paste

openssl sha1 -binary debug.txt > debug_sha.txt

12) you will get debug_sha.txt in openssl bin folder

13) Again copy following code and paste

openssl base64 -in debug_sha.txt > debug_base64.txt

14) you will get debug_base64.txt in openssl bin folder

15) open debug_base64.txt file Here is your Key hash.

Merge, update, and pull Git branches without using checkouts

just to pull the master without checking out the master I use

git fetch origin master:master

Vue 2 - Mutating props vue-warn

Props down, events up. That's Vue's Pattern. The point is that if you try to mutate props passing from a parent. It won't work and it just gets overwritten repeatedly by the parent component. Child component can only emit an event to notify parent component to do sth. If you don't like these restrict, you can use VUEX(actually this pattern will suck in complex components structure, you should use VUEX!)

issue ORA-00001: unique constraint violated coming in INSERT/UPDATE

The error message will include the name of the constraint that was violated (there may be more than one unique constraint on a table). You can use that constraint name to identify the column(s) that the unique constraint is declared on

SELECT column_name, position
  FROM all_cons_columns
 WHERE constraint_name = <<name of constraint from the error message>>
   AND owner           = <<owner of the table>>
   AND table_name      = <<name of the table>>

Once you know what column(s) are affected, you can compare the data you're trying to INSERT or UPDATE against the data already in the table to determine why the constraint is being violated.

Promise Error: Objects are not valid as a React child

You can't just return an array of objects because there's nothing telling React how to render that. You'll need to return an array of components or elements like:

render: function() {
  return (
    <span>
      // This will go through all the elements in arrayFromJson and
      // render each one as a <SomeComponent /> with data from the object
      {this.state.arrayFromJson.map(function(object) {
        return (
          <SomeComponent key={object.id} data={object} />
        );
      })}
    </span>
  );
}

Replace specific characters within strings

Summarizing 2 ways to replace strings:

group<-data.frame(group=c("12357e", "12575e", "197e18", "e18947"))

1) Use gsub

group$group.no.e <- gsub("e", "", group$group)

2) Use the stringr package

group$group.no.e <- str_replace_all(group$group, "e", "")

Both will produce the desire output:

   group group.no.e
1 12357e      12357
2 12575e      12575
3 197e18      19718
4 e18947      18947

How to Remove Array Element and Then Re-Index Array?

Unset($array[0]); 

Sort($array); 

I don't know why this is being downvoted, but if anyone has bothered to try it, you will notice that it works. Using sort on an array reassigns the keys of the the array. The only drawback is it sorts the values. Since the keys will obviously be reassigned, even with array_values, it does not matter is the values are being sorted or not.

How do I set <table> border width with CSS?

The default border-style is none, so you must specify that as well as the width and the colour.

You can use the border shorthand property to set all three values in one go.

Also, the border attribute describes the border for the table and the cells. CSS is much more flexible so it only describes the border of the elements you are selecting. You need to select the cells too in order to get the same effect.

table, th, td {
    border: solid black 1px;
}

See also border properties and tables in CSS.

How to get multiline input from user

Use the input() built-in function to get a input line from the user.

You can read the help here.

You can use the following code to get several line at once (finishing by an empty one):

while input() != '':
    do_thing

Most efficient T-SQL way to pad a varchar on the left to a certain length?

I have one function that lpad with x decimals: CREATE FUNCTION [dbo].[LPAD_DEC] ( -- Add the parameters for the function here @pad nvarchar(MAX), @string nvarchar(MAX), @length int, @dec int ) RETURNS nvarchar(max) AS BEGIN -- Declare the return variable here DECLARE @resp nvarchar(max)

IF LEN(@string)=@length
BEGIN
    IF CHARINDEX('.',@string)>0
    BEGIN
        SELECT @resp = CASE SIGN(@string)
            WHEN -1 THEN
                -- Nros negativos grandes con decimales
                concat('-',SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(abs(@string),@length,@dec)))
            ELSE
                -- Nros positivos grandes con decimales
                concat(SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(@string,@length,@dec)))                  
            END
    END
    ELSE
    BEGIN
        SELECT @resp = CASE SIGN(@string)
            WHEN -1 THEN
                --Nros negativo grande sin decimales
                concat('-',SUBSTRING(replicate(@pad,@length),1,(@length-3)-len(@string)),ltrim(str(abs(@string),@length,@dec)))
            ELSE
                -- Nros positivos grandes con decimales
                concat(SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(@string,@length,@dec)))                  
            END                     
    END
END
ELSE
    IF CHARINDEX('.',@string)>0
    BEGIN
        SELECT @resp =CASE SIGN(@string)
            WHEN -1 THEN
                -- Nros negativos con decimales
                concat('-',SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(abs(@string),@length,@dec)))
            ELSE
                --Ntos positivos con decimales
                concat(SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(abs(@string),@length,@dec))) 
            END
    END
    ELSE
    BEGIN
        SELECT @resp = CASE SIGN(@string)
            WHEN -1 THEN
                -- Nros Negativos sin decimales
                concat('-',SUBSTRING(replicate(@pad,@length-3),1,(@length-3)-len(@string)),ltrim(str(abs(@string),@length,@dec)))
            ELSE
                -- Nros Positivos sin decimales
                concat(SUBSTRING(replicate(@pad,@length),1,(@length-3)-len(@string)),ltrim(str(abs(@string),@length,@dec)))
            END
    END
RETURN @resp

END

jQuery: go to URL with target="_blank"

Use,

var url = $(this).attr('href');
window.open(url, '_blank');

Update:the href is better off being retrieved with prop since it will return the full url and it's slightly faster.

var url = $(this).prop('href');

What is the max size of localStorage values?

Here's a straightforward script for finding out the limit:

if (localStorage && !localStorage.getItem('size')) {
    var i = 0;
    try {
        // Test up to 10 MB
        for (i = 250; i <= 10000; i += 250) {
            localStorage.setItem('test', new Array((i * 1024) + 1).join('a'));
        }
    } catch (e) {
        localStorage.removeItem('test');
        localStorage.setItem('size', i - 250);            
    }
}

Here's the gist, JSFiddle and blog post.

The script will test setting increasingly larger strings of text until the browser throws and exception. At that point it’ll clear out the test data and set a size key in localStorage storing the size in kilobytes.

How to randomize (shuffle) a JavaScript array?

Adding to @Laurens Holsts answer. This is 50% compressed.

function shuffleArray(d) {
  for (var c = d.length - 1; c > 0; c--) {
    var b = Math.floor(Math.random() * (c + 1));
    var a = d[c];
    d[c] = d[b];
    d[b] = a;
  }
  return d
};

How do I dispatch_sync, dispatch_async, dispatch_after, etc in Swift 3, Swift 4, and beyond?

Swift 4.1 and 5. We use queues in many places in our code. So, I created Threads class with all queues. If you don't want to use Threads class you can copy the desired queue code from class methods.

class Threads {

  static let concurrentQueue = DispatchQueue(label: "AppNameConcurrentQueue", attributes: .concurrent)
  static let serialQueue = DispatchQueue(label: "AppNameSerialQueue")

  // Main Queue
  class func performTaskInMainQueue(task: @escaping ()->()) {
    DispatchQueue.main.async {
      task()
    }
  }

  // Background Queue
  class func performTaskInBackground(task:@escaping () throws -> ()) {
    DispatchQueue.global(qos: .background).async {
      do {
        try task()
      } catch let error as NSError {
        print("error in background thread:\(error.localizedDescription)")
      }
    }
  }

  // Concurrent Queue
  class func perfromTaskInConcurrentQueue(task:@escaping () throws -> ()) {
    concurrentQueue.async {
      do {
        try task()
      } catch let error as NSError {
        print("error in Concurrent Queue:\(error.localizedDescription)")
      }
    }
  }

  // Serial Queue
  class func perfromTaskInSerialQueue(task:@escaping () throws -> ()) {
    serialQueue.async {
      do {
        try task()
      } catch let error as NSError {
        print("error in Serial Queue:\(error.localizedDescription)")
      }
    }
  }

  // Perform task afterDelay
  class func performTaskAfterDealy(_ timeInteval: TimeInterval, _ task:@escaping () -> ()) {
    DispatchQueue.main.asyncAfter(deadline: (.now() + timeInteval)) {
      task()
    }
  }
}

Example showing the use of main queue.

override func viewDidLoad() {
    super.viewDidLoad()
     Threads.performTaskInMainQueue {
        //Update UI
    }
}

How to get the current branch name in Git?

Well simple enough, I got it in a one liner (bash)

git branch | sed -n '/\* /s///p'

(credit: Limited Atonement)

And while I am there, the one liner to get the remote tracking branch (if any)

git rev-parse --symbolic-full-name --abbrev-ref @{u}

Calculating the distance between 2 points

You can use the below formula to find the distance between the 2 points:

distance*distance = ((x2 - x1)*(x2 - x1)) + ((y2 - y1)*(y2 - y1))

How can I match on an attribute that contains a certain string?

For the links which contains common url have to console in a variable. Then attempt it sequentially.

webelements allLinks=driver.findelements(By.xpath("//a[contains(@href,'http://122.11.38.214/dl/appdl/application/apk')]"));
int linkCount=allLinks.length();
for(int i=0; <linkCount;i++)
{
    driver.findelement(allLinks[i]).click();
}

How to do a for loop in windows command line?

This may help you find what you're looking for... Batch script loop

My answer is as follows:

@echo off
:start
set /a var+=1
if %var% EQU 100 goto end
:: Code you want to run goes here
goto start

:end
echo var has reached %var%.
pause
exit

The first set of commands under the start label loops until a variable, %var% reaches 100. Once this happens it will notify you and allow you to exit. This code can be adapted to your needs by changing the 100 to 17 and putting your code or using a call command followed by the batch file's path (Shift+Right Click on file and select "Copy as Path") where the comment is placed.

Sort array of objects by single key with date value

With ES2015 support it can be done by:

foo.sort((a, b) => a.updated_at < b.updated_at ? -1 : 1)

how to execute a scp command with the user name and password in one line

Using sshpass works best. To just include your password in scp use the ' ':

scp user1:'password'@xxx.xxx.x.5:sys_config /var/www/dev/

How can I list all of the files in a directory with Perl?

If you are a slacker like me you might like to use the File::Slurp module. The read_dir function will reads directory contents into an array, removes the dots, and if needed prefix the files returned with the dir for absolute paths

my @paths = read_dir( '/path/to/dir', prefix => 1 ) ;

Press enter in textbox to and execute button command

If you're just gonna click the button when Enter was pressed how about this?

private void textbox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            buttonSearch.PerformClick();
        }

What do 'lazy' and 'greedy' mean in the context of regular expressions?

'Greedy' means match longest possible string.

'Lazy' means match shortest possible string.

For example, the greedy h.+l matches 'hell' in 'hello' but the lazy h.+?l matches 'hel'.

Mongoose, Select a specific field with find

Example 1:

0 means ignore

1 means show

User.find({}, { createdAt: 0, updatedAt: 0, isActive: 0, _id : 1 }).then(...)

Example 2:

User.findById(id).select("_id, isActive").then(...)

How to insert a newline in front of a pattern?

in sed you can reference groups in your pattern with "\1", "\2", .... so if the pattern you're looking for is "PATTERN", and you want to insert "BEFORE" in front of it, you can use, sans escaping

sed 's/(PATTERN)/BEFORE\1/g'

i.e.

  sed 's/\(PATTERN\)/BEFORE\1/g'

JQuery datepicker not working

If jQuery UI datepicker isn't working but it used to work on similar DOM earlier, try removing all the classes and try binding it to just a simple input with its id. In my case a class was interfering with it and preventing the date picker to appear.

Android ListView with Checkbox and all clickable

Set the CheckBox as focusable="false" in your XML layout. Otherwise it will steal click events from the list view.

Of course, if you do this, you need to manually handle marking the CheckBox as checked/unchecked if the list item is clicked instead of the CheckBox, but you probably want that anyway.

`export const` vs. `export default` in ES6

It's a named export vs a default export. export const is a named export that exports a const declaration or declarations.

To emphasize: what matters here is the export keyword as const is used to declare a const declaration or declarations. export may also be applied to other declarations such as class or function declarations.

Default Export (export default)

You can have one default export per file. When you import you have to specify a name and import like so:

import MyDefaultExport from "./MyFileWithADefaultExport";

You can give this any name you like.

Named Export (export)

With named exports, you can have multiple named exports per file. Then import the specific exports you want surrounded in braces:

// ex. importing multiple exports:
import { MyClass, MyOtherClass } from "./MyClass";
// ex. giving a named import a different name by using "as":
import { MyClass2 as MyClass2Alias } from "./MyClass2";

// use MyClass, MyOtherClass, and MyClass2Alias here

Or it's possible to use a default along with named imports in the same statement:

import MyDefaultExport, { MyClass, MyOtherClass} from "./MyClass";

Namespace Import

It's also possible to import everything from the file on an object:

import * as MyClasses from "./MyClass";
// use MyClasses.MyClass, MyClasses.MyOtherClass and MyClasses.default here

Notes

  • The syntax favours default exports as slightly more concise because their use case is more common (See the discussion here).
  • A default export is actually a named export with the name default so you are able to import it with a named import:

    import { default as MyDefaultExport } from "./MyFileWithADefaultExport";
    

Can a table row expand and close?

jQuery

$(function() {
    $("td[colspan=3]").find("div").hide();
    $("tr").click(function(event) {
        var $target = $(event.target);
        $target.closest("tr").next().find("div").slideToggle();                
    });
});

HTML

<table>
    <thead>
        <tr>
            <th>one</th><th>two</th><th>three</th>
        </tr>
    </thead>
    <tbody>

        <tr>
            <td><p>data<p></td><td>data</td><td>data</td>
        </tr>
        <tr>
            <td colspan="3">
                <div>
                    <table>
                            <tr>
                                <td>data</td><td>data</td>
                            </tr>
                    </table>
                </div>
            </td>
        </tr>
    </tbody>
</table>

This is much like a previous example above. I found when trying to implement that example that if the table row to be expanded was clicked while it was not expanded it would disappear, and it would no longer be expandable

To fix that I simply removed the ability to click the expandable element for slide up and made it so that you can only toggle using the above table row.

I also made some minor changes to HTML and corresponding jQuery.

NOTE: I would have just made a comment but am not allowed to yet therefore the long post. Just wanted to post this as it took me a bit to figure out what was happening to the disappearing table row.

Credit to Peter Ajtai

Save current directory in variable using Bash?

I have the following in my .bash_profile:

function mark {
    export $1=`pwd`;
}

so anytime I want to remember a directory, I can just type, e.g. mark there .

Then when I want to go back to that location, I just type cd $there

Check Postgres access for a user

You could query the table_privileges table in the information schema:

SELECT table_catalog, table_schema, table_name, privilege_type
FROM   information_schema.table_privileges 
WHERE  grantee = 'MY_USER'

Where to find htdocs in XAMPP Mac

At least for macbook (os high sierra) go to terminal and type or copy and paste:

cd ~/.bitnami/stackman/machines/xampp/volumes/root/htdocs

Remove Safari/Chrome textinput/textarea glow

On textarea resizing in webkit based browsers:

Setting max-height and max-width on the textarea will not remove the visual resize handle. Try:

resize: none;

(and yes I agree with "try to avoid doing anything which breaks the user's expectation", but sometimes it does make sense, i.e. in the context of a web application)

To customize the look and feel of webkit form elements from scratch:

-webkit-appearance: none;

Creating dummy variables in pandas for python

Based on the official documentation:

dummies = pd.get_dummies(df['Category']).rename(columns=lambda x: 'Category_' + str(x))
df = pd.concat([df, dummies], axis=1)
df = df.drop(['Category'], inplace=True, axis=1)

There is also a nice post in the FastML blog.

CSS background image to fit width, height should auto-scale in proportion

Setting background size does not help, the following solution worked for me:

.class {
    background-image: url(blablabla.jpg);
    /* Add this */
    height: auto;
}

It basically crops the image and makes it fit in, background-size: contain/cover still didn't make it fit.

Change onClick attribute with javascript

Well, just do this and your problem is solved :

document.getElementById('buttonLED'+id).setAttribute('onclick','writeLED(1,1)')

Have a nice day XD

How to enable bulk permission in SQL Server

Try this:

USE master;

GO;
 
GRANT ADMINISTER BULK OPERATIONS TO shira;

Adding an assets folder in Android Studio

According to new Gradle based build system. We have to put assets under main folder.

Or simply right click on your project and create it like

File > New > folder > assets Folder

XMLHttpRequest module not defined/found

Since the last update of the xmlhttprequest module was around 2 years ago, in some cases it does not work as expected.

So instead, you can use the xhr2 module. In other words:

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();

becomes:

var XMLHttpRequest = require('xhr2');
var xhr = new XMLHttpRequest();

But ... of course, there are more popular modules like Axios, because -for example- uses promises:

// Make a request for a user with a given ID
axios.get('/user?ID=12345').then(function (response) {
    console.log(response);
}).catch(function (error) {
    console.log(error);
});

Run a PostgreSQL .sql file using command line arguments

Use this to execute *.sql files when the PostgreSQL server is located in a difference place:

psql -h localhost -d userstoreis -U admin -p 5432 -a -q -f /home/jobs/Desktop/resources/postgresql.sql

-h PostgreSQL server IP address
-d database name
-U user name
-p port which PostgreSQL server is listening on
-f path to SQL script
-a all echo
-q quiet

Then you are prompted to enter the password of the user.

EDIT: updated based on the comment provided by @zwacky

mysql is not recognised as an internal or external command,operable program or batch

In my case, I resolved it by adding this path C:\xampp\mysql\bin to system variables path and then restarted pash/cmd.

Note: Click me if you don't know how to set the path and system variables.

Save ArrayList to SharedPreferences

Hey friends I got the solution of above problem without using Gson library. Here I post source code.

1.Variable declaration i.e

  SharedPreferences shared;
  ArrayList<String> arrPackage;

2.Variable initialization i.e

 shared = getSharedPreferences("App_settings", MODE_PRIVATE);
 // add values for your ArrayList any where...
 arrPackage = new ArrayList<>();

3.Store value to sharedPreference using packagesharedPreferences():

 private void packagesharedPreferences() {
   SharedPreferences.Editor editor = shared.edit();
   Set<String> set = new HashSet<String>();
   set.addAll(arrPackage);
   editor.putStringSet("DATE_LIST", set);
   editor.apply();
   Log.d("storesharedPreferences",""+set);
 }

4.Retrive value of sharedPreference using retriveSharedValue():

 private void retriveSharedValue() {
   Set<String> set = shared.getStringSet("DATE_LIST", null);
   arrPackage.addAll(set);
   Log.d("retrivesharedPreferences",""+set);
 }

I hope it will helpful for you...

How to start up spring-boot application via command line?

Spring Boot provide the plugin with maven.

So you can go to your project directory and run

mvn spring-boot:run

This command line run will be easily when you're using spring-boot-devs-tool with auto reload/restart when you have changed you application.

How to start activity in another application?

If both application have the same signature (meaning that both APPS are yours and signed with the same key), you can call your other app activity as follows:

Intent LaunchIntent = getActivity().getPackageManager().getLaunchIntentForPackage(CALC_PACKAGE_NAME);
startActivity(LaunchIntent);

Hope it helps.

Calculate time difference in minutes in SQL Server

Please try as below to get the time difference in hh:mm:ss format

Select StartTime, EndTime, CAST((EndTime - StartTime) as time(0)) 'TotalTime' from [TableName]

Android studio Gradle build speed up

This is what I did and my gradle build speed improved dramatically! from 1 min to 20sec for the first build and succeeding builds became from 40 sec to 5 sec.

In the gradle.properties file Add this:

org.gradle.jvmargs=-Xmx8192M -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

In the Command Line Arguments via Go to File > Other Settings> default Settings >Build, Execution, Deploy> Complier and add the following arguments to Command Line Arguments

Add this:

--debug --stacktrace -a, --no-rebuild -q, --quiet --offline

See image here

How to split a number into individual digits in c#?

You can simply do:

"123456".Select(q => new string(q,1)).ToArray();

to have an enumerable of integers, as per comment request, you can:

"123456".Select(q => int.Parse(new string(q,1))).ToArray();

It is a little weak since it assumes the string actually contains numbers.

How To Check If A Key in **kwargs Exists?

It is just this:

if 'errormessage' in kwargs:
    print("yeah it's here")

You need to check, if the key is in the dictionary. The syntax for that is some_key in some_dict (where some_key is something hashable, not necessarily a string).

The ideas you have linked (these ideas) contained examples for checking if specific key existed in dictionaries returned by locals() and globals(). Your example is similar, because you are checking existence of specific key in kwargs dictionary (the dictionary containing keyword arguments).

Get request URL in JSP which is forwarded by Servlet

If you use RequestDispatcher.forward() to route the request from controller to the view, then request URI is exposed as a request attribute named javax.servlet.forward.request_uri. So, you can use

request.getAttribute("javax.servlet.forward.request_uri")

or

${requestScope['javax.servlet.forward.request_uri']}

Difference between size and length methods?

Based on the syntax I'm assuming that it is some language which is descendant of C. As per what I have seen, length is used for simple collection items like arrays and in most cases it is a property.

size() is a function and is used for dynamic collection objects. However for all the purposes of using, you wont find any differences in outcome using either of them. In most implementations, size simply returns length property.

How do I format {{$timestamp}} as MM/DD/YYYY in Postman?

You could use moment.js with Postman to give you that timestamp format.

You can add this to the pre-request script:

const moment = require('moment');
pm.globals.set("today", moment().format("MM/DD/YYYY"));

Then reference {{today}} where ever you need it.

If you add this to the Collection Level Pre-request Script, it will be run for each request in the Collection. Rather than needing to add it to all the requests individually.

For more information about using moment in Postman, I wrote a short blog post: https://dannydainton.com/2018/05/21/hold-on-wait-a-moment/

AngularJS - Value attribute on an input text box is ignored when there is a ng-model used?

The Angular way

The correct Angular way to do this is to write a single page app, AJAX in the form template, then populate it dynamically from the model. The model is not populated from the form by default because the model is the single source of truth. Instead Angular will go the other way and try to populate the form from the model.

If however, you don't have time to start over from scratch

If you have an app written, this might involve some fairly hefty architectural changes. If you're trying to use Angular to enhance an existing form, rather than constructing an entire single page app from scratch, you can pull the value from the form and store it in the scope at link time using a directive. Angular will then bind the value in the scope back to the form and keep it in sync.

Using a directive

You can use a relatively simple directive to pull the value from the form and load it in to the current scope. Here I've defined an initFromForm directive.

var myApp = angular.module("myApp", ['initFromForm']);

angular.module('initFromForm', [])
  .directive("initFromForm", function ($parse) {
    return {
      link: function (scope, element, attrs) {
        var attr = attrs.initFromForm || attrs.ngModel || element.attrs('name'),
        val = attrs.value;
        if (attrs.type === "number") {val = parseInt(val)}
        $parse(attr).assign(scope, val);
      }
    };
  });

You can see I've defined a couple of fallbacks to get a model name. You can use this directive in conjunction with the ngModel directive, or bind to something other than $scope if you prefer.

Use it like this:

<input name="test" ng-model="toaster.test" value="hello" init-from-form />
{{toaster.test}}

Note this will also work with textareas, and select dropdowns.

<textarea name="test" ng-model="toaster.test" init-from-form>hello</textarea>
{{toaster.test}}

What port is used by Java RMI connection?

You typically set the port at the server using the rmiregistry command. You can set the port on the command line, or it will default to 1099

What is token-based authentication?

I think it's well explained here -- quoting just the key sentences of the long article:

The general concept behind a token-based authentication system is simple. Allow users to enter their username and password in order to obtain a token which allows them to fetch a specific resource - without using their username and password. Once their token has been obtained, the user can offer the token - which offers access to a specific resource for a time period - to the remote site.

In other words: add one level of indirection for authentication -- instead of having to authenticate with username and password for each protected resource, the user authenticates that way once (within a session of limited duration), obtains a time-limited token in return, and uses that token for further authentication during the session.

Advantages are many -- e.g., the user could pass the token, once they've obtained it, on to some other automated system which they're willing to trust for a limited time and a limited set of resources, but would not be willing to trust with their username and password (i.e., with every resource they're allowed to access, forevermore or at least until they change their password).

If anything is still unclear, please edit your question to clarify WHAT isn't 100% clear to you, and I'm sure we can help you further.

How can I add additional PHP versions to MAMP

Maybe easy like this?

Compiled binaries of the PHP interpreter can be found at http://www.mamp.info/en/ downloads/index.html . Drop this downloaded folder into your /Applications/MAMP/bin/php! directory. Close and re-open your MAMP PRO application. Your new PHP version should now appear in the PHP drop down menu. MAMP PRO will only support PHP versions from the downloads page.

Twig: in_array or similar possible within if statement?

It should help you.

{% for user in users if user.active and user.id not 1 %}
   {{ user.name }}
{% endfor %}

More info: http://twig.sensiolabs.org/doc/tags/for.html

Sleep function in C++

You'll need at least C++11.

#include <thread>
#include <chrono>

...

std::this_thread::sleep_for(std::chrono::milliseconds(200));

remove all special characters in java

use [\\W+] or "[^a-zA-Z0-9]" as regex to match any special characters and also use String.replaceAll(regex, String) to replace the spl charecter with an empty string. remember as the first arg of String.replaceAll is a regex you have to escape it with a backslash to treat em as a literal charcter.

          String c= "hjdg$h&jk8^i0ssh6";
        Pattern pt = Pattern.compile("[^a-zA-Z0-9]");
        Matcher match= pt.matcher(c);
        while(match.find())
        {
            String s= match.group();
        c=c.replaceAll("\\"+s, "");
        }
        System.out.println(c);

How to update TypeScript to latest version with npm?

Open command prompt (cmd.exe/git bash)

Recommended:

npm install -g typescript@latest

or

yarn global add typescript@latest  // if you use yarn package manager

This will install the latest typescript version if not already installed, otherwise it will update the current installation to the latest version.

And then verify which version is installed:

tsc -v

enter image description here


If you have typescript already installed you could also use the following command to update to latest version, but as commentators have reported and I confirm it that the following command does not update to latest (as of now [ Feb 10 '17])!

npm update -g typescript@latest

Convert a Map<String, String> to a POJO

convert Map to POJO example.Notice the Map key contains underline and field variable is hump.

User.class POJO

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

@Data
public class User {
    @JsonProperty("user_name")
    private String userName;
    @JsonProperty("pass_word")
    private String passWord;
}

The App.class test the example

import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;

public class App {
    public static void main(String[] args) {
        Map<String, String> info = new HashMap<>();
        info.put("user_name", "Q10Viking");
        info.put("pass_word", "123456");

        ObjectMapper mapper = new ObjectMapper();
        User user = mapper.convertValue(info, User.class);

        System.out.println("-------------------------------");
        System.out.println(user);
    }
}
/**output
-------------------------------
User(userName=Q10Viking, passWord=123456)
 */

Most efficient conversion of ResultSet to JSON?

For all who've opted for the if-else mesh solution, please use:

String columnName = metadata.getColumnName(
String displayName = metadata.getColumnLabel(i);
switch (metadata.getColumnType(i)) {
case Types.ARRAY:
    obj.put(displayName, resultSet.getArray(columnName));
    break;
...

Because in case of aliases in your query, the column name and column label are two different things. For example if you execute:

select col1, col2 as my_alias from table

You will get

[
    { "col1": 1, "col2": 2 }, 
    { "col1": 1, "col2": 2 }
]

Rather than:

[
    { "col1": 1, "my_alias": 2 }, 
    { "col1": 1, "my_alias": 2 }
]

vertical alignment of text element in SVG

attr("dominant-baseline", "central")

git: Your branch is ahead by X commits

I went through every solution on this page, and fortunately @anatolii-pazhyn commented because his solution was the one that worked. Unfortunately I don't have enough reputation to upvote him, but I recommend trying his solution first:

git reset --hard origin/master

Which gave me:

HEAD is now at 900000b Comment from my last git commit here

I also recommend:

git rev-list origin..HEAD
# to see if the local repository is ahead, push needed

git rev-list HEAD..origin
# to see if the local repository is behind, pull needed

You can also use:

git rev-list --count --left-right origin/master...HEAD
# if you have numbers for both, then the two repositories have diverged

Best of luck

Abstract methods in Python

See the abc module. Basically, you define __metaclass__ = abc.ABCMeta on the class, then decorate each abstract method with @abc.abstractmethod. Classes derived from this class cannot then be instantiated unless all abstract methods have been overridden.

If your class is already using a metaclass, derive it from ABCMeta rather than type and you can continue to use your own metaclass.

A cheap alternative (and the best practice before the abc module was introduced) would be to have all your abstract methods just raise an exception (NotImplementedError is a good one) so that classes derived from it would have to override that method to be useful.

However, the abc solution is better because it keeps such classes from being instantiated at all (i.e., it "fails faster"), and also because you can provide a default or base implementation of each method that can be reached using the super() function in derived classes.

JavaScript adding decimal numbers issue

Testing this Javascript:

var arr = [1234563995.721, 12345691212.718, 1234568421.5891, 12345677093.49284];

var sum = 0;
for( var i = 0; i < arr.length; i++ ) {
    sum += arr[i];
}

alert( "fMath(sum) = " + Math.round( sum * 1e12 ) / 1e12 );
alert( "fFixed(sum) = " + sum.toFixed( 5 ) );

Conclusion

Dont use Math.round( (## + ## + ... + ##) * 1e12) / 1e12

Instead, use ( ## + ## + ... + ##).toFixed(5) )

In IE 9, toFixed works very well.

How to create SPF record for multiple IPs?

The open SPF wizard from the previous answer is no longer available, neither the one from Microsoft.

Where does the @Transactional annotation belong?

Transactional Annotations should be placed around all operations that are inseparable.

For example, your call is "change password". That consists of two operations

  1. Change the password.
  2. Audit the change.
  3. Email the client that the password has changed.

So in the above, if the audit fails, then should the password change also fail? If so, then the transaction should be around 1 and 2 (so at the service layer). If the email fails (probably should have some kind of fail safe on this so it won't fail) then should it roll back the change password and the audit?

These are the kind of questions you need to be asking when deciding where to put the @Transactional.

Pandas unstack problems: ValueError: Index contains duplicate entries, cannot reshape

I had such problem. In my case problem was in data - my column 'information' contained 1 unique value and it caused error

UPDATE: to correct work 'pivot' pairs (id_user,information) cannot have duplicates

It works:

df2 = pd.DataFrame({'id_user':[1,2,3,4,4,5,5], 
'information':['phon','phon','phone','phone1','phone','phone1','phone'], 
'value': [1, '01.01.00', '01.02.00', 2, '01.03.00', 3, '01.04.00']})
df2.pivot(index='id_user', columns='information', values='value')

it doesn't work:

df2 = pd.DataFrame({'id_user':[1,2,3,4,4,5,5], 
'information':['phone','phone','phone','phone','phone','phone','phone'], 
'value': [1, '01.01.00', '01.02.00', 2, '01.03.00', 3, '01.04.00']})
df2.pivot(index='id_user', columns='information', values='value')

source: https://stackoverflow.com/a/37021196/6088984

Detecting when Iframe content has loaded (Cross browser)

For those using React, detecting a same-origin iframe load event is as simple as setting onLoad event listener on iframe element.

<iframe src={'path-to-iframe-source'} onLoad={this.loadListener} frameBorder={0} />

How to add "class" to host element?

You can simply add @HostBinding('class') class = 'someClass'; inside your @Component class.

Example:

@Component({
   selector: 'body',
   template: 'app-element'       
})
export class App implements OnInit {

  @HostBinding('class') class = 'someClass';

  constructor() {}      

  ngOnInit() {}
}

Bash foreach loop

If they all have the same extension (for example .jpg), you can use this:

for picture in  *.jpg ; do
    echo "the next file is $picture"
done

(This solution also works if the filename has spaces)

Error: Cannot access file bin/Debug/... because it is being used by another process

See my answer here if you're having this problem while running unit tests. Answer copied below:

Building upon Sébastien's answer, I added a pre-build step to my test project to automatically kill any vstest.* executables still running. The following pre-build command worked for me:

taskkill /f /im vstest.*
exit 0

The exit 0 command is at the end to prevent build failure when there are no vstest.* executables running.

Order data frame rows according to vector with specific order

Here's a similar system for the situation where you have a variable you want to sort by, initially, but then you want to sort by a secondary variable according to the order that this secondary variable first appears in the initial sort.

In the function below, the initial sort variable is called order_by and the secondary variable is called order_along - as in "order by this variable along its initial order".

library(dplyr, warn.conflicts = FALSE)
df <- structure(
  list(
    msoa11hclnm = c(
      "Bewbush", "Tilgate", "Felpham",
      "Selsey", "Brunswick", "Ratton", "Ore", "Polegate", "Mile Oak",
      "Upperton", "Arundel", "Kemptown"
    ),
    lad20nm = c(
      "Crawley", "Crawley",
      "Arun", "Chichester", "Brighton and Hove", "Eastbourne", "Hastings",
      "Wealden", "Brighton and Hove", "Eastbourne", "Arun", "Brighton and Hove"
    ),
    shape_area = c(
      1328821, 3089180, 3540014, 9738033, 448888, 10152663, 5517102,
      7036428, 5656430, 2653589, 72832514, 826151
    )
  ),
  row.names = c(NA, -12L), class = "data.frame"
)

this does not give me what I need:

df %>% 
  dplyr::arrange(shape_area, lad20nm)
#>    msoa11hclnm           lad20nm shape_area
#> 1    Brunswick Brighton and Hove     448888
#> 2     Kemptown Brighton and Hove     826151
#> 3      Bewbush           Crawley    1328821
#> 4     Upperton        Eastbourne    2653589
#> 5      Tilgate           Crawley    3089180
#> 6      Felpham              Arun    3540014
#> 7          Ore          Hastings    5517102
#> 8     Mile Oak Brighton and Hove    5656430
#> 9     Polegate           Wealden    7036428
#> 10      Selsey        Chichester    9738033
#> 11      Ratton        Eastbourne   10152663
#> 12     Arundel              Arun   72832514

Here’s a function:

order_along <- function(df, order_along, order_by) {
  cols <- colnames(df)
  
  df <- df %>%
    dplyr::arrange({{ order_by }})
  
  df %>% 
    dplyr::select({{ order_along }}) %>% 
    dplyr::distinct() %>% 
    dplyr::full_join(df) %>% 
    dplyr::select(dplyr::all_of(cols))
  
}

order_along(df, lad20nm, shape_area)
#> Joining, by = "lad20nm"
#>    msoa11hclnm           lad20nm shape_area
#> 1    Brunswick Brighton and Hove     448888
#> 2     Kemptown Brighton and Hove     826151
#> 3     Mile Oak Brighton and Hove    5656430
#> 4      Bewbush           Crawley    1328821
#> 5      Tilgate           Crawley    3089180
#> 6     Upperton        Eastbourne    2653589
#> 7       Ratton        Eastbourne   10152663
#> 8      Felpham              Arun    3540014
#> 9      Arundel              Arun   72832514
#> 10         Ore          Hastings    5517102
#> 11    Polegate           Wealden    7036428
#> 12      Selsey        Chichester    9738033

Created on 2021-01-12 by the reprex package (v0.3.0)

JUnit Eclipse Plugin?

JUnit is part of Eclipse Java Development Tools (JDT). So, either install the JDT via Software Updates or download and install Eclipse IDE for Java Developers (actually, I'd recommend installing Eclipse IDE for Java EE Developers if you want a complete built-in environment for server side development).

You add it to a project by right clicking the project in the Package Explorer and selecting Build Path -> Add Libraries... Then simply select JUnit and click Next >.

No visible cause for "Unexpected token ILLEGAL"

I changed all space areas to &nbsp, just like that and it worked without problem.

val.replace(" ", "&nbsp");

I hope it helps someone.

"Integer number too large" error message for 600851475143

600851475143 cannot be represented as a 32-bit integer (type int). It can be represented as a 64-bit integer (type long). long literals in Java end with an "L": 600851475143L

Reference requirements.txt for the install_requires kwarg in setuptools setup.py file

Cross posting my answer from this SO question for another simple, pip version proof solution.

try:  # for pip >= 10
    from pip._internal.req import parse_requirements
    from pip._internal.download import PipSession
except ImportError:  # for pip <= 9.0.3
    from pip.req import parse_requirements
    from pip.download import PipSession

requirements = parse_requirements(os.path.join(os.path.dirname(__file__), 'requirements.txt'), session=PipSession())

if __name__ == '__main__':
    setup(
        ...
        install_requires=[str(requirement.req) for requirement in requirements],
        ...
    )

Then just throw in all your requirements under requirements.txt under project root directory.

How to check if a variable exists in a FreeMarker template?

This one seems to be a better fit:

<#if userName?has_content>
... do something
</#if>

http://freemarker.sourceforge.net/docs/ref_builtins_expert.html

How to check if element is visible after scrolling?

jQuery Waypoints plugin goes very nice here.

$('.entry').waypoint(function() {
   alert('You have scrolled to an entry.');
});

There are some examples on the site of the plugin.

Returning boolean if set is empty

If you want to return True for an empty set, then I think it would be clearer to do:

return c == set()

i.e. "c is equal to an empty set".

(Or, for the other way around, return c != set()).

In my opinion, this is more explicit (though less idiomatic) than relying on Python's interpretation of an empty set as False in a boolean context.

How best to include other scripts?

I put all my startup scripts in a .bashrc.d directory. This is a common technique in such places as /etc/profile.d, etc.

while read file; do source "${file}"; done <<HERE
$(find ${HOME}/.bashrc.d -type f)
HERE

The problem with the solution using globbing...

for file in ${HOME}/.bashrc.d/*.sh; do source ${file};done

...is you might have a file list which is "too long". An approach like...

find ${HOME}/.bashrc.d -type f | while read file; do source ${file}; done

...runs but doesn't change the environment as desired.

Use Mockito to mock some methods but not others

Partial mocking using Mockito's spy method could be the solution to your problem, as already stated in the answers above. To some degree I agree that, for your concrete use case, it may be more appropriate to mock the DB lookup. From my experience this is not always possible - at least not without other workarounds - that I would consider as being very cumbersome or at least fragile. Note, that partial mocking does not work with ally versions of Mockito. You have use at least 1.8.0.

I would have just written a simple comment for the original question instead of posting this answer, but StackOverflow does not allow this.

Just one more thing: I really cannot understand that many times a question is being asked here gets comment with "Why you want to do this" without at least trying to understand the problem. Escpecially when it comes to then need for partial mocking there are really a lot of use cases that I could imagine where it would be useful. That's why the guys from Mockito provided that functionality. This feature should of course not be overused. But when we talk about test case setups that otherwise could not be established in a very complicated way, spying should be used.

Remove last item from array

// Setup
var myArray = [["John", 23], ["cat", 2]];

// Only change code below this line
var removedFromMyArray;
removedFromMyArray = myArray.pop()

What is the difference between Left, Right, Outer and Inner Joins?

Check out Join (SQL) on Wikipedia

  • Inner join - Given two tables an inner join returns all rows that exist in both tables
  • left / right (outer) join - Given two tables returns all rows that exist in either the left or right table of your join, plus the rows from the other side will be returned when the join clause is a match or null will be returned for those columns

  • Full Outer - Given two tables returns all rows, and will return nulls when either the left or right column is not there

  • Cross Joins - Cartesian join and can be dangerous if not used carefully

How do I install command line MySQL client on mac?

if you need a lighter solution i recommend mysql-shell, install using the command below.

brew cask install mysql-shell

To start after installation type mysqlsh.

Routing HTTP Error 404.0 0x80070002

The solution suggested

<system.webServer>
  <modules runAllManagedModulesForAllRequests="true" >
    <remove name="UrlRoutingModule"/>    
  </modules>
</system.webServer>

works, but can degrade performance and can even cause errors, because now all registered HTTP modules run on every request, not just managed requests (e.g. .aspx). This means modules will run on every .jpg .gif .css .html .pdf etc.

A more sensible solution is to include this in your web.config:

<system.webServer>
  <modules>
    <remove name="UrlRoutingModule-4.0" />
    <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
  </modules>
</system.webServer>

Credit for his goes to Colin Farr. Check-out his post about this topic at http://www.britishdeveloper.co.uk/2010/06/dont-use-modules-runallmanagedmodulesfo.html.

jquery stop child triggering parent event

Do this:

$(document).ready(function(){
    $(".header").click(function(){
        $(this).children(".children").toggle();
    });
   $(".header a").click(function(e) {
        e.stopPropagation();
   });
});

If you want to read more on .stopPropagation(), look here.

PHP: Call to undefined function: simplexml_load_string()

If the XML module is not installed, install it.

Current version 5.6 on ubuntu 14.04:

sudo apt-get install php5.6-xml

And don't forget to run sudo service apache2 restart command after it

Zulhilmi Zainudi

How can I make setInterval also work when a tab is inactive in Chrome?

Playing an audio file ensures full background Javascript performance for the time being

For me, it was the simplest and least intrusive solution - apart from playing a faint / almost-empty sound, there are no other potential side effects

You can find the details here: https://stackoverflow.com/a/51191818/914546

(From other answers, I see that some people use different properties of the Audio tag, I do wonder whether it's possible to use the Audio tag for full performance, without actually playing something)

How to set default value to the input[type="date"]

Here are three statements for three different dates in the form with three type=date fields.

$inv_date is the current date:

$inv_date = date("Y-m-d");

$inv_date_from is the first day of the current month:

$inv_date_from = date("Y") . "-" . date("m") . "-" . "01";

$inv_date_to is the last day of the month:

$inv_date_to = date("Y-m-t", strtotime(date("Y-m-t")));

I hope this helps :)

'Use of Unresolved Identifier' in Swift

My issue was calling my program with the same name as one of its cocoapods. It caused a conflict. Solution: Create a program different name.

How to display line numbers in 'less' (GNU)

If you hit = and expect to see line numbers, but only see byte counts, then line numbers are turned off. Hit -n to turn them on, and make sure $LESS doesn't include 'n'.

Turning off line numbers by default (for example, setting LESS=n) speeds up searches in very large files. It is handy if you frequently search through big files, but don't usually care which line you're on.

I typically run with LESS=RSXin (escape codes enabled, long lines chopped, don't clear the screen on exit, ignore case on all lower case searches, and no line number counting by default) and only use -n or -S from inside less as needed.

Action Image MVC3 Razor

I have joined the answer from Lucas and "ASP.NET MVC Helpers, Merging two object htmlAttributes together" and plus controllerName to following code:

// Sample usage in CSHTML

 @Html.ActionImage("Edit",
       "EditController"
        new { id = MyId },
       "~/Content/Images/Image.bmp",
       new { width=108, height=129, alt="Edit" })

And the extension class for the code above:

using System.Collections.Generic;
using System.Reflection;
using System.Web.Mvc;

namespace MVC.Extensions
{
    public static class MvcHtmlStringExt
    {
        // Extension method
        public static MvcHtmlString ActionImage(
          this HtmlHelper html,
          string action,
          string controllerName,
          object routeValues,
          string imagePath,
          object htmlAttributes)
        {
            //https://stackoverflow.com/questions/4896439/action-image-mvc3-razor
            var url = new UrlHelper(html.ViewContext.RequestContext);

            // build the <img> tag
            var imgBuilder = new TagBuilder("img");
            imgBuilder.MergeAttribute("src", url.Content(imagePath));

            var dictAttributes = htmlAttributes.ToDictionary();

            if (dictAttributes != null)
            {
                foreach (var attribute in dictAttributes)
                {
                    imgBuilder.MergeAttribute(attribute.Key, attribute.Value.ToString(), true);
                }
            }                        

            string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);

            // build the <a> tag
            var anchorBuilder = new TagBuilder("a");
            anchorBuilder.MergeAttribute("href", url.Action(action, controllerName, routeValues));
            anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside            
            string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);

            return MvcHtmlString.Create(anchorHtml);
        }

        public static IDictionary<string, object> ToDictionary(this object data)
        {
            //https://stackoverflow.com/questions/6038255/asp-net-mvc-helpers-merging-two-object-htmlattributes-together

            if (data == null) return null; // Or throw an ArgumentNullException if you want

            BindingFlags publicAttributes = BindingFlags.Public | BindingFlags.Instance;
            Dictionary<string, object> dictionary = new Dictionary<string, object>();

            foreach (PropertyInfo property in
                     data.GetType().GetProperties(publicAttributes))
            {
                if (property.CanRead)
                {
                    dictionary.Add(property.Name, property.GetValue(data, null));
                }
            }
            return dictionary;
        }
    }
}

Determine if char is a num or letter

<ctype.h> includes a range of functions for determining if a char represents a letter or a number, such as isalpha, isdigit and isalnum.

The reason why int a = (int)theChar won't do what you want is because a will simply hold the integer value that represents a specific character. For example the ASCII number for '9' is 57, and for 'a' it's 97.

Also for ASCII:

  • Numeric - if (theChar >= '0' && theChar <= '9')
  • Alphabetic -
    if (theChar >= 'A' && theChar <= 'Z' || theChar >= 'a' && theChar <= 'z')

Take a look at an ASCII table to see for yourself.

How to select the row with the maximum value in each group

Another base solution

group_sorted <- group[order(group$Subject, -group$pt),]
group_sorted[!duplicated(group_sorted$Subject),]

# Subject pt Event
#       1  5     2
#       2 17     2
#       3  5     2

Order the data frame by pt (descending) and then remove rows duplicated in Subject

Match everything except for specified strings

Matching any text but those matching a pattern is usually achieved with splitting the string with the regex pattern.

Examples:

  • - Regex.Split(text, @"red|green|blue") or, to get rid of empty values, Regex.Split(text, @"red|green|blue").Where(x => !string.IsNullOrEmpty(x)) (see demo)
  • - Regex.Split(text, "red|green|blue") or, to remove empty items, Regex.Split(text, "red|green|blue").Where(Function(s) Not String.IsNullOrWhitespace(s)) (see demo, or this demo where LINQ is supported)
  • - text.split(/red|green|blue/) (no need to use g modifier here!) (to get rid of empty values, use text.split(/red|green|blue/).filter(Boolean)), see demo
  • - text.split("red|green|blue"), or - to keep all trailing empty items - use text.split("red|green|blue", -1), or to remove all empty items use more code to remove them (see demo)
  • - Similar to Java, text.split(/red|green|blue/), to get all trailing items use text.split(/red|green|blue/, -1) and to remove all empty items use text.split(/red|green|blue/).findAll {it != ""}) (see demo)
  • - text.split(Regex("red|green|blue")) or, to remove blank items, use text.split(Regex("red|green|blue")).filter{ !it.isBlank() }, see demo
  • - text.split("red|green|blue"), or to keep all trailing empty items, use text.split("red|green|blue", -1) and to remove all empty items, use text.split("red|green|blue").filter(_.nonEmpty) (see demo)
  • - text.split(/red|green|blue/), to get rid of empty values use .split(/red|green|blue/).reject(&:empty?) (and to get both leading and trailing empty items, use -1 as the second argument, .split(/red|green|blue/, -1)) (see demo)
  • - my @result1 = split /red|green|blue/, $text;, or with all trailing empty items, my @result2 = split /red|green|blue/, $text, -1;, or without any empty items, my @result3 = grep { /\S/ } split /red|green|blue/, $text; (see demo)
  • - preg_split('~red|green|blue~', $text) or preg_split('~red|green|blue~', $text, -1, PREG_SPLIT_NO_EMPTY) to output no empty items (see demo)
  • - re.split(r'red|green|blue', text) or, to remove empty items, list(filter(None, re.split(r'red|green|blue', text))) (see demo)
  • - Use regexp.MustCompile("red|green|blue").Split(text, -1), and if you need to remove empty items, use this code. See Go demo.

NOTE: If you patterns contain capturing groups, regex split functions/methods may behave differently, also depending on additional options. Please refer to the appropriate split method documentation then.

How to debug in Django, the good way?

Most options are alredy mentioned. To print template context, I've created a simple library for that. See https://github.com/edoburu/django-debugtools

You can use it to print template context without any {% load %} construct:

{% print var %}   prints variable
{% print %}       prints all

It uses a customized pprint format to display the variables in a <pre> tag.

How to make sure that a certain Port is not occupied by any other process

netstat -ano|find ":port_no" will give you the list.
a: Displays all connections and listening ports.
n: Displays addresses and port numbers in numerical form.
o: Displays the owning process ID associated with each connection .

example : netstat -ano | find ":1900" This gives you the result like this.

UDP    107.109.121.196:1900   *:*                                    1324  
UDP    127.0.0.1:1900         *:*                                    1324  
UDP    [::1]:1900             *:*                                    1324  
UDP    [fe80::8db8:d9cc:12a8:2262%13]:1900  *:*                      1324

How do I correctly setup and teardown for my pytest class with tests?

According to Fixture finalization / executing teardown code, the current best practice for setup and teardown is to use yield instead of return:

import pytest

@pytest.fixture()
def resource():
    print("setup")
    yield "resource"
    print("teardown")

class TestResource:
    def test_that_depends_on_resource(self, resource):
        print("testing {}".format(resource))

Running it results in

$ py.test --capture=no pytest_yield.py
=== test session starts ===
platform darwin -- Python 2.7.10, pytest-3.0.2, py-1.4.31, pluggy-0.3.1
collected 1 items

pytest_yield.py setup
testing resource
.teardown


=== 1 passed in 0.01 seconds ===

Another way to write teardown code is by accepting a request-context object into your fixture function and calling its request.addfinalizer method with a function that performs the teardown one or multiple times:

import pytest

@pytest.fixture()
def resource(request):
    print("setup")

    def teardown():
        print("teardown")
    request.addfinalizer(teardown)
    
    return "resource"

class TestResource:
    def test_that_depends_on_resource(self, resource):
        print("testing {}".format(resource))

How to write multiple conditions of if-statement in Robot Framework

The below code worked fine:

Run Keyword if    '${value1}' \ \ == \ \ '${cost1}' \ and \ \ '${value2}' \ \ == \ \ 'cost2'    LOG    HELLO

NoClassDefFoundError while trying to run my jar with java.exe -jar...what's wrong?

The -jar option is mutually exclusive of -classpath. See an old description here

-jar

Execute a program encapsulated in a JAR file. The first argument is the name of a JAR file instead of a startup class name. In order for this option to work, the manifest of the JAR file must contain a line of the form Main-Class: classname. Here, classname identifies the class having the public static void main(String[] args) method that serves as your application's starting point.

See the Jar tool reference page and the Jar trail of the Java Tutorial for information about working with Jar files and Jar-file manifests.

When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.

A quick and dirty hack is to append your classpath to the bootstrap classpath:

-Xbootclasspath/a:path

Specify a colon-separated path of directires, JAR archives, and ZIP archives to append to the default bootstrap class path.

However, as @Dan rightly says, the correct solution is to ensure your JARs Manifest contains the classpath for all JARs it will need.

JavaScript equivalent of PHP's in_array()

function in_array(needle, haystack){

    return haystack.indexOf(needle) !== -1;
}

Find the division remainder of a number

From Python 3.7, there is a new math.remainder() function:

from math import remainder
print(remainder(26,7))

Output:

-2.0  # not 5

Note, as above, it's not the same as %.

Quoting the documentation:

math.remainder(x, y)

Return the IEEE 754-style remainder of x with respect to y. For finite x and finite nonzero y, this is the difference x - n*y, where n is the closest integer to the exact value of the quotient x / y. If x / y is exactly halfway between two consecutive integers, the nearest even integer is used for n. The remainder r = remainder(x, y) thus always satisfies abs(r) <= 0.5 * abs(y).

Special cases follow IEEE 754: in particular, remainder(x, math.inf) is x for any finite x, and remainder(x, 0) and remainder(math.inf, x) raise ValueError for any non-NaN x. If the result of the remainder operation is zero, that zero will have the same sign as x.

On platforms using IEEE 754 binary floating-point, the result of this operation is always exactly representable: no rounding error is introduced.

Issue29962 describes the rationale for creating the new function.

Eclipse error: "Editor does not contain a main type"

Try closing and reopening the file, then press Ctrl+F11.

Verify that the name of the file you are running is the same as the name of the project you are working in, and that the name of the public class in that file is the same as the name of the project you are working in as well.

Otherwise, restart Eclipse. Let me know if this solves the problem! Otherwise, comment, and I'll try and help.

How do you cache an image in Javascript

Yes, the browser caches images for you, automatically.

You can, however, set an image cache to expire. Check out this Stack Overflow questions and answer:

Cache Expiration On Static Images

Do HttpClient and HttpClientHandler have to be disposed between requests?

I think one should use singleton pattern to avoid having to create instances of the HttpClient and closing it all the time. If you are using .Net 4.0 you could use a sample code as below. for more information on singleton pattern check here.

class HttpClientSingletonWrapper : HttpClient
{
    private static readonly Lazy<HttpClientSingletonWrapper> Lazy= new Lazy<HttpClientSingletonWrapper>(()=>new HttpClientSingletonWrapper()); 

    public static HttpClientSingletonWrapper Instance {get { return Lazy.Value; }}

    private HttpClientSingletonWrapper()
    {
    }
}

Use the code as below.

var client = HttpClientSingletonWrapper.Instance;

Set line spacing

I am not sure if this is what you meant:

line-height: size;

How to remove special characters from a string?

If you just want to do a literal replace in java, use Pattern.quote(string) to escape any string to a literal.

myString.replaceAll(Pattern.quote(matchingStr), replacementStr)

Shell script to copy files from one location to another location and rename add the current date to every file

You can be used this step is very useful:

for i in `ls -l folder1 | grep -v total | awk '{print $ ( ? )}'`
do
   cd folder1
   cp $i folder2/$i.`date +%m%d%Y`
done

Plot correlation matrix using pandas

If you dataframe is df you can simply use:

import matplotlib.pyplot as plt
import seaborn as sns

plt.figure(figsize=(15, 10))
sns.heatmap(df.corr(), annot=True)

Does a finally block always get executed in Java?

If you don't handle exception, before terminating the program, JVM executes finally block. It will not executed only if normal execution of program will fail mean's termination of program due to these following reasons..

  1. By causing a fatal error that causes the process to abort.

  2. Termination of program due to memory corrupt.

  3. By calling System.exit()

  4. If program goes into infinity loop.

How to SELECT in Oracle using a DBLINK located in a different schema?

I had the same problem I used the solution offered above - I dropped the SYNONYM, created a VIEW with the same name as the synonym. it had a select using the dblink , and gave GRANT SELECT to the other schema It worked great.

Passing std::string by Value or Reference

Check this answer for C++11. Basically, if you pass an lvalue the rvalue reference

From this article:

void f1(String s) {
    vector<String> v;
    v.push_back(std::move(s));
}
void f2(const String &s) {
    vector<String> v;
    v.push_back(s);
}

"For lvalue argument, ‘f1’ has one extra copy to pass the argument because it is by-value, while ‘f2’ has one extra copy to call push_back. So no difference; for rvalue argument, the compiler has to create a temporary ‘String(L“”)’ and pass the temporary to ‘f1’ or ‘f2’ anyway. Because ‘f2’ can take advantage of move ctor when the argument is a temporary (which is an rvalue), the costs to pass the argument are the same now for ‘f1’ and ‘f2’."

Continuing: " This means in C++11 we can get better performance by using pass-by-value approach when:

  1. The parameter type supports move semantics - All standard library components do in C++11
  2. The cost of move constructor is much cheaper than the copy constructor (both the time and stack usage).
  3. Inside the function, the parameter type will be passed to another function or operation which supports both copy and move.
  4. It is common to pass a temporary as the argument - You can organize you code to do this more.

"

OTOH, for C++98 it is best to pass by reference - less data gets copied around. Passing const or non const depend of whether you need to change the argument or not.

How can I pad a value with leading zeros?

Even later to the party.

function zfill(num, len) {
  return(0 > num ? "-" : "") + (Math.pow(10, len) <= Math.abs(num) ? "0" + Math.abs(num) : Math.pow(10, len) + Math.abs(num)).toString().substr(1)
}

This handles negatives and situations where the number is longer than the field width. And floating-point.

Style input type file?

Follow these steps then you can create custom styles for your file upload form:

1.) This is the simple HTML form(please read the HTML comments I have written here bellow)

    <form action="#type your action here" method="POST" enctype="multipart/form-data">
    <div id="yourBtn" style="height: 50px; width: 100px;border: 1px dashed #BBB; cursor:pointer;" onclick="getFile()">Click to upload!</div>
    <!-- this is your file input tag, so i hide it!-->
    <div style='height: 0px;width: 0px; overflow:hidden;'><input id="upfile" type="file" value="upload"/></div>
    <!-- here you can have file submit button or you can write a simple script to upload the file automatically-->
    <input type="submit" value='submit' >
    </form>

2.) Then use this simple script to pass the click event to file input tag.

    function getFile(){
        document.getElementById("upfile").click();
    }

Now you can use any type of a styling without worrying how to change default styles. I know this very well, because I have been trying to change the default styles for month and a half. believe me it's very hard because different browsers have different upload input tag. So use this one to build your custom file upload forms.Here is the full AUTOMATED UPLOAD code.

<html>
<style>
#yourBtn{
   position: relative;
   top: 150px;
   font-family: calibri;
   width: 150px;
   padding: 10px;
   -webkit-border-radius: 5px;
   -moz-border-radius: 5px;
   border: 1px dashed #BBB; 
   text-align: center;
   background-color: #DDD;
   cursor:pointer;
  }
</style>
<script type="text/javascript">
 function getFile(){
   document.getElementById("upfile").click();
 }
 function sub(obj){
    var file = obj.value;
    var fileName = file.split("\\");
    document.getElementById("yourBtn").innerHTML = fileName[fileName.length-1];
    document.myForm.submit();
    event.preventDefault();
  }
</script>
<body>
<center>
<form action="#type your action here" method="POST" enctype="multipart/form-data" name="myForm">
<div id="yourBtn" onclick="getFile()">click to upload a file</div>
<!-- this is your file input tag, so i hide it!-->
<!-- i used the onchange event to fire the form submission-->
<div style='height: 0px; width: 0px;overflow:hidden;'><input id="upfile" type="file" value="upload" onchange="sub(this)"/></div>
<!-- here you can have file submit button or you can write a simple script to upload the file automatically-->
<!-- <input type="submit" value='submit' > -->
</form>
</center>
</body>
</html>

PHP DateTime __construct() Failed to parse time string (xxxxxxxx) at position x

This worked for me.

   /**
     * return date in specific format, given a timestamp.
     *
     * @param  timestamp  $datetime
     * @return string
     */
    public static function showDateString($timestamp)
    {
      if ($timestamp !== NULL) {
        $date = new DateTime();
        $date->setTimestamp(intval($timestamp));
        return $date->format("d-m-Y");
      }
      return '';
    }

"register" keyword in C?

Register keyword tells compiler to store the particular variable in CPU registers so that it could be accessible fast. From a programmer's point of view register keyword is used for the variables which are heavily used in a program, so that compiler can speedup the code. Although it depends on the compiler whether to keep the variable in CPU registers or main memory.

Can you create nested WITH clauses for Common Table Expressions?

we can create nested cte.please see the below cte in example

;with cte_data as 
(
Select * from [HumanResources].[Department]
),cte_data1 as
(
Select * from [HumanResources].[Department]
)

select * from cte_data,cte_data1

Best way to change the background color for an NSView

edit/update: Xcode 8.3.1 • Swift 3.1

extension NSView {
    var backgroundColor: NSColor? {
        get {
            guard let color = layer?.backgroundColor else { return nil }
            return NSColor(cgColor: color)
        }
        set {
            wantsLayer = true
            layer?.backgroundColor = newValue?.cgColor
        }
    }
}

usage:

let myView = NSView(frame: NSRect(x: 0, y: 0, width: 100, height: 100))
print(myView.backgroundColor ?? "none")     //  NSView's background hasn't been set yet = nil
myView.backgroundColor = .red               // set NSView's background color to red color
print(myView.backgroundColor ?? "none")
view.addSubview(myView)

Python: find position of element in array

For your first question, find the position of some value in a list x using index(), like so:

x.index(value)

For your second question, to check for multiple same values you should split your list into chunks and use the same logic from above. They say divide and conquer. It works. Try this:

value = 1 
x = [1,2,3,4,5,6,2,1,4,5,6]

chunk_a = x[:int(len(x)/2)] # get the first half of x 
chunk_b = x[int(len(x)/2):] # get the rest half of x

print(chunk_a.index(value))
print(chunk_b.index(value))

Hope that helps!

How does the data-toggle attribute work? (What's its API?)

I think you are a bit confused on the purpose of custom data attributes. From the w3 spec

Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.

By itself an attribute of data-toggle=value is basically a key-value pair, in which the key is "data-toggle" and the value is "value".

In the context of Bootstrap, the custom data in the attribute is almost useless without the context that their JavaScript library includes for the data. If you look at the non-minified version of bootstrap.js then you can do a search for "data-toggle" and find how it is being used.

Here is an example of Bootstrap JavaScript code that I copied straight from the file regarding the use of "data-toggle".

  • Button Toggle

    Button.prototype.toggle = function () {
      var changed = true
      var $parent = this.$element.closest('[data-toggle="buttons"]')
    
      if ($parent.length) {
        var $input = this.$element.find('input')
        if ($input.prop('type') == 'radio') {
          if ($input.prop('checked') && this.$element.hasClass('active')) changed = false
          else $parent.find('.active').removeClass('active')
        }
        if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
      } else {
        this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
      }
    
      if (changed) this.$element.toggleClass('active')
    }
    

The context that the code provides shows that Bootstrap is using the data-toggle attribute as a custom query selector to process the particular element.

From what I see these are the data-toggle options:

  • collapse
  • dropdown
  • modal
  • tab
  • pill
  • button(s)

You may want to look at the Bootstrap JavaScript documentation to get more specifics of what each do, but basically the data-toggle attribute toggles the element to active or not.

Understanding the Linux oom-killer's logs

Memory management in Linux is a bit tricky to understand, and I can't say I fully understand it yet, but I'll try to share a little bit of my experience and knowledge.

Short answer to your question: Yes there are other stuff included than whats in the list.

What's being shown in your list is applications run in userspace. The kernel uses memory for itself and modules, on top of that it also has a lower limit of free memory that you can't go under. When you've reached that level it will try to free up resources, and when it can't do that anymore, you end up with an OOM problem.

From the last line of your list you can read that the kernel reports a total-vm usage of: 1498536kB (1,5GB), where the total-vm includes both your physical RAM and swap space. You stated you don't have any swap but the kernel seems to think otherwise since your swap space is reported to be full (Total swap = 524284kB, Free swap = 0kB) and it reports a total vmem size of 1,5GB.

Another thing that can complicate things further is memory fragmentation. You can hit the OOM killer when the kernel tries to allocate lets say 4096kB of continous memory, but there are no free ones availible.

Now that alone probably won't help you solve the actual problem. I don't know if it's normal for your program to require that amount of memory, but I would recommend to try a static code analyzer like cppcheck to check for memory leaks or file descriptor leaks. You could also try to run it through Valgrind to get a bit more information out about memory usage.

Converting a string to an integer on Android

Use regular expression is best way to doing this as already mentioned by ashish sahu

public int getInt(String s){
return Integer.parseInt(s.replaceAll("[\\D]", ""));
}

Find length of 2D array Python

You can also use np.size(a,1), 1 here is the axis and this will give you the number of columns

Redefining the Index in a Pandas DataFrame object

Why don't you simply use set_index method?

In : col = ['a','b','c']

In : data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)

In : data
Out:
    a   b   c
0   1   2   3
1  10  11  12
2  20  21  22

In : data2 = data.set_index('a')

In : data2
Out:
     b   c
a
1    2   3
10  11  12
20  21  22

Specifying trust store information in spring boot application.properties

If you execute your Spring Boot application as a linux service (e.g. init.d script or similar), then you have the following option as well: Create a file called yourApplication.conf and put it next to your executable war/jar file. It's content should be something similar:

JAVA_OPTS="
-Djavax.net.ssl.trustStore=path-to-your-trustStore-file
-Djavax.net.ssl.trustStorePassword=yourCrazyPassword
"

How to use default Android drawables

Java Usage example: myMenuItem.setIcon(android.R.drawable.ic_menu_save);

Resource Usage example: android:icon="@android:drawable/ic_menu_save"

Make the current Git branch a master branch

To add to Jefromi's answer, if you don't want to place a meaningless merge in the history of the source branch, you can create a temporary branch for the ours merge, then throw it away:

git checkout <source>
git checkout -b temp            # temporary branch for merge
git merge -s ours <target>      # create merge commit with contents of <source>
git checkout <target>           # fast forward <target> to merge commit
git merge temp                  # ...
git branch -d temp              # throw temporary branch away

That way the merge commit will only exist in the history of the target branch.

Alternatively, if you don't want to create a merge at all, you can simply grab the contents of source and use them for a new commit on target:

git checkout <source>                          # fill index with contents of <source>
git symbolic-ref HEAD <target>                 # tell git we're committing on <target>
git commit -m "Setting contents to <source>"   # make an ordinary commit with the contents of <source>

How to measure time elapsed on Javascript?

The Date documentation states that :

The JavaScript date is based on a time value that is milliseconds since midnight January 1, 1970, UTC

Click on start button then on end button. It will show you the number of seconds between the 2 clicks.

The milliseconds diff is in variable timeDiff. Play with it to find seconds/minutes/hours/ or what you need

_x000D_
_x000D_
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
  startTime = new Date();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
  endTime = new Date();_x000D_
  var timeDiff = endTime - startTime; //in ms_x000D_
  // strip the ms_x000D_
  timeDiff /= 1000;_x000D_
_x000D_
  // get seconds _x000D_
  var seconds = Math.round(timeDiff);_x000D_
  console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
_x000D_
<button onclick="end()">End</button>
_x000D_
_x000D_
_x000D_

OR another way of doing it for modern browser

Using performance.now() which returns a value representing the time elapsed since the time origin. This value is a double with microseconds in the fractional.

The time origin is a standard time which is considered to be the beginning of the current document's lifetime.

_x000D_
_x000D_
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
  startTime = performance.now();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
  endTime = performance.now();_x000D_
  var timeDiff = endTime - startTime; //in ms _x000D_
  // strip the ms _x000D_
  timeDiff /= 1000; _x000D_
  _x000D_
  // get seconds _x000D_
  var seconds = Math.round(timeDiff);_x000D_
  console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
<button onclick="end()">End</button>
_x000D_
_x000D_
_x000D_

How to change the sender's name or e-mail address in mutt?

Normally, mutt sets the From: header based on the from configuration variable you set in ~/.muttrc:

set from="Fubar <foo@bar>"

If this is not set, mutt uses the EMAIL environment variable by default. In which case, you can get away with calling mutt like this on the command line (as opposed to how you showed it in your comment):

EMAIL="foo@bar" mutt -s '$MailSubject' -c "abc@def"

However, if you want to be able to edit the From: header while composing, you need to configure mutt to allow you to edit headers first. This involves adding the following line in your ~/.muttrc:

set edit_headers=yes

After that, next time you open up mutt and are composing an E-mail, your chosen text editor will pop up containing the headers as well, so you can edit them. This includes the From: header.

Best practice for REST token-based authentication with JAX-RS and Jersey

This answer is all about authorization and it is a complement of my previous answer about authentication

Why another answer? I attempted to expand my previous answer by adding details on how to support JSR-250 annotations. However the original answer became the way too long and exceeded the maximum length of 30,000 characters. So I moved the whole authorization details to this answer, keeping the other answer focused on performing authentication and issuing tokens.


Supporting role-based authorization with the @Secured annotation

Besides authentication flow shown in the other answer, role-based authorization can be supported in the REST endpoints.

Create an enumeration and define the roles according to your needs:

public enum Role {
    ROLE_1,
    ROLE_2,
    ROLE_3
}

Change the @Secured name binding annotation created before to support roles:

@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Secured {
    Role[] value() default {};
}

And then annotate the resource classes and methods with @Secured to perform the authorization. The method annotations will override the class annotations:

@Path("/example")
@Secured({Role.ROLE_1})
public class ExampleResource {

    @GET
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response myMethod(@PathParam("id") Long id) {
        // This method is not annotated with @Secured
        // But it's declared within a class annotated with @Secured({Role.ROLE_1})
        // So it only can be executed by the users who have the ROLE_1 role
        ...
    }

    @DELETE
    @Path("{id}")    
    @Produces(MediaType.APPLICATION_JSON)
    @Secured({Role.ROLE_1, Role.ROLE_2})
    public Response myOtherMethod(@PathParam("id") Long id) {
        // This method is annotated with @Secured({Role.ROLE_1, Role.ROLE_2})
        // The method annotation overrides the class annotation
        // So it only can be executed by the users who have the ROLE_1 or ROLE_2 roles
        ...
    }
}

Create a filter with the AUTHORIZATION priority, which is executed after the AUTHENTICATION priority filter defined previously.

The ResourceInfo can be used to get the resource Method and resource Class that will handle the request and then extract the @Secured annotations from them:

@Secured
@Provider
@Priority(Priorities.AUTHORIZATION)
public class AuthorizationFilter implements ContainerRequestFilter {

    @Context
    private ResourceInfo resourceInfo;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        // Get the resource class which matches with the requested URL
        // Extract the roles declared by it
        Class<?> resourceClass = resourceInfo.getResourceClass();
        List<Role> classRoles = extractRoles(resourceClass);

        // Get the resource method which matches with the requested URL
        // Extract the roles declared by it
        Method resourceMethod = resourceInfo.getResourceMethod();
        List<Role> methodRoles = extractRoles(resourceMethod);

        try {

            // Check if the user is allowed to execute the method
            // The method annotations override the class annotations
            if (methodRoles.isEmpty()) {
                checkPermissions(classRoles);
            } else {
                checkPermissions(methodRoles);
            }

        } catch (Exception e) {
            requestContext.abortWith(
                Response.status(Response.Status.FORBIDDEN).build());
        }
    }

    // Extract the roles from the annotated element
    private List<Role> extractRoles(AnnotatedElement annotatedElement) {
        if (annotatedElement == null) {
            return new ArrayList<Role>();
        } else {
            Secured secured = annotatedElement.getAnnotation(Secured.class);
            if (secured == null) {
                return new ArrayList<Role>();
            } else {
                Role[] allowedRoles = secured.value();
                return Arrays.asList(allowedRoles);
            }
        }
    }

    private void checkPermissions(List<Role> allowedRoles) throws Exception {
        // Check if the user contains one of the allowed roles
        // Throw an Exception if the user has not permission to execute the method
    }
}

If the user has no permission to execute the operation, the request is aborted with a 403 (Forbidden).

To know the user who is performing the request, see my previous answer. You can get it from the SecurityContext (which should be already set in the ContainerRequestContext) or inject it using CDI, depending on the approach you go for.

If a @Secured annotation has no roles declared, you can assume all authenticated users can access that endpoint, disregarding the roles the users have.

Supporting role-based authorization with JSR-250 annotations

Alternatively to defining the roles in the @Secured annotation as shown above, you could consider JSR-250 annotations such as @RolesAllowed, @PermitAll and @DenyAll.

JAX-RS doesn't support such annotations out-of-the-box, but it could be achieved with a filter. Here are a few considerations to keep in mind if you want to support all of them:

So an authorization filter that checks JSR-250 annotations could be like:

@Provider
@Priority(Priorities.AUTHORIZATION)
public class AuthorizationFilter implements ContainerRequestFilter {

    @Context
    private ResourceInfo resourceInfo;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        Method method = resourceInfo.getResourceMethod();

        // @DenyAll on the method takes precedence over @RolesAllowed and @PermitAll
        if (method.isAnnotationPresent(DenyAll.class)) {
            refuseRequest();
        }

        // @RolesAllowed on the method takes precedence over @PermitAll
        RolesAllowed rolesAllowed = method.getAnnotation(RolesAllowed.class);
        if (rolesAllowed != null) {
            performAuthorization(rolesAllowed.value(), requestContext);
            return;
        }

        // @PermitAll on the method takes precedence over @RolesAllowed on the class
        if (method.isAnnotationPresent(PermitAll.class)) {
            // Do nothing
            return;
        }

        // @DenyAll can't be attached to classes

        // @RolesAllowed on the class takes precedence over @PermitAll on the class
        rolesAllowed = 
            resourceInfo.getResourceClass().getAnnotation(RolesAllowed.class);
        if (rolesAllowed != null) {
            performAuthorization(rolesAllowed.value(), requestContext);
        }

        // @PermitAll on the class
        if (resourceInfo.getResourceClass().isAnnotationPresent(PermitAll.class)) {
            // Do nothing
            return;
        }

        // Authentication is required for non-annotated methods
        if (!isAuthenticated(requestContext)) {
            refuseRequest();
        }
    }

    /**
     * Perform authorization based on roles.
     *
     * @param rolesAllowed
     * @param requestContext
     */
    private void performAuthorization(String[] rolesAllowed, 
                                      ContainerRequestContext requestContext) {

        if (rolesAllowed.length > 0 && !isAuthenticated(requestContext)) {
            refuseRequest();
        }

        for (final String role : rolesAllowed) {
            if (requestContext.getSecurityContext().isUserInRole(role)) {
                return;
            }
        }

        refuseRequest();
    }

    /**
     * Check if the user is authenticated.
     *
     * @param requestContext
     * @return
     */
    private boolean isAuthenticated(final ContainerRequestContext requestContext) {
        // Return true if the user is authenticated or false otherwise
        // An implementation could be like:
        // return requestContext.getSecurityContext().getUserPrincipal() != null;
    }

    /**
     * Refuse the request.
     */
    private void refuseRequest() {
        throw new AccessDeniedException(
            "You don't have permissions to perform this action.");
    }
}

Note: The above implementation is based on the Jersey RolesAllowedDynamicFeature. If you use Jersey, you don't need to write your own filter, just use the existing implementation.

How to specify preference of library path?

If one is used to work with DLL in Windows and would like to skip .so version numbers in linux/QT, adding CONFIG += plugin will take version numbers out. To use absolute path to .so, giving it to linker works fine, as Mr. Klatchko mentioned.

what does -zxvf mean in tar -zxvf <filename>?

Instead of wading through the description of all the options, you can jump to 3.4.3 Short Options Cross Reference under the info tar command.

x means --extract. v means --verbose. f means --file. z means --gzip. You can combine one-letter arguments together, and f takes an argument, the filename. There is something you have to watch out for:

Short options' letters may be clumped together, but you are not required to do this (as compared to old options; see below). When short options are clumped as a set, use one (single) dash for them all, e.g., ''tar' -cvf'. Only the last option in such a set is allowed to have an argument(1).


This old way of writing 'tar' options can surprise even experienced users. For example, the two commands:

 tar cfz archive.tar.gz file
 tar -cfz archive.tar.gz file

are quite different. The first example uses 'archive.tar.gz' as the value for option 'f' and recognizes the option 'z'. The second example, however, uses 'z' as the value for option 'f' -- probably not what was intended.

iPad browser WIDTH & HEIGHT standard

The pixel width and height of your page will depend on orientation as well as the meta viewport tag, if specified. Here are the results of running jquery's $(window).width() and $(window).height() on iPad 1 browser.

When page has no meta viewport tag:

  • Portrait: 980x1208
  • Landscape: 980x661

When page has either of these two meta tags:

<meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,width=device-width">

<meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1">

  • Portrait: 768x946
  • Landscape: 1024x690

With <meta name="viewport" content="width=device-width">:

  • Portrait: 768x946
  • Landscape: 768x518

With <meta name="viewport" content="height=device-height">:

  • Portrait: 980x1024
  • Landscape: 980x1024

With <meta name="viewport" content="height=device-height,width=device-width">:

  • Portrait: 768x1024
  • Landscape: 768x1024

With <meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,width=device-width,height=device-height">

  • Portrait: 768x1024
  • Landscape: 1024x1024

With <meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,height=device-height">

  • Portrait: 831x1024
  • Landscape: 1520x1024

How to see tomcat is running or not

open http://localhost:8080/ in browser, if you get tomcat home page. it means tomcat is running

Understanding repr( ) function in Python

The feedback you get on the interactive interpreter uses repr too. When you type in an expression (let it be expr), the interpreter basically does result = expr; if result is not None: print repr(result). So the second line in your example is formatting the string foo into the representation you want ('foo'). And then the interpreter creates the representation of that, leaving you with double quotes.

Why when I combine %r with double-quote and single quote escapes and print them out, it prints it the way I'd write it in my .py file but not the way I'd like to see it?

I'm not sure what you're asking here. The text single ' and double " quotes, when run through repr, includes escapes for one kind of quote. Of course it does, otherwise it wouldn't be a valid string literal by Python rules. That's precisely what you asked for by calling repr.

Also note that the eval(repr(x)) == x analogy isn't meant literal. It's an approximation and holds true for most (all?) built-in types, but the main thing is that you get a fairly good idea of the type and logical "value" from looking the the repr output.

Python - Extracting and Saving Video Frames

The previous answers have lost the first frame. And it will be nice to store the images in a folder.

# create a folder to store extracted images
import os
folder = 'test'  
os.mkdir(folder)
# use opencv to do the job
import cv2
print(cv2.__version__)  # my version is 3.1.0
vidcap = cv2.VideoCapture('test_video.mp4')
count = 0
while True:
    success,image = vidcap.read()
    if not success:
        break
    cv2.imwrite(os.path.join(folder,"frame{:d}.jpg".format(count)), image)     # save frame as JPEG file
    count += 1
print("{} images are extacted in {}.".format(count,folder))

By the way, you can check the frame rate by VLC. Go to windows -> media information -> codec details

Mockito match any class argument

Two more ways to do it (see my comment on the previous answer by @Tomasz Nurkiewicz):

The first relies on the fact that the compiler simply won't let you pass in something of the wrong type:

when(a.method(any(Class.class))).thenReturn(b);

You lose the exact typing (the Class<? extends A>) but it probably works as you need it to.

The second is a lot more involved but is arguably a better solution if you really want to be sure that the argument to method() is an A or a subclass of A:

when(a.method(Matchers.argThat(new ClassOrSubclassMatcher<A>(A.class)))).thenReturn(b);

Where ClassOrSubclassMatcher is an org.hamcrest.BaseMatcher defined as:

public class ClassOrSubclassMatcher<T> extends BaseMatcher<Class<T>> {

    private final Class<T> targetClass;

    public ClassOrSubclassMatcher(Class<T> targetClass) {
        this.targetClass = targetClass;
    }

    @SuppressWarnings("unchecked")
    public boolean matches(Object obj) {
        if (obj != null) {
            if (obj instanceof Class) {
                return targetClass.isAssignableFrom((Class<T>) obj);
            }
        }
        return false;
    }

    public void describeTo(Description desc) {
        desc.appendText("Matches a class or subclass");
    }       
}

Phew! I'd go with the first option until you really need to get finer control over what method() actually returns :-)

Generate an HTML Response in a Java Servlet

You normally forward the request to a JSP for display. JSP is a view technology which provides a template to write plain vanilla HTML/CSS/JS in and provides ability to interact with backend Java code/variables with help of taglibs and EL. You can control the page flow with taglibs like JSTL. You can set any backend data as an attribute in any of the request, session or application scope and use EL (the ${} things) in JSP to access/display them. You can put JSP files in /WEB-INF folder to prevent users from directly accessing them without invoking the preprocessing servlet.

Kickoff example:

@WebServlet("/hello")
public class HelloWorldServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String message = "Hello World";
        request.setAttribute("message", message); // This will be available as ${message}
        request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
    }

}

And /WEB-INF/hello.jsp look like:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 2370960</title>
    </head>
    <body>
         <p>Message: ${message}</p>
    </body>
</html>

When opening http://localhost:8080/contextpath/hello this will show

Message: Hello World

in the browser.

This keeps the Java code free from HTML clutter and greatly improves maintainability. To learn and practice more with servlets, continue with below links.

Also browse the "Frequent" tab of all questions tagged [servlets] to find frequently asked questions.

How to get JSON from webpage into Python script

Get data from the URL and then call json.loads e.g.

Python3 example:

import urllib.request, json 
with urllib.request.urlopen("http://maps.googleapis.com/maps/api/geocode/json?address=google") as url:
    data = json.loads(url.read().decode())
    print(data)

Python2 example:

import urllib, json
url = "http://maps.googleapis.com/maps/api/geocode/json?address=google"
response = urllib.urlopen(url)
data = json.loads(response.read())
print data

The output would result in something like this:

{
"results" : [
    {
    "address_components" : [
        {
            "long_name" : "Charleston and Huff",
            "short_name" : "Charleston and Huff",
            "types" : [ "establishment", "point_of_interest" ]
        },
        {
            "long_name" : "Mountain View",
            "short_name" : "Mountain View",
            "types" : [ "locality", "political" ]
        },
        {
...

Can multiple different HTML elements have the same ID if they're different elements?

And for what it's worth, on Chrome 26.0.1410.65, Firefox 19.0.2, and Safari 6.0.3 at least, if you have multiple elements with the same ID, jquery selectors (at least) will return the first element with that ID.

e.g.

<div id="one">first text for one</div>
<div id="one">second text for one</div>

and

alert($('#one').size());

See http://jsfiddle.net/RuysX/ for a test.

Send form data using ajax

$.ajax({
  url: "target.php",
  type: "post",
  data: "fname="+fname+"&lname="+lname,
}).done(function(data) {
  alert(data);
});

Alternative to iFrames with HTML5

This also does seem to work, although W3C specifies it is not intended "for an external (typically non-HTML) application or interactive content"

<embed src="http://www.somesite.com" width=200 height=200 />

More info: http://www.w3.org/wiki/HTML/Elements/embed http://www.w3schools.com/tags/tag_embed.asp

Using parameters in batch files at Windows command line

As others have already said, parameters passed through the command line can be accessed in batch files with the notation %1 to %9. There are also two other tokens that you can use:

  • %0 is the executable (batch file) name as specified in the command line.
  • %* is all parameters specified in the command line -- this is very useful if you want to forward the parameters to another program.

There are also lots of important techniques to be aware of in addition to simply how to access the parameters.

Checking if a parameter was passed

This is done with constructs like IF "%~1"=="", which is true if and only if no arguments were passed at all. Note the tilde character which causes any surrounding quotes to be removed from the value of %1; without a tilde you will get unexpected results if that value includes double quotes, including the possibility of syntax errors.

Handling more than 9 arguments (or just making life easier)

If you need to access more than 9 arguments you have to use the command SHIFT. This command shifts the values of all arguments one place, so that %0 takes the value of %1, %1 takes the value of %2, etc. %9 takes the value of the tenth argument (if one is present), which was not available through any variable before calling SHIFT (enter command SHIFT /? for more options).

SHIFT is also useful when you want to easily process parameters without requiring that they are presented in a specific order. For example, a script may recognize the flags -a and -b in any order. A good way to parse the command line in such cases is

:parse
IF "%~1"=="" GOTO endparse
IF "%~1"=="-a" REM do something
IF "%~1"=="-b" REM do something else
SHIFT
GOTO parse
:endparse
REM ready for action!

This scheme allows you to parse pretty complex command lines without going insane.

Substitution of batch parameters

For parameters that represent file names the shell provides lots of functionality related to working with files that is not accessible in any other way. This functionality is accessed with constructs that begin with %~.

For example, to get the size of the file passed in as an argument use

ECHO %~z1

To get the path of the directory where the batch file was launched from (very useful!) you can use

ECHO %~dp0

You can view the full range of these capabilities by typing CALL /? in the command prompt.

JSON response parsing in Javascript to get key/value pair

var yourobj={
"c":{
    "a":[{"name":"cable - black","value":2},{"name":"case","value":2}]
    },
"o":{
    "v":[{"name":"over the ear headphones - white/purple","value":1}]
},
"l":{
    "e":[{"name":"lens cleaner","value":1}]
},
"h":{
    "d":[{"name":"hdmi cable","value":1},
         {"name":"hdtv essentials (hdtv cable setup)","value":1},
         {"name":"hd dvd \u0026 blue-ray disc lens cleaner","value":1}]
}}
  • first of all it's a good idea to get organized
  • top level reference must be a more convenient name other that a..v... etc
  • in o.v,o.i.e no need for the array [] because it is one json entry

my solution

var obj = [];
for(n1 in yourjson)
    for(n1_1 in yourjson[n])
        for(n1_2 in yourjson[n][n1_1])
            obj[n1_2[name]] = n1_2[value];

Approved code

for(n1 in yourobj){
    for(n1_1 in yourobj[n1]){
    for(n1_2 in yourobj[n1][n1_1]){
            for(n1_3 in yourobj[n1][n1_1][n1_2]){
      obj[yourobj[n1][n1_1][n1_2].name]=yourobj[n1][n1_1][n1_2].value;
            }
    }
 }
}
console.log(obj);

result

*You should use distinguish accessorizes when using [] method or dot notation

proove

What is the largest possible heap size with a 64-bit JVM?

For a 64-bit JVM running in a 64-bit OS on a 64-bit machine, is there any limit besides the theoretical limit of 2^64 bytes or 16 exabytes?

You also have to take hardware limits into account. While pointers may be 64bit current CPUs can only address a less than 2^64 bytes worth of virtual memory.

With uncompressed pointers the hotspot JVM needs a continuous chunk of virtual address space for its heap. So the second hurdle after hardware is the operating system providing such a large chunk, not all OSes support this.

And the third one is practicality. Even if you can have that much virtual memory it does not mean the CPUs support that much physical memory, and without physical memory you will end up swapping, which will adversely affect the performance of the JVM because the GCs generally have to touch a large fraction of the heap.

As other answers mention compressed oops: By bumping the object alignment higher than 8 bytes the limits with compressed oops can be increased beyond 32GB

Android Stop Emulator from Command Line

Sometimes the command

adb -s emulator-5554 emu kill

did not work on my CI servers or desktops, for unknown reason. I think on Windows it's OK to kill the process of qemu, just like

Taskkill /IM qemu-system-x86_64.exe /F /T

'Connect-MsolService' is not recognized as the name of a cmdlet

This issue can occur if the Azure Active Directory Module for Windows PowerShell isn't loaded correctly.

To resolve this issue, follow these steps.
1.Install the Azure Active Directory Module for Windows PowerShell on the computer (if it isn't already installed). To install the Azure Active Directory Module for Windows PowerShell, go to the following Microsoft website:
Manage Azure AD using Windows PowerShell

2.If the MSOnline module isn't present, use Windows PowerShell to import the MSOnline module.

Import-Module MSOnline 

After it complete, we can use this command to check it.

PS C:\Users> Get-Module -ListAvailable -Name MSOnline*


    Directory: C:\windows\system32\WindowsPowerShell\v1.0\Modules


ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   1.1.166.0  MSOnline                            {Get-MsolDevice, Remove-MsolDevice, Enable-MsolDevice, Disable-MsolDevice...}
Manifest   1.1.166.0  MSOnlineExtended                    {Get-MsolDevice, Remove-MsolDevice, Enable-MsolDevice, Disable-MsolDevice...}

More information about this issue, please refer to it.


Update:

We should import azure AD powershell to VS 2015, we can add tool and select Azure AD powershell.

enter image description here

Spring RequestMapping for controllers that produce and consume JSON

There are 2 annotations in Spring: @RequestBody and @ResponseBody. These annotations consumes, respectively produces JSONs. Some more info here.

How do you modify the web.config appSettings at runtime?

2012 This is a better solution for this scenario (tested With Visual Studio 2008):

Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
config.AppSettings.Settings.Remove("MyVariable");
config.AppSettings.Settings.Add("MyVariable", "MyValue");
config.Save();

Update 2018 =>
Tested in vs 2015 - Asp.net MVC5

var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
config.AppSettings.Settings["MyVariable"].Value = "MyValue";
config.Save();

if u need to checking element exist, use this code:

var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
if (config.AppSettings.Settings["MyVariable"] != null)
{
config.AppSettings.Settings["MyVariable"].Value = "MyValue";
}
else { config.AppSettings.Settings.Add("MyVariable", "MyValue"); }
config.Save();

How do I restart nginx only after the configuration test was successful on Ubuntu?

You can reload using /etc/init.d/nginx reload and sudo service nginx reload

If nginx -t throws some error then it won't reload

so use && to run both at a same time

like

nginx -t && /etc/init.d/nginx reload

How to encode a string in JavaScript for displaying in HTML?

You need to escape < and &. Escaping > too doesn't hurt:

function magic(input) {
    input = input.replace(/&/g, '&amp;');
    input = input.replace(/</g, '&lt;');
    input = input.replace(/>/g, '&gt;');
    return input;
}

Or you let the DOM engine do the dirty work for you (using jQuery because I'm lazy):

function magic(input) {
    return $('<span>').text(input).html();
}

What this does is creating a dummy element, assigning your string as its textContent (i.e. no HTML-specific characters have side effects since it's just text) and then you retrieve the HTML content of that element - which is the text but with special characters converted to HTML entities in cases where it's necessary.

how to set the default value to the drop down list control?

if you know the index of the item of default value,just

lstDepartment.SelectedIndex = 1;//the second item

or if you know the value you want to set, just

lstDepartment.SelectedValue = "the value you want to set";

Repeat a task with a time delay?

In my case, I had to execute a process if one of these conditions were true: if a previous process was completed or if 5 seconds had already passed. So, I did the following and worked pretty well:

private Runnable mStatusChecker;
private Handler mHandler;

class {
method() {
  mStatusChecker = new Runnable() {
            int times = 0;
            @Override
            public void run() {
                if (times < 5) {
                    if (process1.isRead()) {
                        executeProcess2();
                    } else {
                        times++;
                        mHandler.postDelayed(mStatusChecker, 1000);
                    }
                } else {
                    executeProcess2();
                }
            }
        };

        mHandler = new Handler();
        startRepeatingTask();
}

    void startRepeatingTask() {
       mStatusChecker.run();
    }

    void stopRepeatingTask() {
        mHandler.removeCallbacks(mStatusChecker);
    }


}

If process1 is read, it executes process2. If not, it increments the variable times, and make the Handler be executed after one second. It maintains a loop until process1 is read or times is 5. When times is 5, it means that 5 seconds passed and in each second, the if clause of process1.isRead() is executed.

Where is the Global.asax.cs file?

That's because you created a Web Site instead of a Web Application. The cs/vb files can only be seen in a Web Application, but in a website you can't have a separate cs/vb file.

Edit: In the website you can add a cs file behavior like..

<%@ Application CodeFile="Global.asax.cs" Inherits="ApplicationName.MyApplication" Language="C#" %>

~/Global.asax.cs:

namespace ApplicationName
{
    public partial class MyApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
        }
    }
}

Transparent background on winforms?

My solution was extremely close to Joel's (Not Etherton, just plain Joel):

public partial class WaitingDialog : Form
{
    public WaitingDialog()
    {
        InitializeComponent();

        SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        this.BackColor = Color.Transparent;
        this.TransparencyKey = Color.Transparent; // I had to add this to get it to work.

        // Other stuff
    }

    protected override void OnPaintBackground(PaintEventArgs e) { /* Ignore */ }
}

Most simple code to populate JTable from ResultSet

Well I'm sure that this is the simplest way to populate JTable from ResultSet, without any external library. I have included comments in this method.

public void resultSetToTableModel(ResultSet rs, JTable table) throws SQLException{
        //Create new table model
        DefaultTableModel tableModel = new DefaultTableModel();

        //Retrieve meta data from ResultSet
        ResultSetMetaData metaData = rs.getMetaData();

        //Get number of columns from meta data
        int columnCount = metaData.getColumnCount();

        //Get all column names from meta data and add columns to table model
        for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++){
            tableModel.addColumn(metaData.getColumnLabel(columnIndex));
        }

        //Create array of Objects with size of column count from meta data
        Object[] row = new Object[columnCount];

        //Scroll through result set
        while (rs.next()){
            //Get object from column with specific index of result set to array of objects
            for (int i = 0; i < columnCount; i++){
                row[i] = rs.getObject(i+1);
            }
            //Now add row to table model with that array of objects as an argument
            tableModel.addRow(row);
        }

        //Now add that table model to your table and you are done :D
        table.setModel(tableModel);
    }

Read a local text file using Javascript

Please find below the code that generates automatically the content of the txt local file and display it html. Good luck!

<html>
<head>
  <meta charset="utf-8">
  <script type="text/javascript">

  var x;
  if(navigator.appName.search('Microsoft')>-1) { x = new ActiveXObject('MSXML2.XMLHTTP'); }
  else { x = new XMLHttpRequest(); }

  function getdata() {
    x.open('get', 'data1.txt', true); 
    x.onreadystatechange= showdata;
    x.send(null);
  }

  function showdata() {
    if(x.readyState==4) {
      var el = document.getElementById('content');
      el.innerHTML = x.responseText;
    }
  }

  </script>
</head>
<body onload="getdata();showdata();">

  <div id="content"></div>

</body>
</html>

Form onSubmit determine which submit button was pressed

All of the answers above are very good but I cleaned it up a little bit.

This solution automatically puts the name of the submit button pressed into the action hidden field. Both the javascript on the page and the server code can check the action hidden field value as needed.

The solution uses jquery to automatically apply to all submit buttons.

<input type="hidden" name="action" id="action" />
<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        //when a submit button is clicked, put its name into the action hidden field
        $(":submit").click(function () { $("#action").val(this.name); });
    });
</script>
<input type="submit" class="bttn" value="<< Back" name="back" />
<input type="submit" class="bttn" value="Finish" name="finish" />
<input type="submit" class="bttn" value="Save" name="save" />
<input type="submit" class="bttn" value="Next >>" name="next" />
<input type="submit" class="bttn" value="Delete" name="delete" />
<input type="button" class="bttn" name="cancel" value="Cancel" onclick="window.close();" />

Then write code like this into your form submit handler.

 if ($("#action").val() == "delete") {
     return confirm("Are you sure you want to delete the selected item?");
 }

INNER JOIN in UPDATE sql for DB2

Try this and then tell me the results:

UPDATE File1 AS B                          
SET    b.campo1 = (SELECT DISTINCT A.campo1
                   FROM  File2 A           
                   INNER JOIN File1      
                   ON A.campo2 = File1.campo2 
                   AND A.campo2 = B.campo2) 

How to use ternary operator in razor (specifically on HTML attributes)?

I have a field named IsActive in table rows that's True when an item has been deleted. This code applies a CSS class named strikethrough only to deleted items. You can see how it uses the C# Ternary Operator:

<tr class="@(@businesstypes.IsActive ? "" : "strikethrough")">

Handling back button in Android Navigation Component

Just add these lines

     override fun onBackPressed() {
            if(navController.popBackStack().not()) {
            //Last fragment: Do your operation here 
            finish()
   } 

navController.popBackStack() will just pop your fragment if this is not your last fragment

CSS Equivalent of the "if" statement

The @supports rule (92% browser support July 2017) rule can be used for conditional logic on css properties:

@supports (display: -webkit-box) {
    .for_older_webkit_browser { display: -webkit-box }
}

@supports not (display: -webkit-box) {
    .newer_browsers { display: flex } 
}

What does "Object reference not set to an instance of an object" mean?

In a nutshell it means.. You are trying to access an object without instantiating it.. You might need to use the "new" keyword to instantiate it first i.e create an instance of it.

For eg:

public class MyClass
{
   public int Id {get; set;}
}

MyClass myClass;

myClass.Id = 0; <----------- An error will be thrown here.. because myClass is null here...

You will have to use:

myClass = new MyClass();
myClass.Id = 0;

Hope I made it clear..

Oracle SQL - select within a select (on the same table!)

Basically, all you have to do is

select ..., (select ... from ... where ...) as ..., ..., from ... where ...

For exemple. You can insert the (select ... from ... where) wherever you want it will be replaced by the corresponding data.

I know that the others exemple (even if each of them are really great :) ) are a bit complicated to understand for the newbies (like me :p) so i hope this "simple" exemple will help some of you guys :)

Convert command line arguments into an array in Bash

Actually the list of parameters could be accessed with $1 $2 ... etc.
Which is exactly equivalent to:

${!i}

So, the list of parameters could be changed with set,
and ${!i} is the correct way to access them:

$ set -- aa bb cc dd 55 ff gg hh ii jjj kkk lll
$ for ((i=0;i<=$#;i++)); do echo "$#" "$i" "${!i}"; done
12 1 aa
12 2 bb
12 3 cc
12 4 dd
12 5 55
12 6 ff
12 7 gg
12 8 hh
12 9 ii
12 10 jjj
12 11 kkk
12 12 lll

For your specific case, this could be used (without the need for arrays), to set the list of arguments when none was given:

if [ "$#" -eq 0 ]; then
    set -- defaultarg1 defaultarg2
fi

which translates to this even simpler expression:

[ "$#" == "0" ] && set -- defaultarg1 defaultarg2

How do I launch a program from command line without opening a new cmd window?

Add /B, as documented in the command-line help for start:

C:\>start /?
Starts a separate window to run a specified program or command.

START ["title"] [/D path] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED]
  [/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL]
  [/NODE <NUMA node>] [/AFFINITY <hex affinity mask>] [/WAIT] [/B]
  [command/program] [parameters]

"title"     Title to display in window title bar.
path        Starting directory.
B           Start application without creating a new window. The
            application has ^C handling ignored. Unless the application
            enables ^C processing, ^Break is the only way to interrupt
            the application.

Service will not start: error 1067: the process terminated unexpectedly

I resolved the problem.This is for EAServer Windows Service

Resolution is --> Open Regedit in Run prompt

Under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\EAServer

In parameters, give SERVERNAME entry as EAServer.

[It is sometime overwritten with Envirnoment variable : Path value]

Android - Get value from HashMap

HashMap<String, String> meMap=new HashMap<String, String>();
meMap.put("Color1","Red");
meMap.put("Color2","Blue");
meMap.put("Color3","Green");
meMap.put("Color4","White");
Iterator iterator = meMap.keySet().iterator();
while( iterator. hasNext() ){
    Toast.makeText(getBaseContext(), meMap.get(iterator.next().toString()), 
    Toast.LENGTH_SHORT).show();
}

Display date/time in user's locale format and time offset

For new projects, just use moment.js

This question is pretty old, so moment.js didn't exist at that time, but for new projects, it simplifies tasks like this a lot.

It's best to parse your date string from UTC as follows (create an ISO-8601 compatible string on the server to get consistent results across all browsers):

var m = moment("2013-02-08T09:30:26Z");

Now just use m in your application, moment.js defaults to the local timezone for display operations. There are many ways to format the date and time values or extract portions of it.

You can even format a moment object in the users locale like this:

m.format('LLL') // Returns "February 8 2013 8:30 AM" on en-us

To transform a moment.js object into a different timezone (i.e. neither the local one nor UTC), you'll need the moment.js timezone extension. That page has also some examples, it's pretty simple to use.

How to terminate a python subprocess launched with shell=True

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
p.kill()

p.kill() ends up killing the shell process and cmd is still running.

I found a convenient fix this by:

p = subprocess.Popen("exec " + cmd, stdout=subprocess.PIPE, shell=True)

This will cause cmd to inherit the shell process, instead of having the shell launch a child process, which does not get killed. p.pid will be the id of your cmd process then.

p.kill() should work.

I don't know what effect this will have on your pipe though.

Body of Http.DELETE request in Angular2

deleteInsurance(insuranceId: any) {
    const insuranceData = {
      id : insuranceId
    }
    var reqHeader = new HttpHeaders({
            "Content-Type": "application/json",
        });
        const httpOptions = {
            headers: reqHeader,
            body: insuranceData,
        };
    return this.http.delete<any>(this.url + "users/insurance", httpOptions);
    }

Python Matplotlib figure title overlaps axes label when using twiny

A temporary solution if you don't want to get into the x, y position of your title.

Following worked for me.

plt.title('Capital Expenditure\n') # Add a next line after your title

kudos.

Could not autowire field in spring. why?

In spring servlet .xml :

<context:component-scan base-package="net.controller" />

(I assumed that the service impl is in the same package as the service interface "net.service")

I think you have to add the package net.service (or all of net) to the component scan. Currently spring only searches in net.controller for components and as your service impl is in net.service, it will not be instantiated by spring.

Converting array to list in Java

One-liner:

List<Integer> list = Arrays.asList(new Integer[] {1, 2, 3, 4});

Creating new table with SELECT INTO in SQL

The syntax for creating a new table is

CREATE TABLE new_table
AS
SELECT *
  FROM old_table

This will create a new table named new_table with whatever columns are in old_table and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.

SELECT INTO is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.

How to allocate aligned memory only using the standard library?

Here's an alternate approach to the 'round up' part. Not the most brilliantly coded solution but it gets the job done, and this type of syntax is a bit easier to remember (plus would work for alignment values that aren't a power of 2). The uintptr_t cast was necessary to appease the compiler; pointer arithmetic isn't very fond of division or multiplication.

void *mem = malloc(1024 + 15);
void *ptr = (void*) ((uintptr_t) mem + 15) / 16 * 16;
memset_16aligned(ptr, 0, 1024);
free(mem);

Change the mouse pointer using JavaScript

Look at this page: http://www.webcodingtech.com/javascript/change-cursor.php. Looks like you can access cursor off of style. This page shows it being done with the entire page, but I'm sure a child element would work just as well.

document.body.style.cursor = 'wait';