Programs & Examples On #Find

This tag has multiple meanings. Please DO NOT use this tag if you're just trying to find something.

Python: Find in list

If you are going to check if value exist in the collectible once then using 'in' operator is fine. However, if you are going to check for more than once then I recommend using bisect module. Keep in mind that using bisect module data must be sorted. So you sort data once and then you can use bisect. Using bisect module on my machine is about 12 times faster than using 'in' operator.

Here is an example of code using Python 3.8 and above syntax:

import bisect
from timeit import timeit

def bisect_search(container, value):
    return (
      (index := bisect.bisect_left(container, value)) < len(container) 
      and container[index] == value
    )

data = list(range(1000))
# value to search
true_value = 666
false_value = 66666

# times to test
ttt = 1000

print(f"{bisect_search(data, true_value)=} {bisect_search(data, false_value)=}")

t1 = timeit(lambda: true_value in data, number=ttt)
t2 = timeit(lambda: bisect_search(data, true_value), number=ttt)

print("Performance:", f"{t1=:.4f}, {t2=:.4f}, diffs {t1/t2=:.2f}")

Output:

bisect_search(data, true_value)=True bisect_search(data, false_value)=False
Performance: t1=0.0220, t2=0.0019, diffs t1/t2=11.71

How to use find command to find all files with extensions from list?

On Mac OS use

find -E packages  -regex ".*\.(jpg|gif|png|jpeg)"

Find files with size in Unix

Find can be used to print out the file-size in bytes with %s as a printf. %h/%f prints the directory prefix and filename respectively. \n forces a newline.

Example

find . -size +10000k -printf "%h/%f,%s\n"

Output

./DOTT/extract/DOTT/TENTACLE.001,11358470
./DOTT/Day Of The Tentacle.nrg,297308316
./DOTT/foo.iso,297001116

How to pipe list of files returned by find command to cat to view all the files

Use ggrep.

ggrep -H -R -I "mysearchstring" *

to search for a file in unix containing text located in the current directory or a subdirectory

How to select where ID in Array Rails ActiveRecord without exception

To avoid exceptions killing your app you should catch those exceptions and treat them the way you wish, defining the behavior for you app on those situations where the id is not found.

begin
  current_user.comments.find(ids)
rescue
  #do something in case of exception found
end

Here's more info on exceptions in ruby.

How can I find WPF controls by name or type?

I combined the template format used by John Myczek and Tri Q's algorithm above to create a findChild Algorithm that can be used on any parent. Keep in mind that recursively searching a tree downwards could be a lengthy process. I've only spot-checked this on a WPF application, please comment on any errors you might find and I'll correct my code.

WPF Snoop is a useful tool in looking at the visual tree - I'd strongly recommend using it while testing or using this algorithm to check your work.

There is a small error in Tri Q's Algorithm. After the child is found, if childrenCount is > 1 and we iterate again we can overwrite the properly found child. Therefore I added a if (foundChild != null) break; into my code to deal with this condition.

/// <summary>
/// Finds a Child of a given item in the visual tree. 
/// </summary>
/// <param name="parent">A direct parent of the queried item.</param>
/// <typeparam name="T">The type of the queried item.</typeparam>
/// <param name="childName">x:Name or Name of child. </param>
/// <returns>The first parent item that matches the submitted type parameter. 
/// If not matching item can be found, 
/// a null parent is being returned.</returns>
public static T FindChild<T>(DependencyObject parent, string childName)
   where T : DependencyObject
{    
  // Confirm parent and childName are valid. 
  if (parent == null) return null;

  T foundChild = null;

  int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
  for (int i = 0; i < childrenCount; i++)
  {
    var child = VisualTreeHelper.GetChild(parent, i);
    // If the child is not of the request child type child
    T childType = child as T;
    if (childType == null)
    {
      // recursively drill down the tree
      foundChild = FindChild<T>(child, childName);

      // If the child is found, break so we do not overwrite the found child. 
      if (foundChild != null) break;
    }
    else if (!string.IsNullOrEmpty(childName))
    {
      var frameworkElement = child as FrameworkElement;
      // If the child's name is set for search
      if (frameworkElement != null && frameworkElement.Name == childName)
      {
        // if the child's name is of the request name
        foundChild = (T)child;
        break;
      }
    }
    else
    {
      // child element found.
      foundChild = (T)child;
      break;
    }
  }

  return foundChild;
}

Call it like this:

TextBox foundTextBox = 
   UIHelper.FindChild<TextBox>(Application.Current.MainWindow, "myTextBoxName");

Note Application.Current.MainWindow can be any parent window.

How do I find files that do not contain a given string pattern?

You will actually need:

find .  -not  -ipath '.*svn*' -exec  grep  -H -E -o -c  "foo"  {} \; | grep :0\$

Finding the indices of matching elements in list in Python

You are using .index() which will only find the first occurrence of your value in the list. So if you have a value 1.0 at index 2, and at index 9, then .index(1.0) will always return 2, no matter how many times 1.0 occurs in the list.

Use enumerate() to add indices to your loop instead:

def find(lst, a, b):
    result = []
    for i, x in enumerate(lst):
        if x<a or x>b:
            result.append(i)
    return result

You can collapse this into a list comprehension:

def find(lst, a, b):
    return [i for i, x in enumerate(lst) if x<a or x>b]

How can I find a specific element in a List<T>?

You can also use LINQ extensions:

string id = "hello";
MyClass result = list.Where(m => m.GetId() == id).First();

How can I search for a multiline pattern in a file?

You can use the grep alternative sift here (disclaimer: I am the author).

It support multiline matching and limiting the search to specific file types out of the box:

sift -m --files '*.py' 'YOUR_PATTERN'

(search all *.py files for the specified multiline regex pattern)

It is available for all major operating systems. Take a look at the samples page to see how it can be used to to extract multiline values from an XML file.

Does a "Find in project..." feature exist in Eclipse IDE?

yes, but you need to open the global search panel. to do so, press the binoculars icon on the top right corner of the IDE.

you can even filter searches by function identifiers, method scopes an etc...

  • Choose File Search for plain text search in workspace/selected projects
  • For specific expression searches, choose the relevant tab (such as Java Search which allows to search for specific identifiers)

Getting Index of an item in an arraylist;

for (int i = 0; i < list.length; i++) {
   if (list.get(i) .getName().equalsIgnoreCase("myName")) {
    System.out.println(i);
    break;
  }
}

Batch / Find And Edit Lines in TXT file

This is the kind of stuff sed was made for (of course, you need sed on your system for that).

sed 's/ex3/ex5/g' input.txt > output.txt

You will either need a Unix system or a Windows Cygwin kind of platform for this.
There is also GnuWin32 for sed. (GnuWin32 installation and usage).

Find files in created between a date range

You can use the below to find what you need.

Find files older than a specific date/time:

find ~/ -mtime $(echo $(date +%s) - $(date +%s -d"Dec 31, 2009 23:59:59") | bc -l | awk '{print $1 / 86400}' | bc -l)

Or you can find files between two dates. First date more recent, last date, older. You can go down to the second, and you don't have to use mtime. You can use whatever you need.

find . -mtime $(date +%s -d"Aug 10, 2013 23:59:59") -mtime $(date +%s -d"Aug 1, 2013 23:59:59")

How to only get file name with Linux 'find'?

Honestly basename and dirname solutions are easier, but you can also check this out :

find . -type f | grep -oP "[^/]*$"

or

find . -type f | rev | cut -d '/' -f1 | rev

or

find . -type f | sed "s/.*\///"

Using find to locate files that match one of multiple patterns

You could programmatically add more -name clauses, separated by -or:

find Documents \( -name "*.py" -or -name "*.html" \)

Or, go for a simple loop instead:

for F in Documents/*.{py,html}; do ...something with each '$F'... ; done

How can I find all *.js file in directory recursively in Linux?

find /abs/path/ -name '*.js'

Edit: As Brian points out, add -type f if you want only plain files, and not directories, links, etc.

Get all files modified in last 30 days in a directory

A couple of issues

  • You're not limiting it to files, so when it finds a matching directory it will list every file within it.
  • You can't use > in -exec without something like bash -c '... > ...'. Though the > will overwrite the file, so you want to redirect the entire find anyway rather than each -exec.
  • +30 is older than 30 days, -30 would be modified in last 30 days.
  • -exec really isn't needed, you could list everything with various -printf options.

Something like below should work

find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt

Example with -printf

find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt

This will list files in format "permissions owner group time date filename". -printf is generally preferable to -exec in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec. Depending on the version of find, you may also be able to use -ls, which has a similar format to above.

Find files and tar them (with spaces)

Use this:

find . -type f -print0 | tar -czvf backup.tar.gz --null -T -

It will:

  • deal with files with spaces, newlines, leading dashes, and other funniness
  • handle an unlimited number of files
  • won't repeatedly overwrite your backup.tar.gz like using tar -c with xargs will do when you have a large number of files

Also see:

Fast way of finding lines in one file that are not in another?

You can use Python:

python -c '
lines_to_remove = set()
with open("file2", "r") as f:
    for line in f.readlines():
        lines_to_remove.add(line.strip())

with open("f1", "r") as f:
    for line in f.readlines():
        if line.strip() not in lines_to_remove:
            print(line.strip())
'

Linux find and grep command together

You are looking for -H option in gnu grep.

find . -name '*bills*' -exec grep -H "put" {} \;

Here is the explanation

    -H, --with-filename
      Print the filename for each match.

PowerShell Script to Find and Replace for all Files with a Specific Extension

Here a first attempt at the top of my head.

$configFiles = Get-ChildItem . *.config -rec
foreach ($file in $configFiles)
{
    (Get-Content $file.PSPath) |
    Foreach-Object { $_ -replace "Dev", "Demo" } |
    Set-Content $file.PSPath
}

C# - using List<T>.Find() with custom objects

Previous answers don't account for the fact that you've overloaded the equals operator and are using that to test for the sought element. In that case, your code would look like this:

list.Find(x => x == objectToFind);

Or, if you don't like lambda syntax, and have overriden object.Equals(object) or have implemented IEquatable<T>, you could do this:

list.Find(objectToFind.Equals);

linux find regex

Regular expressions with character classes (e.g. [[:digit:]]) are not supported in the default regular expression syntax used by find. You need to specify a different regex type such as posix-extended in order to use them.

Take a look at GNU Find's Regular Expression documentation which shows you all the regex types and what they support.

Mongoose.js: Find user by username LIKE value

router.route('/product/name/:name')
.get(function(req, res) {

    var regex = new RegExp(req.params.name, "i")
    ,   query = { description: regex };

    Product.find(query, function(err, products) {
        if (err) {
            res.json(err);
        }

        res.json(products);
    });

});  

find: missing argument to -exec

For anyone else having issues when using GNU find binary in a Windows command prompt. The semicolon needs to be escaped with ^

find.exe . -name "*.rm" -exec ffmpeg -i {} -sameq {}.mp3 ^;

How do I find what Java version Tomcat6 is using?

Or you could use the Probe application and just look at its System Info page. Much easier than writing code, and once you start using it you'll never go back to Tomcat Manager.

Find all elements on a page whose element ID contains a certain text using jQuery

This selects all DIVs with an ID containing 'foo' and that are visible

$("div:visible[id*='foo']");

Find all files with a filename beginning with a specified string?

ls | grep "^abc"  

will give you all files beginning (which is what the OP specifically required) with the substringabc.
It operates only on the current directory whereas find operates recursively into sub folders.

To use find for only files starting with your string try

find . -name 'abc'*

Find all stored procedures that reference a specific column in some table

You can use the below query to identify the values. But please keep in mind that this will not give you the results from encrypted stored procedure.

SELECT DISTINCT OBJECT_NAME(comments.id) OBJECT_NAME
    ,objects.type_desc
FROM syscomments comments
    ,sys.objects objects
WHERE comments.id = objects.object_id
    AND TEXT LIKE '%CreatedDate%'
ORDER BY 1

jQuery select by attribute using AND and OR operators

How about writing a filter like below,

$('[myc="blue"]').filter(function () {
   return (this.id == '1' || this.id == '3');
});

Edit: @Jack Thanks.. totally missed it..

$('[myc="blue"]').filter(function() {
   var myId = $(this).attr('myid');   
   return (myId == '1' || myId == '3');
});

DEMO

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

  1. Arange your word list with delimiter which never occures in the words, f.e. |
  2. swap arguments in find call - we want search if cell value is matching one of the words in pattern string {=FIND("cell I want to search","list of words I want to search for")}
  3. if the patterns are similar, there is a risk of getting more results than wanted, we restrict just correct results via adding &"|" to the cell value tested (works well with array formulas) cell G3 could contain: {=SUM(FIND($A$1:$A$100&"|";A3))} this ensures spreadsheet will compare strings like "cellvlaue|" againts "pattern1|", "pattern2|" etc. which sorts out conflicts like pattern1="newly added", pattern2="added" (sum of all cells matching "added" would be too high, including the target values for cells matching "newly added", which would be a logical error)

How to exclude a directory in find . command

The -path -prune approach also works with wildcards in the path. Here is a find statement that will find the directories for a git server serving multiple git repositiories leaving out the git internal directories:

find . -type d \
   -not \( -path */objects -prune \) \
   -not \( -path */branches -prune \) \
   -not \( -path */refs -prune \) \
   -not \( -path */logs -prune \) \
   -not \( -path */.git -prune \) \
   -not \( -path */info -prune \) \
   -not \( -path */hooks -prune \)  

Use bash to find first folder name that contains a string

for example:

dir1=$(find . -name \*foo\* -type d -maxdepth 1 -print | head -n1)
echo "$dir1"

or (For the better shell solution see Adrian Frühwirth's answer)

for dir1 in *
do
    [[ -d "$dir1" && "$dir1" =~ foo ]] && break
    dir1=        #fix based on comment
done
echo "$dir1"

or

dir1=$(find . -type d -maxdepth 1 -print | grep 'foo' | head -n1)
echo "$dir1"

Edited head -n1 based on @ hek2mgl comment

Next based on @chepner's comments

dir1=$(find . -type d -maxdepth 1 -print | grep -m1 'foo')

or

dir1=$(find . -name \*foo\* -type d -maxdepth 1 -print -quit)

How to loop through file names returned by find?

What ever you do, don't use a for loop:

# Don't do this
for file in $(find . -name "*.txt")
do
    …code using "$file"
done

Three reasons:

  • For the for loop to even start, the find must run to completion.
  • If a file name has any whitespace (including space, tab or newline) in it, it will be treated as two separate names.
  • Although now unlikely, you can overrun your command line buffer. Imagine if your command line buffer holds 32KB, and your for loop returns 40KB of text. That last 8KB will be dropped right off your for loop and you'll never know it.

Always use a while read construct:

find . -name "*.txt" -print0 | while read -d $'\0' file
do
    …code using "$file"
done

The loop will execute while the find command is executing. Plus, this command will work even if a file name is returned with whitespace in it. And, you won't overflow your command line buffer.

The -print0 will use the NULL as a file separator instead of a newline and the -d $'\0' will use NULL as the separator while reading.

JQuery Find #ID, RemoveClass and AddClass

corrected Code:

jQuery('#testID2').addClass('test3').removeClass('test2');

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

data = "abcdefg hi j 12345"

digits_count = 0
letters_count = 0
others_count = 0

for i in userinput:

    if i.isdigit():
        digits_count += 1 
    elif i.isalpha():
        letters_count += 1
    else:
        others_count += 1

print("Result:")        
print("Letters=", letters_count)
print("Digits=", digits_count)

Output:

Please Enter Letters with Numbers:
abcdefg hi j 12345
Result:
Letters = 10
Digits = 5

By using str.isalpha() you can check if it is a letter.

jQuery Find and List all LI elements within a UL within a specific DIV

$('li[rel=7]').siblings().andSelf();

// or:

$('li[rel=7]').parent().children();

Now that you added that comment explaining that you want to "form an array of rels per column", you should do this:

var rels = [];

$('ul').each(function() {
    var localRels = [];

    $(this).find('li').each(function(){
        localRels.push( $(this).attr('rel') );
    });

    rels.push(localRels);
});

Best way to handle list.index(might-not-exist) in python?

What about this :

li = [1,2,3,4,5] # create list 

li = dict(zip(li,range(len(li)))) # convert List To Dict 
print( li ) # {1: 0, 2: 1, 3: 2, 4:3 , 5: 4}
li.get(20) # None 
li.get(1)  # 0 

find index of an int in a list

List<string> accountList = new List<string> {"123872", "987653" , "7625019", "028401"};

int i = accountList.FindIndex(x => x.StartsWith("762"));
//This will give you index of 7625019 in list that is 2. value of i will become 2.
//delegate(string ac)
//{
//    return ac.StartsWith(a.AccountNumber);
//}
//);

ls command: how can I get a recursive full-path listing, one line per file?

du -a

Handy for some limited appliance shells where find/locate aren't available.

Delete files older than 10 days using shell script in Unix

Just spicing up the shell script above to delete older files but with logging and calculation of elapsed time

#!/bin/bash

path="/data/backuplog/"
timestamp=$(date +%Y%m%d_%H%M%S)    
filename=log_$timestamp.txt    
log=$path$filename
days=7

START_TIME=$(date +%s)

find $path -maxdepth 1 -name "*.txt"  -type f -mtime +$days  -print -delete >> $log

echo "Backup:: Script Start -- $(date +%Y%m%d_%H%M)" >> $log


... code for backup ...or any other operation .... >> $log


END_TIME=$(date +%s)

ELAPSED_TIME=$(( $END_TIME - $START_TIME ))


echo "Backup :: Script End -- $(date +%Y%m%d_%H%M)" >> $log
echo "Elapsed Time ::  $(date -d 00:00:$ELAPSED_TIME +%Hh:%Mm:%Ss) "  >> $log

The code adds a few things.

  • log files named with a timestamp
  • log folder specified
  • find looks for *.txt files only in the log folder
  • type f ensures you only deletes files
  • maxdepth 1 ensures you dont enter subfolders
  • log files older than 7 days are deleted ( assuming this is for a backup log)
  • notes the start / end time
  • calculates the elapsed time for the backup operation...

Note: to test the code, just use -print instead of -print -delete. But do check your path carefully though.

Note: Do ensure your server time is set correctly via date - setup timezone/ntp correctly . Additionally check file times with 'stat filename'

Note: mtime can be replaced with mmin for better control as mtime discards all fractions (older than 2 days (+2 days) actually means 3 days ) when it deals with getting the timestamps of files in the context of days

-mtime +$days  --->  -mmin  +$((60*24*$days))

find filenames NOT ending in specific extensions on Unix?

one more :-)

$ ls -ltr
total 10
-rw-r--r--    1 scripter     linuxdumb         47 Dec 23 14:46 test1
-rw-r--r--    1 scripter     linuxdumb          0 Jan  4 23:40 test4
-rw-r--r--    1 scripter     linuxdumb          0 Jan  4 23:40 test3
-rw-r--r--    1 scripter     linuxdumb          0 Jan  4 23:40 test2
-rw-r--r--    1 scripter     linuxdumb          0 Jan  4 23:41 file5
-rw-r--r--    1 scripter     linuxdumb          0 Jan  4 23:41 file4
-rw-r--r--    1 scripter     linuxdumb          0 Jan  4 23:41 file3
-rw-r--r--    1 scripter     linuxdumb          0 Jan  4 23:41 file2
-rw-r--r--    1 scripter     linuxdumb          0 Jan  4 23:41 file1
$ find . -type f ! -name "*1" ! -name "*2" -print
./test3
./test4
./file3
./file4
./file5
$

Unix find command reference

How do I find all of the symlinks in a directory tree?

One command, no pipes

find . -type l -ls

Explanation: find from the current directory . onwards all references of -type link and list -ls those in detail. Plain and simple...

Expanding upon this answer, here are a couple more symbolic link related find commands:

Find symbolic links to a specific target

find . -lname link_target

Note that link_target is a pattern that may contain wildcard characters.

Find broken symbolic links

find -L . -type l -ls

The -L option instructs find to follow symbolic links, unless when broken.

Find & replace broken symbolic links

find -L . -type l -delete -exec ln -s new_target {} \;

More find examples

More find examples can be found here: https://hamwaves.com/find/

How to find the files that are created in the last hour in unix

If the dir to search is srch_dir then either

$ find srch_dir -cmin -60 # change time

or

$ find srch_dir -mmin -60 # modification time

or

$ find srch_dir -amin -60 # access time

shows files created, modified or accessed in the last hour.

correction :ctime is for change node time (unsure though, please correct me )

How do I get the find command to print out the file size with the file name?

You could try this:

find. -name *.ear -exec du {} \;

This will give you the size in bytes. But the du command also accepts the parameters -k for KB and -m for MB. It will give you an output like

5000  ./dir1/dir2/earFile1.ear
5400  ./dir1/dir2/earFile2.ear
5400  ./dir1/dir3/earFile1.ear

Check if one list contains element from the other

Loius answer is correct, I just want to add an example:

listOne.add("A");
listOne.add("B");
listOne.add("C");

listTwo.add("D");
listTwo.add("E");
listTwo.add("F");      

boolean noElementsInCommon = Collections.disjoint(listOne, listTwo); // true

How to recursively find the latest modified file in a directory?

This simple cli will also work:

ls -1t | head -1

You may change the -1 to the number of files you want to list

How to use '-prune' option of 'find' in sh?

Beware that -prune does not prevent descending into any directory as some have said. It prevents descending into directories that match the test it's applied to. Perhaps some examples will help (see the bottom for a regex example). Sorry for this being so lengthy.

$ find . -printf "%y %p\n"    # print the file type the first time FYI
d .
f ./test
d ./dir1
d ./dir1/test
f ./dir1/test/file
f ./dir1/test/test
d ./dir1/scripts
f ./dir1/scripts/myscript.pl
f ./dir1/scripts/myscript.sh
f ./dir1/scripts/myscript.py
d ./dir2
d ./dir2/test
f ./dir2/test/file
f ./dir2/test/myscript.pl
f ./dir2/test/myscript.sh

$ find . -name test
./test
./dir1/test
./dir1/test/test
./dir2/test

$ find . -prune
.

$ find . -name test -prune
./test
./dir1/test
./dir2/test

$ find . -name test -prune -o -print
.
./dir1
./dir1/scripts
./dir1/scripts/myscript.pl
./dir1/scripts/myscript.sh
./dir1/scripts/myscript.py
./dir2

$ find . -regex ".*/my.*p.$"
./dir1/scripts/myscript.pl
./dir1/scripts/myscript.py
./dir2/test/myscript.pl

$ find . -name test -prune -regex ".*/my.*p.$"
(no results)

$ find . -name test -prune -o -regex ".*/my.*p.$"
./test
./dir1/test
./dir1/scripts/myscript.pl
./dir1/scripts/myscript.py
./dir2/test

$ find . -regex ".*/my.*p.$" -a -not -regex ".*test.*"
./dir1/scripts/myscript.pl
./dir1/scripts/myscript.py

$ find . -not -regex ".*test.*"                   .
./dir1
./dir1/scripts
./dir1/scripts/myscript.pl
./dir1/scripts/myscript.sh
./dir1/scripts/myscript.py
./dir2

Find and replace words/lines in a file

This is the sort of thing I'd normally use a scripting language for. It's very useful to have the ability to perform these sorts of transformations very simply using something like Ruby/Perl/Python (insert your favorite scripting language here).

I wouldn't normally use Java for this since it's too heavyweight in terms of development cycle/typing etc.

Note that if you want to be particular in manipulating XML, it's advisable to read the file as XML and manipulate it as such (the above scripting languages have very useful and simple APIs for doing this sort of work). A simple text search/replace can invalidate your file in terms of character encoding etc. As always, it depends on the complexity of your search/replace requirements.

How do I list all the files in a directory and subdirectories in reverse chronological order?

ls -lR is to display all files, directories and sub directories of the current directory ls -lR | more is used to show all the files in a flow.

How to get span tag inside a div in jQuery and assign a text?

function Errormessage(txt) {
    $("#message").fadeIn("slow");
    $("#message span:first").text(txt);
    // find the span inside the div and assign a text
    $("#message a.close-notify").click(function() {
        $("#message").fadeOut("slow");
    });
}

Scala check if element is present in a list

Even easier!

strings contains myString

How do I find the current directory of a batch file, and then use it for the path?

ElektroStudios answer is a bit misleading.

"when you launch a bat file the working dir is the dir where it was launched" This is true if the user clicks on the batch file in the explorer.

However, if the script is called from another script using the CALL command, the current working directory does not change.

Thus, inside your script, it is better to use %~dp0subfolder\file1.txt

Please also note that %~dp0 will end with a backslash when the current script is not in the current working directory. Thus, if you need the directory name without a trailing backslash, you could use something like

call :GET_THIS_DIR
echo I am here: %THIS_DIR%
goto :EOF

:GET_THIS_DIR
pushd %~dp0
set THIS_DIR=%CD%
popd
goto :EOF

find files by extension, *.html under a folder in nodejs

You can use Filehound to do this.

For example: find all .html files in /tmp:

const Filehound = require('filehound');

Filehound.create()
  .ext('html')
  .paths("/tmp")
  .find((err, htmlFiles) => {
    if (err) return console.error("handle err", err);

    console.log(htmlFiles);
});

For further information (and examples), check out the docs: https://github.com/nspragg/filehound

Disclaimer: I'm the author.

FileNotFoundError: [Errno 2] No such file or directory

You are using a relative path, which means that the program looks for the file in the working directory. The error is telling you that there is no file of that name in the working directory.

Try using the exact, or absolute, path.

Find text in string with C#

I have different approach on ReplaceTextBetween() function.

public static string ReplaceTextBetween(this string strSource, string strStart, string strEnd, string strReplace)
        {
            if (strSource.Contains(strStart) && strSource.Contains(strEnd))
            {
                var startIndex = strSource.IndexOf(strStart, 0) + strStart.Length;

                var endIndex = strSource.IndexOf(strEnd, startIndex);

                var strSourceLength = strSource.Length;

                var strToReplace = strSource.Substring(startIndex, endIndex - startIndex);

                var concatStart = startIndex + strToReplace.Length;

                var beforeReplaceStr = strSource.Substring(0, startIndex);

                var afterReplaceStr = strSource.Substring(concatStart, strSourceLength - endIndex);

                return string.Concat(beforeReplaceStr, strReplace, afterReplaceStr);
            }

            return strSource;
        }

How to check if a value exists in a dictionary (python)

Use dictionary views:

if x in d.viewvalues():
    dosomething()..

Find methods calls in Eclipse project

select method > right click > References > Workspace/Project (your preferred context ) 

or

(Ctrl+Shift+G) 

This will show you a Search view containing the hierarchy of class and method which using this method.

Chmod recursively

Adding executable permissions, recursively, to all files (not folders) within the current folder with sh extension:

find . -name '*.sh' -type f | xargs chmod +x

* Notice the pipe (|)

Find and copy files

You need to use cp -t /home/shantanu/tosend in order to tell it that the argument is the target directory and not a source. You can then change it to -exec ... + in order to get cp to copy as many files as possible at once.

find . -type f -exec chmod 644 {} ;

I need this so often that I created a function in my ~/.bashrc file:

chmodf() {
        find $2 -type f -exec chmod $1 {} \;
}
chmodd() {
        find $2 -type d -exec chmod $1 {} \;
}

Now I can use these shortcuts:

chmodd 0775 .
chmodf 0664 .

Return Index of an Element in an Array Excel VBA

The only (& even though cumbersome but yet expedient / relatively quick) way I can do this, is to concatenate the any-dimensional array, and reduce it to 1 dimension, with "/[column number]//\|" as the delimiter.

& use a single-cell result multiple lookupall macro function on the this 1-d column.

& then index match to pull out the positions. (usuing multiple find match)

That way you get all matching occurrences of the element/string your looking for, in the original any-dimension array, and their positions. In one cell.

Wish I could write a macro / function for this entire process. It would save me more fuss.

How to use 'find' to search for files created on a specific date?

As pointed out by Max, you can't, but checking files modified or accessed is not all that hard. I wrote a tutorial about this, as late as today. The essence of which is to use -newerXY and ! -newerXY:

Example: To find all files modified on the 7th of June, 2007:

$ find . -type f -newermt 2007-06-07 ! -newermt 2007-06-08

To find all files accessed on the 29th of september, 2008:

$ find . -type f -newerat 2008-09-29 ! -newerat 2008-09-30

Or, files which had their permission changed on the same day:

$ find . -type f -newerct 2008-09-29 ! -newerct 2008-09-30

If you don't change permissions on the file, 'c' would normally correspond to the creation date, though.

Find duplicate lines in a file and count how many time each line was duplicated?

In windows using "Windows PowerShell" I used the command mentioned below to achieve this

Get-Content .\file.txt | Group-Object | Select Name, Count

Also we can use the where-object Cmdlet to filter the result

Get-Content .\file.txt | Group-Object | Where-Object { $_.Count -gt 1 } | Select Name, Count

find -exec with multiple commands

There's an easier way:

find ... | while read -r file; do
    echo "look at my $file, my $file is amazing";
done

Alternatively:

while read -r file; do
    echo "look at my $file, my $file is amazing";
done <<< "$(find ...)"

Linux find file names with given string recursively

A correct answer has already been supplied, but for you to learn how to help yourself I thought I'd throw in something helpful in a different way; if you can sum up what you're trying to achieve in one word, there's a mighty fine help feature on Linux.

man -k <your search term>

What that does is to list all commands that have your search term in the short description. There's usually a pretty good chance that you will find what you're after. ;)

That output can sometimes be somewhat overwhelming, and I'd recommend narrowing it down to the executables, rather than all available man-pages, like so:

man -k find | egrep '\(1\)'

or, if you also want to look for commands that require higher privilege levels, like this:

man -k find | egrep '\([18]\)'

MongoDB Show all contents from all collections

This will do:

db.getCollectionNames().forEach(c => {
    db[c].find().forEach(d => {
        print(c); 
        printjson(d)
    })
})

Find a file by name in Visual Studio Code

Press Ctl+T will open a search box. Delete # symbol and enter your file name.

Use find command but exclude files in two directories

Try something like

find . \( -type f -name \*_peaks.bed -print \) -or \( -type d -and \( -name tmp -or -name scripts \) -and -prune \)

and don't be too surprised if I got it a bit wrong. If the goal is an exec (instead of print), just substitute it in place.

How to find the largest file in a directory and its subdirectories?

This will find the largest file or folder in your present working directory:

ls -S /path/to/folder | head -1

To find the largest file in all sub-directories:

find /path/to/folder -type f -exec ls -s {} \; | sort -nr | awk 'NR==1 { $1=""; sub(/^ /, ""); print }'

jQuery .find() on data from .ajax() call is returning "[object Object]" instead of div

The jQuery find() is returning a jQuery object that wraps the DOM object. You should be able to work with that object to do what you'd like with the div.

Explaining the 'find -mtime' command

The POSIX specification for find says:

-mtimen The primary shall evaluate as true if the file modification time subtracted from the initialization time, divided by 86400 (with any remainder discarded), is n.

Interestingly, the description of find does not further specify 'initialization time'. It is probably, though, the time when find is initialized (run).

In the descriptions, wherever n is used as a primary argument, it shall be interpreted as a decimal integer optionally preceded by a plus ( '+' ) or minus-sign ( '-' ) sign, as follows:

+n More than n.
  n Exactly n.
-n Less than n.

At the given time (2014-09-01 00:53:44 -4:00, where I'm deducing that AST is Atlantic Standard Time, and therefore the time zone offset from UTC is -4:00 in ISO 8601 but +4:00 in ISO 9945 (POSIX), but it doesn't matter all that much):

1409547224 = 2014-09-01 00:53:44 -04:00
1409457540 = 2014-08-30 23:59:00 -04:00

so:

1409547224 - 1409457540 = 89684
89684 / 86400 = 1

Even if the 'seconds since the epoch' values are wrong, the relative values are correct (for some time zone somewhere in the world, they are correct).

The n value calculated for the 2014-08-30 log file therefore is exactly 1 (the calculation is done with integer arithmetic), and the +1 rejects it because it is strictly a > 1 comparison (and not >= 1).

Make xargs handle filenames that contain spaces

On macOS 10.12.x (Sierra), if you have spaces in file names or subdirectories, you can use the following:

find . -name '*.swift' -exec echo '"{}"' \; |xargs wc -l

Using find command in bash script

Welcome to bash. It's an old, dark and mysterious thing, capable of great magic. :-)

The option you're asking about is for the find command though, not for bash. From your command line, you can man find to see the options.

The one you're looking for is -o for "or":

  list="$(find /home/user/Desktop -name '*.bmp' -o -name '*.txt')"

That said ... Don't do this. Storage like this may work for simple filenames, but as soon as you have to deal with special characters, like spaces and newlines, all bets are off. See ParsingLs for details.

$ touch 'one.txt' 'two three.txt' 'foo.bmp'
$ list="$(find . -name \*.txt -o -name \*.bmp -type f)"
$ for file in $list; do if [ ! -f "$file" ]; then echo "MISSING: $file"; fi; done
MISSING: ./two
MISSING: three.txt

Pathname expansion (globbing) provides a much better/safer way to keep track of files. Then you can also use bash arrays:

$ a=( *.txt *.bmp )
$ declare -p a
declare -a a=([0]="one.txt" [1]="two three.txt" [2]="foo.bmp")
$ for file in "${a[@]}"; do ls -l "$file"; done
-rw-r--r--  1 ghoti  staff  0 24 May 16:27 one.txt
-rw-r--r--  1 ghoti  staff  0 24 May 16:27 two three.txt
-rw-r--r--  1 ghoti  staff  0 24 May 16:27 foo.bmp

The Bash FAQ has lots of other excellent tips about programming in bash.

How can I exclude all "permission denied" messages from "find"?

To avoid just the permission denied warnings, tell find to ignore the unreadable files by pruning them from the search. Add an expression as an OR to your find, such as

find / \! -readable -prune -o -name '*.jbd' -ls

This mostly says to (match an unreadable file and prune it from the list) OR (match a name like *.jbd and display it [with ls]). (Remember that by default the expressions are AND'd together unless you use -or.) You need the -ls in the second expression or else find may add a default action to show either match, which will also show you all the unreadable files.

But if you're looking for real files on your system, there is usually no reason to look in /dev, which has many many files, so you should add an expression that excludes that directory, like:

find / -mount \! -readable -prune  -o  -path /dev -prune  -o  -name '*.jbd' -ls

So (match unreadable file and prune from list) OR (match path /dev and prune from list) OR (match file like *.jbd and display it).

Find files containing a given text

find them and grep for the string:

This will find all files of your 3 types in /starting/path and grep for the regular expression '(document\.cookie|setcookie)'. Split over 2 lines with the backslash just for readability...

find /starting/path -type f -name "*.php" -o -name "*.html" -o -name "*.js" | \
 xargs egrep -i '(document\.cookie|setcookie)'

Why does find -exec mv {} ./target/ + not work?

The standard equivalent of find -iname ... -exec mv -t dest {} + for find implementations that don't support -iname or mv implementations that don't support -t is to use a shell to re-order the arguments:

find . -name '*.[cC][pP][pP]' -type f -exec sh -c '
  exec mv "$@" /dest/dir/' sh {} +

By using -name '*.[cC][pP][pP]', we also avoid the reliance on the current locale to decide what's the uppercase version of c or p.

Note that +, contrary to ; is not special in any shell so doesn't need to be quoted (though quoting won't harm, except of course with shells like rc that don't support \ as a quoting operator).

The trailing / in /dest/dir/ is so that mv fails with an error instead of renaming foo.cpp to /dest/dir in the case where only one cpp file was found and /dest/dir didn't exist or wasn't a directory (or symlink to directory).

grep without showing path/file:line

No need to find. If you are just looking for a pattern within a specific directory, this should suffice:

grep -hn FOO /your/path/*.bar

Where -h is the parameter to hide the filename, as from man grep:

-h, --no-filename

Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search.

Note that you were using

-H, --with-filename

Print the file name for each match. This is the default when there is more than one file to search.

Find the files that have been changed in last 24 hours

Another, more humane way:

find /<directory> -newermt "-24 hours" -ls

or:

find /<directory> -newermt "1 day ago" -ls

or:

find /<directory> -newermt "yesterday" -ls

jQuery: find element by text

The following jQuery selects div nodes that contain text but have no children, which are the leaf nodes of the DOM tree.

_x000D_
_x000D_
$('div:contains("test"):not(:has(*))').css('background-color', 'red');
_x000D_
<div>div1_x000D_
<div>This is a test, nested in div1</div>_x000D_
<div>Nested in div1<div>_x000D_
</div>_x000D_
<div>div2 test_x000D_
<div>This is another test, nested in div2</div>_x000D_
<div>Nested in div2</div>_x000D_
</div>_x000D_
<div>_x000D_
div3_x000D_
</div>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Search for executable files using find command

So as to have another possibility1 to find the files that are executable by the current user:

find . -type f -exec test -x {} \; -print

(the test command here is the one found in PATH, very likely /usr/bin/test, not the builtin).


1 Only use this if the -executable flag of find is not available! this is subtly different from the -perm +111 solution.

Linux command: How to 'find' only text files?

Here's how I've done it ...

1 . make a small script to test if a file is plain text istext:

#!/bin/bash
[[ "$(file -bi $1)" == *"file"* ]]

2 . use find as before

find . -type f -exec istext {} \; -exec grep -nHi mystring {} \;

How can I find a file/directory that could be anywhere on linux command line?

The find command will take long time, the fastest way to search for file is using locate command, which looks for file names (and path) in a indexed database (updated by command updatedb).

The result will appear immediately with a simple command:

locate {file-name-or-path}

If the command is not found, you need to install mlocate package and run updatedb command first to prepare the search database for the first time.

More detail here: https://medium.com/@thucnc/the-fastest-way-to-find-files-by-filename-mlocate-locate-commands-55bf40b297ab

Examples for string find in Python

if x is a string and you search for y which also a string their is two cases : case 1: y is exist in x so x.find(y) = the index (the position) of the y in x . case 2: y is not exist so x.find (y) = -1 this mean y is not found in x.

find without recursion

I think you'll get what you want with the -maxdepth 1 option, based on your current command structure. If not, you can try looking at the man page for find.

Relevant entry (for convenience's sake):

-maxdepth levels
          Descend at most levels (a non-negative integer) levels of direc-
          tories below the command line arguments.   `-maxdepth  0'  means
          only  apply the tests and actions to the command line arguments.

Your options basically are:

# Do NOT show hidden files (beginning with ".", i.e., .*):
find DirsRoot/* -maxdepth 0 -type f

Or:

#  DO show hidden files:
find DirsRoot/ -maxdepth 1 -type f

Find all CSV files in a directory using Python

By using the combination of filters and lambda, you can easily filter out csv files in given folder.

import os

files = os.listdir("/path-to-dir")    
files = list(filter(lambda f: f.endswith('.csv'), files))

# lambda returns True if filename name ends with .csv or else False
# and filter function uses the returned boolean value to filter .csv files from list files.

How to find elements with 'value=x'?

$('#attached_docs [value="123"]').find ... .remove();

it should do your need however, you cannot duplicate id! remember it

How do I find all files containing specific text on Linux?

Try:

find . -name "*.txt" | xargs grep -i "text_pattern"

Ruby Array find_first object?

Either I don't understand your question, or Enumerable#find is the thing you were looking for.

How to go to each directory and execute a command?

If you're using GNU find, you can try -execdir parameter, e.g.:

find . -type d -execdir realpath "{}" ';'

or (as per @gniourf_gniourf comment):

find . -type d -execdir sh -c 'printf "%s/%s\n" "$PWD" "$0"' {} \;

Note: You can use ${0#./} instead of $0 to fix ./ in the front.

or more practical example:

find . -name .git -type d -execdir git pull -v ';'

If you want to include the current directory, it's even simpler by using -exec:

find . -type d -exec sh -c 'cd -P -- "{}" && pwd -P' \;

or using xargs:

find . -type d -print0 | xargs -0 -L1 sh -c 'cd "$0" && pwd && echo Do stuff'

Or similar example suggested by @gniourf_gniourf:

find . -type d -print0 | while IFS= read -r -d '' file; do
# ...
done

The above examples support directories with spaces in their name.


Or by assigning into bash array:

dirs=($(find . -type d))
for dir in "${dirs[@]}"; do
  cd "$dir"
  echo $PWD
done

Change . to your specific folder name. If you don't need to run recursively, you can use: dirs=(*) instead. The above example doesn't support directories with spaces in the name.

So as @gniourf_gniourf suggested, the only proper way to put the output of find in an array without using an explicit loop will be available in Bash 4.4 with:

mapfile -t -d '' dirs < <(find . -type d -print0)

Or not a recommended way (which involves parsing of ls):

ls -d */ | awk '{print $NF}' | xargs -n1 sh -c 'cd $0 && pwd && echo Do stuff'

The above example would ignore the current dir (as requested by OP), but it'll break on names with the spaces.

See also:

How to find file accessed/created just few minutes ago

Simply specify whether you want the time to be greater, smaller, or equal to the time you want, using, respectively:

find . -cmin +<time>
find . -cmin -<time>
find . -cmin  <time>

In your case, for example, the files with last edition in a maximum of 5 minutes, are given by:

find . -cmin -5

How to move or copy files listed by 'find' command in unix?

If you're using GNU find,

find . -mtime 1 -exec cp -t ~/test/ {} +

This works as well as piping the output into xargs while avoiding the pitfalls of doing so (it handles embedded spaces and newlines without having to use find ... -print0 | xargs -0 ...).

How to find and replace all occurrences of a string recursively in a directory tree?

For me works the next command:

find /path/to/dir -name "file.txt" | xargs sed -i 's/string_to_replace/new_string/g'

if string contains slash 'path/to/dir' it can be replace with another character to separate, like '@' instead '/'.

For example: 's@string/to/replace@new/string@g'

How to use regex with find command?

The -regex find expression matches the whole name, including the relative path from the current directory. For find . this always starts with ./, then any directories.

Also, these are emacs regular expressions, which have other escaping rules than the usual egrep regular expressions.

If these are all directly in the current directory, then

find . -regex '\./[a-f0-9\-]\{36\}\.jpg'

should work. (I'm not really sure - I can't get the counted repetition to work here.) You can switch to egrep expressions by -regextype posix-egrep:

find . -regextype posix-egrep -regex '\./[a-f0-9\-]{36}\.jpg'

(Note that everything said here is for GNU find, I don't know anything about the BSD one which is also the default on Mac.)

How to remove first 10 characters from a string?

You can use the method Substring method that takes a single parameter, which is the index to start from.

In my code below i deal with the case were the length is less than your desired start index and when the length is zero.

string s = "hello world!";
s = s.Substring(Math.Max(0, Math.Min(10, s.Length - 1)));

C# "as" cast vs classic cast

The as operator is useful in a couple of circumstances.

  1. When you only need to know an object is of a specific type but don't need to specifically act on members of that type
  2. When you'd like to avoid exceptions and instead explicitly deal with null
  3. You want to know if there is a CLR conversion between the objects and not just some user defined conversion.

The 3rd point is subtle but important. There is not a 1-1 mapping between which casts will succeed with the cast operator and those which will succeed with the as operator. The as operator is strictly limited to CLR conversions and will not consider user defined conversions (the cast operator will).

Specifically the as operator only allows for the following (from section 7.9.11 of the C# lang spec)

  • An identity (§6.1.1), implicit reference (§6.1.6), boxing (§6.1.7), explicit reference (§6.2.4), or unboxing (§6.2.5) conversion exists from the type of E to T.
  • The type of E or T is an open type.
  • E is the null literal.

downcast and upcast

  1. That is correct. When you do that you are casting it it into an employee object, so that means you cannot access anything manager specific.

  2. Downcasting is where you take a base class and then try and turn it into a more specific class. This can be accomplished with using is and an explicit cast like this:

    if (employee is Manager)
    {
        Manager m = (Manager)employee;
        //do something with it
    }
    

or with the as operator like this:

Manager m = (employee as Manager);
if (m != null)
{
    //do something with it
}

If anything is unclear I'll be happy to correct it!

Return multiple values from a function, sub or type?

A function returns one value, but it can "output" any number of values. A sample code:

Function Test (ByVal Input1 As Integer, ByVal Input2 As Integer, _
ByRef Output1 As Integer, ByRef Output2 As Integer) As Integer

  Output1 = Input1 + Input2
  Output2 = Input1 - Input2
  Test = Output1 + Output2

End Function

Sub Test2()

  Dim Ret As Integer, Input1 As Integer, Input2 As Integer, _
  Output1 As integer, Output2 As Integer
  Input1 = 1
  Input2 = 2
  Ret = Test(Input1, Input2, Output1, Output2)
  Sheet1.Range("A1") = Ret     ' 2
  Sheet1.Range("A2") = Output1 ' 3
  Sheet1.Range("A3") = Output2 '-1

End Sub

Find IP address of directly connected device

Mmh ... there are many ways. I answer another network discovery question, and I write a little getting started.

Some tcpip stacks reply to icmp broadcasts. So you can try a PING to your network broadcast address.

For example, you have ip 192.168.1.1 and subnet 255.255.255.0

  1. ping 192.168.1.255
  2. stop the ping after 5 seconds
  3. watch the devices replies : arp -a

Note : on step 3. you get the lists of the MAC-to-IP cached entries, so there are also the hosts in your subnet you exchange data to in the last minutes, even if they don't reply to icmp_get.

Note (2) : now I am on linux. I am not sure, but it can be windows doesn't reply to icm_get via broadcast.

Is it the only one device attached to your pc ? Is it a router or another simple pc ?

deny directory listing with htaccess

Options -Indexes should work to prevent directory listings.

If you are using a .htaccess file make sure you have at least the "allowoverride options" setting in your main apache config file.

NHibernate.MappingException: No persister for: XYZ

Sounds like you forgot to add a mapping assembly to the session factory configuration..

If you're using app.config...

.
.
    <property name="show_sql">true</property>
    <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
    <mapping assembly="Project.DomainModel"/>  <!-- Here -->
</session-factory>
.
.

How to upgrade pip3?

To upgrade your pip3, try running:

sudo -H pip3 install --upgrade pip3

To upgrade pip as well, you can follow it by:

sudo -H pip2 install --upgrade pip

grep's at sign caught as whitespace

No -P needed; -E is sufficient:

grep -E '(^|\s)abc(\s|$)' 

or even without -E:

grep '\(^\|\s\)abc\(\s\|$\)' 

Convert UTF-8 with BOM to UTF-8 with no BOM in Python

In Python 3 it's quite easy: read the file and rewrite it with utf-8 encoding:

s = open(bom_file, mode='r', encoding='utf-8-sig').read()
open(bom_file, mode='w', encoding='utf-8').write(s)

How to dump a table to console?

Format as JSON (you can "beautify" in IDE later):

local function format_any_value(obj, buffer)
    local _type = type(obj)
    if _type == "table" then
        buffer[#buffer + 1] = '{"'
        for key, value in next, obj, nil do
            buffer[#buffer + 1] = tostring(key) .. '":'
            format_any_value(value, buffer)
            buffer[#buffer + 1] = ',"'
        end
        buffer[#buffer] = '}' -- note the overwrite
    elseif _type == "string" then
        buffer[#buffer + 1] = '"' .. obj .. '"'
    elseif _type == "boolean" or _type == "number" then
        buffer[#buffer + 1] = tostring(obj)
    else
        buffer[#buffer + 1] = '"???' .. _type .. '???"'
    end
end

Usage:

local function format_as_json(obj)
    if obj == nil then return "null" else
        local buffer = {}
        format_any_value(obj, buffer)
        return table.concat(buffer)
    end
end

local function print_as_json(obj)
    print(_format_as_json(obj))
end

print_as_json {1, 2, 3}
print_as_json(nil)
print_as_json("string")
print_as_json {[1] = 1, [2] = 2, three = { { true } }, four = "four"}

BTW, I also wrote several other solutions: a very fast one, and one with special characters escaping: https://github.com/vn971/fast_json_encode

How to call getResources() from a class which has no context?

A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. It is an "interface" that allows access to application specific resources and class and information about application environment. Your activities and services also extend Context to they inherit all those methods to access the environment information in which the application is running.

This means you must have to pass context to the specific class if you want to get/modify some specific information about the resources. You can pass context in the constructor like

public classname(Context context, String s1) 
{
...
}

Find length of 2D array Python

Like this:

numrows = len(input)    # 3 rows in your example
numcols = len(input[0]) # 2 columns in your example

Assuming that all the sublists have the same length (that is, it's not a jagged array).

Output Django queryset as JSON

For a efficient solution, you can use .values() function to get a list of dict objects and then dump it to json response by using i.e. JsonResponse (remember to set safe=False).

Once you have your desired queryset object, transform it to JSON response like this:

...
data = list(queryset.values())
return JsonResponse(data, safe=False)

You can specify field names in .values() function in order to return only wanted fields (the example above will return all model fields in json objects).

Changing Node.js listening port

you can get the nodejs configuration from http://nodejs.org/
The important thing you need to keep in your mind is about its configuration in file app.js which consists of port number host and other settings these are settings working for me

backendSettings = {
"scheme":"https / http ",
"host":"Your website url",
"port":49165, //port number 
'sslKeyPath': 'Path for key',
'sslCertPath': 'path for SSL certificate',
'sslCAPath': '',
"resource":"/socket.io",
"baseAuthPath": '/nodejs/',
"publishUrl":"publish",
"serviceKey":"",
"backend":{
"port":443,
"scheme": 'https / http', //whatever is your website scheme
"host":"host name",
"messagePath":"/nodejs/message/"},
"clientsCanWriteToChannels":false,
"clientsCanWriteToClients":false,
"extensions":"",
"debug":false,
"addUserToChannelUrl": 'user/channel/add/:channel/:uid',
"publishMessageToContentChannelUrl": 'content/token/message',
"transports":["websocket",
"flashsocket",
"htmlfile",
"xhr-polling",
"jsonp-polling"],
"jsMinification":true,
"jsEtag":true,
"logLevel":1};

In this if you are getting "Error: listen EADDRINUSE" then please change the port number i.e, here I am using "49165" so you can use other port such as 49170 or some other port. For this you can refer to the following article
http://www.a2hosting.com/kb/installable-applications/manual-installations/installing-node-js-on-shared-hosting-accounts

Nesting queries in SQL

You need to join the two tables and then filter the result in where clause:

SELECT country.name as country, country.headofstate 
from country
inner join city on city.id = country.capital
where city.population > 100000
and country.headofstate like 'A%'

How should I do integer division in Perl?

Integer division $x divided by $y ...

$z = -1 & $x / $y

How does it work?

$x / $y

return the floating point division

&

perform a bit-wise AND

-1

stands for

&HFFFFFFFF

for the largest integer ... whence

$z = -1 & $x / $y

gives the integer division ...

Convert String to Calendar Object in Java

No new Calendar needs to be created, SimpleDateFormat already uses a Calendar underneath.

SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.EN_US);
Date date = sdf.parse("Mon Mar 14 16:02:37 GMT 2011"));// all done
Calendar cal = sdf.getCalendar();

(I can't comment yet, that's why I created a new answer)

In Bootstrap 3,How to change the distance between rows in vertical?

If it was me I would introduce new CSS class and use along with unmodified bootstrap row class.

HTML

<div class="row extra-bottom-padding" id="a">
   <img>...</img>
<div>
<div class="row" id="b">
   <button>..</button>
<div>

CSS

.row.extra-bottom-padding{
   margin-bottom: 20px;
}

What is the function __construct used for?

I Hope this Help:

<?php
    // The code below creates the class
    class Person {
        // Creating some properties (variables tied to an object)
        public $isAlive = true;
        public $firstname;
        public $lastname;
        public $age;

        // Assigning the values
        public function __construct($firstname, $lastname, $age) {
          $this->firstname = $firstname;
          $this->lastname = $lastname;
          $this->age = $age;
        }

        // Creating a method (function tied to an object)
        public function greet() {
          return "Hello, my name is " . $this->firstname . " " . $this->lastname . ". Nice to meet you! :-)";
        }
      }

    // Creating a new person called "boring 12345", who is 12345 years old ;-)
    $me = new Person('boring', '12345', 12345);

    // Printing out, what the greet method returns
    echo $me->greet(); 
    ?>

For More Information You need to Go to codecademy.com

WPF What is the correct way of using SVG files as icons in WPF

Windows 10 build 15063 "Creators Update" natively supports SVG images (though with some gotchas) to UWP/UAP applications targeting Windows 10.

If your application is a WPF app rather than a UWP/UAP, you can still use this API (after jumping through quite a number of hoops): Windows 10 build 17763 "October 2018 Update" introduced the concept of XAML islands (as a "preview" technology but I believe allowed in the app store; in all cases, with Windows 10 build 18362 "May 2019 Update" XAML islands are no longer a preview feature and are fully supported) allowing you to use UWP APIs and controls in your WPF applications.

You need to first add the references to the WinRT APIs, and to use certain Windows 10 APIs that interact with user data or the system (e.g. loading images from disk in a Windows 10 UWP webview or using the toast notification API to show toasts), you also need to associate your WPF application with a package identity, as shown here (immensely easier in Visual Studio 2019). This shouldn't be necessary to use the Windows.UI.Xaml.Media.Imaging.SvgImageSource class, though.

Usage (if you're on UWP or you've followed the directions above and added XAML island support under WPF) is as simple as setting the Source for an <Image /> to the path to the SVG. That is equivalent to using SvgImageSource, as follows:

<Image>
    <Image.Source>
        <SvgImageSource UriSource="Assets/svg/icon.svg" />
    </Image.Source>
</Image>

However, SVG images loaded in this way (via XAML) may load jagged/aliased. One workaround is to specify a RasterizePixelHeight or RasterizePixelWidth value that is double+ your actual height/width:

<SvgImageSource RasterizePixelHeight="300" RasterizePixelWidth="300" UriSource="Assets/svg/icon.svg" /> <!-- presuming actual height or width is under 150 -->

This can be worked around dynamically by creating a new SvgImageSource in the ImageOpened event for the base image:

var svgSource = new SvgImageSource(new Uri("ms-appx://" + Icon));
PrayerIcon.ImageOpened += (s, e) =>
{
    var newSource = new SvgImageSource(svgSource.UriSource);
    newSource.RasterizePixelHeight = PrayerIcon.DesiredSize.Height * 2;
    newSource.RasterizePixelWidth = PrayerIcon.DesiredSize.Width * 2;
    PrayerIcon2.Source = newSource;
};
PrayerIcon.Source = svgSource;

The aliasing may be hard to see on non high-dpi screens, but here's an attempt to illustrate it.

This is the result of the code above: an Image that uses the initial SvgImageSource, and a second Image below it that uses the SvgImageSource created in the ImageOpened event:

enter image description here

This is a blown up view of the top image:

enter image description here

Whereas this is a blown-up view of the bottom (antialiased, correct) image:

enter image description here

(you'll need to open the images in a new tab and view at full size to appreciate the difference)

How to fetch Java version using single line command in Linux

Since (at least on my linux system) the version string looks like "1.8.0_45":

 #!/bin/bash
 function checkJavaVers {
    for token in $(java -version 2>&1)
    do
        if [[ $token =~ \"([[:digit:]])\.([[:digit:]])\.(.*)\" ]]
        then
            export JAVA_MAJOR=${BASH_REMATCH[1]}
            export JAVA_MINOR=${BASH_REMATCH[2]}
            export JAVA_BUILD=${BASH_REMATCH[3]}
            return 0
        fi
    done
    return 1
}

#test
checkJavaVers || { echo "check failed" ; exit; }
echo "$JAVA_MAJOR $JAVA_MINOR $JAVA_BUILD"
~

Add a UIView above all, even the navigation bar

Note if you want add view in Full screen then only use below code

Add these extension of UIViewController

public extension UIViewController {
   internal func makeViewAsFullScreen() {
      var viewFrame:CGRect = self.view.frame
      if viewFrame.origin.y > 0 || viewFrame.origin.x > 0 {
        self.view.frame = UIScreen.main.bounds
      }
   }
}

Continue as normal adding process of subview

Now use in adding UIViewController's viewDidAppear

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

     self.makeViewAsFullScreen()
}

UTF-8 byte[] to String

Why not get what you are looking for from the get go and read a string from the file instead of an array of bytes? Something like:

BufferedReader in = new BufferedReader(new InputStreamReader( new FileInputStream( "foo.txt"), Charset.forName( "UTF-8"));

then readLine from in until it's done.

Find out who is locking a file on a network share

Just in case someone looking for a solution to this for a Windows based system or NAS:

There is a built-in function in Windows that shows you what files on the local computer are open/locked by remote computer (which has the file open through a file share):

  • Select "Manage Computer" (Open "Computer Management")
  • click "Shared Folders"
  • choose "Open Files"

There you can even close the file forcefully.

Path to MSBuild

@AllenSanborn has a great powershell version, but some folks have a requirement to use only batch scripts for builds.

This is an applied version of what @bono8106 answered.

msbuildpath.bat

@echo off

reg.exe query "HKLM\SOFTWARE\Microsoft\MSBuild\ToolsVersions\14.0" /v MSBuildToolsPath > nul 2>&1
if ERRORLEVEL 1 goto MissingMSBuildRegistry

for /f "skip=2 tokens=2,*" %%A in ('reg.exe query "HKLM\SOFTWARE\Microsoft\MSBuild\ToolsVersions\14.0" /v MSBuildToolsPath') do SET "MSBUILDDIR=%%B"

IF NOT EXIST "%MSBUILDDIR%" goto MissingMSBuildToolsPath
IF NOT EXIST "%MSBUILDDIR%msbuild.exe" goto MissingMSBuildExe

exit /b 0

goto:eof
::ERRORS
::---------------------
:MissingMSBuildRegistry
echo Cannot obtain path to MSBuild tools from registry
goto:eof
:MissingMSBuildToolsPath
echo The MSBuild tools path from the registry '%MSBUILDDIR%' does not exist
goto:eof
:MissingMSBuildExe
echo The MSBuild executable could not be found at '%MSBUILDDIR%'
goto:eof

build.bat

@echo off
call msbuildpath.bat
"%MSBUILDDIR%msbuild.exe" foo.csproj /p:Configuration=Release

For Visual Studio 2017 / MSBuild 15, Aziz Atif (the guy who wrote Elmah) wrote a batch script

build.cmd Release Foo.csproj

https://github.com/linqpadless/LinqPadless/blob/master/build.cmd

@echo off
setlocal
if "%PROCESSOR_ARCHITECTURE%"=="x86" set PROGRAMS=%ProgramFiles%
if defined ProgramFiles(x86) set PROGRAMS=%ProgramFiles(x86)%
for %%e in (Community Professional Enterprise) do (
    if exist "%PROGRAMS%\Microsoft Visual Studio\2017\%%e\MSBuild\15.0\Bin\MSBuild.exe" (
        set "MSBUILD=%PROGRAMS%\Microsoft Visual Studio\2017\%%e\MSBuild\15.0\Bin\MSBuild.exe"
    )
)
if exist "%MSBUILD%" goto :restore
set MSBUILD=
for %%i in (MSBuild.exe) do set MSBUILD=%%~dpnx$PATH:i
if not defined MSBUILD goto :nomsbuild
set MSBUILD_VERSION_MAJOR=
set MSBUILD_VERSION_MINOR=
for /f "delims=. tokens=1,2,3,4" %%m in ('msbuild /version /nologo') do (
    set MSBUILD_VERSION_MAJOR=%%m
    set MSBUILD_VERSION_MINOR=%%n
)
if not defined MSBUILD_VERSION_MAJOR goto :nomsbuild
if not defined MSBUILD_VERSION_MINOR goto :nomsbuild
if %MSBUILD_VERSION_MAJOR% lss 15    goto :nomsbuild
if %MSBUILD_VERSION_MINOR% lss 1     goto :nomsbuild
:restore
for %%i in (NuGet.exe) do set nuget=%%~dpnx$PATH:i
if "%nuget%"=="" (
    echo WARNING! NuGet executable not found in PATH so build may fail!
    echo For more on NuGet, see https://github.com/nuget/home
)
pushd "%~dp0"
nuget restore ^
 && call :build Debug   %* ^
 && call :build Release %*
popd
goto :EOF

:build
setlocal
"%MSBUILD%" /p:Configuration=%1 /v:m %2 %3 %4 %5 %6 %7 %8 %9
goto :EOF

:nomsbuild
echo Microsoft Build version 15.1 (or later) does not appear to be
echo installed on this machine, which is required to build the solution.
exit /b 1

Android: Clear the back stack

Intent intent = new Intent(this, A.class);
startActivity(intent);
finish();

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

SELECT object_definition (OBJECT_ID(N'dbo.vEmployee'))

How to list files in an android directory?

Your path is not within the assets folder. Either you enumerate files within the assets folder by means of AssetManager.list() or you enumerate files on your SD card by means of File.list()

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

I just wrote something to handle something along the authors intention. I found the best thing to do was to let the constructor take all the objects and then in your implemented method use that constructor objects.

However, if you are writing a generic interface class, then you have to pass an Object, or better a list of Objects. This could be done by Object[] or even better, Object ... because it is easier to call.

See my example piece just below.

List<String> lst = new ArrayList<String>();
lst.add("1");
lst.add("2");        

SomeAbstractClass p = new SomeAbstractClass (lst, "another parameter", 20, true) {            

    public void perform( ) {                           
        ArrayList<String> lst = (ArrayList<String>)getArgs()[0];                        
    }

};

public abstract class SomeAbstractClass{    
    private Object[] args;

    public SomeAbstractClass(Object ... args) {
        this.args = args;           
    }      

    public abstract void perform();        

    public Object[] getArgs() {
        return args;
    }

}

Please see this post about Java closures that supports this out of the box: http://mseifed.blogspot.se/2012/09/closure-implementation-for-java-5-6-and.html

Version 1 supports passing of non-final closures with autocasting:
https://github.com/MSeifeddo/Closure-implementation-for-Java-5-6-and-7/blob/master/org/mo/closure/v1/Closure.java

    SortedSet<String> sortedNames = new TreeSet<String>();
    // NOTE! Instead of enforcing final, we pass it through the constructor
    eachLine(randomFile0, new V1<String>(sortedNames) {
        public void call(String line) {
            SortedSet<String> sortedNames = castFirst();  // Read contructor arg zero, and auto cast it
            sortedNames.add(extractName(line));
        }
    });

How to find the php.ini file used by the command line?

Just run php --ini and look for Loaded Configuration File in output for the location of php.ini used by your CLI

How to create a temporary table in SSIS control flow task and then use it in data flow task?

Solution:

Set the property RetainSameConnection on the Connection Manager to True so that temporary table created in one Control Flow task can be retained in another task.

Here is a sample SSIS package written in SSIS 2008 R2 that illustrates using temporary tables.

Walkthrough:

Create a stored procedure that will create a temporary table named ##tmpStateProvince and populate with few records. The sample SSIS package will first call the stored procedure and then will fetch the temporary table data to populate the records into another database table. The sample package will use the database named Sora Use the below create stored procedure script.

USE Sora;
GO

CREATE PROCEDURE dbo.PopulateTempTable
AS
BEGIN
    
    SET NOCOUNT ON;

    IF OBJECT_ID('TempDB..##tmpStateProvince') IS NOT NULL
        DROP TABLE ##tmpStateProvince;

    CREATE TABLE ##tmpStateProvince
    (
            CountryCode     nvarchar(3)         NOT NULL
        ,   StateCode       nvarchar(3)         NOT NULL
        ,   Name            nvarchar(30)        NOT NULL
    );

    INSERT INTO ##tmpStateProvince 
        (CountryCode, StateCode, Name)
    VALUES
        ('CA', 'AB', 'Alberta'),
        ('US', 'CA', 'California'),
        ('DE', 'HH', 'Hamburg'),
        ('FR', '86', 'Vienne'),
        ('AU', 'SA', 'South Australia'),
        ('VI', 'VI', 'Virgin Islands');
END
GO

Create a table named dbo.StateProvince that will be used as the destination table to populate the records from temporary table. Use the below create table script to create the destination table.

USE Sora;
GO

CREATE TABLE dbo.StateProvince
(
        StateProvinceID int IDENTITY(1,1)   NOT NULL
    ,   CountryCode     nvarchar(3)         NOT NULL
    ,   StateCode       nvarchar(3)         NOT NULL
    ,   Name            nvarchar(30)        NOT NULL
    CONSTRAINT [PK_StateProvinceID] PRIMARY KEY CLUSTERED
        ([StateProvinceID] ASC)
) ON [PRIMARY];
GO

Create an SSIS package using Business Intelligence Development Studio (BIDS). Right-click on the Connection Managers tab at the bottom of the package and click New OLE DB Connection... to create a new connection to access SQL Server 2008 R2 database.

Connection Managers - New OLE DB Connection

Click New... on Configure OLE DB Connection Manager.

Configure OLE DB Connection Manager - New

Perform the following actions on the Connection Manager dialog.

  • Select Native OLE DB\SQL Server Native Client 10.0 from Provider since the package will connect to SQL Server 2008 R2 database
  • Enter the Server name, like MACHINENAME\INSTANCE
  • Select Use Windows Authentication from Log on to the server section or whichever you prefer.
  • Select the database from Select or enter a database name, the sample uses the database name Sora.
  • Click Test Connection
  • Click OK on the Test connection succeeded message.
  • Click OK on Connection Manager

Connection Manager

The newly created data connection will appear on Configure OLE DB Connection Manager. Click OK.

Configure OLE DB Connection Manager - Created

OLE DB connection manager KIWI\SQLSERVER2008R2.Sora will appear under the Connection Manager tab at the bottom of the package. Right-click the connection manager and click Properties

Connection Manager Properties

Set the property RetainSameConnection on the connection KIWI\SQLSERVER2008R2.Sora to the value True.

RetainSameConnection Property on Connection Manager

Right-click anywhere inside the package and then click Variables to view the variables pane. Create the following variables.

  • A new variable named PopulateTempTable of data type String in the package scope SO_5631010 and set the variable with the value EXEC dbo.PopulateTempTable.

  • A new variable named FetchTempData of data type String in the package scope SO_5631010 and set the variable with the value SELECT CountryCode, StateCode, Name FROM ##tmpStateProvince

Variables

Drag and drop an Execute SQL Task on to the Control Flow tab. Double-click the Execute SQL Task to view the Execute SQL Task Editor.

On the General page of the Execute SQL Task Editor, perform the following actions.

  • Set the Name to Create and populate temp table
  • Set the Connection Type to OLE DB
  • Set the Connection to KIWI\SQLSERVER2008R2.Sora
  • Select Variable from SQLSourceType
  • Select User::PopulateTempTable from SourceVariable
  • Click OK

Execute SQL Task Editor

Drag and drop a Data Flow Task onto the Control Flow tab. Rename the Data Flow Task as Transfer temp data to database table. Connect the green arrow from the Execute SQL Task to the Data Flow Task.

Control Flow Tab

Double-click the Data Flow Task to switch to Data Flow tab. Drag and drop an OLE DB Source onto the Data Flow tab. Double-click OLE DB Source to view the OLE DB Source Editor.

On the Connection Manager page of the OLE DB Source Editor, perform the following actions.

  • Select KIWI\SQLSERVER2008R2.Sora from OLE DB Connection Manager
  • Select SQL command from variable from Data access mode
  • Select User::FetchTempData from Variable name
  • Click Columns page

OLE DB Source Editor - Connection Manager

Clicking Columns page on OLE DB Source Editor will display the following error because the table ##tmpStateProvince specified in the source command variable does not exist and SSIS is unable to read the column definition.

Error message

To fix the error, execute the statement EXEC dbo.PopulateTempTable using SQL Server Management Studio (SSMS) on the database Sora so that the stored procedure will create the temporary table. After executing the stored procedure, click Columns page on OLE DB Source Editor, you will see the column information. Click OK.

OLE DB Source Editor - Columns

Drag and drop OLE DB Destination onto the Data Flow tab. Connect the green arrow from OLE DB Source to OLE DB Destination. Double-click OLE DB Destination to open OLE DB Destination Editor.

On the Connection Manager page of the OLE DB Destination Editor, perform the following actions.

  • Select KIWI\SQLSERVER2008R2.Sora from OLE DB Connection Manager
  • Select Table or view - fast load from Data access mode
  • Select [dbo].[StateProvince] from Name of the table or the view
  • Click Mappings page

OLE DB Destination Editor - Connection Manager

Click Mappings page on the OLE DB Destination Editor would automatically map the columns if the input and output column names are same. Click OK. Column StateProvinceID does not have a matching input column and it is defined as an IDENTITY column in database. Hence, no mapping is required.

OLE DB Destination Editor - Mappings

Data Flow tab should look something like this after configuring all the components.

Data Flow tab

Click the OLE DB Source on Data Flow tab and press F4 to view Properties. Set the property ValidateExternalMetadata to False so that SSIS would not try to check for the existence of the temporary table during validation phase of the package execution.

Set ValidateExternalMetadata

Execute the query select * from dbo.StateProvince in the SQL Server Management Studio (SSMS) to find the number of rows in the table. It should be empty before executing the package.

Rows in table before package execution

Execute the package. Control Flow shows successful execution.

Package Execution  - Control Flow tab

In Data Flow tab, you will notice that the package successfully processed 6 rows. The stored procedure created early in this posted inserted 6 rows into the temporary table.

Package Execution  - Data Flow tab

Execute the query select * from dbo.StateProvince in the SQL Server Management Studio (SSMS) to find the 6 rows successfully inserted into the table. The data should match with rows founds in the stored procedure.

Rows in table after package execution

The above example illustrated how to create and use temporary table within a package.

powershell 2.0 try catch how to access the exception

Try something like this:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    Write-Host $_.Exception.ToString()
}

The exception is in the $_ variable. You might explore $_ like this:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    $_ | fl * -Force
}

I think it will give you all the info you need.

My rule: if there is some data that is not displayed, try to use -force.

Structuring online documentation for a REST API

That's a very complex question for a simple answer.

You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.

Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.

At the very top level I think quality REST API docs require at least the following:

  • a list of all your API endpoints (base/relative URLs)
  • corresponding HTTP GET/POST/... method type for each endpoint
  • request/response MIME-type (how to encode params and parse replies)
  • a sample request/response, including HTTP headers
  • type and format specified for all params, including those in the URL, body and headers
  • a brief text description and important notes
  • a short code snippet showing the use of the endpoint in popular web programming languages

Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.

how to remove json object key and value.?

Follow this, it can be like what you are looking:

_x000D_
_x000D_
var obj = {_x000D_
    Objone: 'one',_x000D_
    Objtwo: 'two'_x000D_
};_x000D_
_x000D_
var key = "Objone";_x000D_
delete obj[key];_x000D_
console.log(obj); // prints { "objtwo": two}
_x000D_
_x000D_
_x000D_

How to specify an alternate location for the .m2 folder or settings.xml permanently?

You can change the default location of .m2 directory in m2.conf file. It resides in your maven installation directory.

add modify this line in

m2.conf

set maven.home C:\Users\me\.m2

How to make a smaller RatingBar?

the small one implement by the OS

<RatingBar
    android:id="@+id/ratingBar"
    style="?android:attr/ratingBarStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    />

String concatenation in Jinja

My bad, in trying to simplify it, I went too far, actually stuffs is a record of all kinds of info, I just want the id in it.

stuffs = [[123, first, last], [456, first, last]]

I want my_sting to be

my_sting = '123, 456'

My original code should have looked like this:

{% set my_string = '' %}
{% for stuff in stuffs %}
{% set my_string = my_string + stuff.id + ', '%}
{% endfor%}

Thinking about it, stuffs is probably a dictionary, but you get the gist.

Yes I found the join filter, and was going to approach it like this:

 {% set my_string = [] %}
 {% for stuff in stuffs %}
 {% do my_string.append(stuff.id) %}
 {% endfor%}
 {%  my_string|join(', ') %}

But the append doesn't work without importing the extensions to do it, and reading that documentation gave me a headache. It doesn't explicitly say where to import it from or even where you would put the import statement, so I figured finding a way to concat would be the lesser of the two evils.

Go test string contains substring

To compare, there are more options:

import (
    "fmt"
    "regexp"
    "strings"
)

const (
    str    = "something"
    substr = "some"
)

// 1. Contains
res := strings.Contains(str, substr)
fmt.Println(res) // true

// 2. Index: check the index of the first instance of substr in str, or -1 if substr is not present
i := strings.Index(str, substr)
fmt.Println(i) // 0

// 3. Split by substr and check len of the slice, or length is 1 if substr is not present
ss := strings.Split(str, substr)
fmt.Println(len(ss)) // 2

// 4. Check number of non-overlapping instances of substr in str
c := strings.Count(str, substr)
fmt.Println(c) // 1

// 5. RegExp
matched, _ := regexp.MatchString(substr, str)
fmt.Println(matched) // true

// 6. Compiled RegExp
re = regexp.MustCompile(substr)
res = re.MatchString(str)
fmt.Println(res) // true

Benchmarks: Contains internally calls Index, so the speed is almost the same (btw Go 1.11.5 showed a bit bigger difference than on Go 1.14.3).

BenchmarkStringsContains-4              100000000               10.5 ns/op             0 B/op          0 allocs/op
BenchmarkStringsIndex-4                 117090943               10.1 ns/op             0 B/op          0 allocs/op
BenchmarkStringsSplit-4                  6958126               152 ns/op              32 B/op          1 allocs/op
BenchmarkStringsCount-4                 42397729                29.1 ns/op             0 B/op          0 allocs/op
BenchmarkStringsRegExp-4                  461696              2467 ns/op            1326 B/op         16 allocs/op
BenchmarkStringsRegExpCompiled-4         7109509               168 ns/op               0 B/op          0 allocs/op

What is the LD_PRELOAD trick?

As many people mentioned, using LD_PRELOAD to preload library. BTW, you can CHECK if the setting is available by ldd command.

Example: suppose you need to preload your own libselinux.so.1.

> ldd /bin/ls
    ...
    libselinux.so.1 => /lib/x86_64-linux-gnu/libselinux.so.1 (0x00007f3927b1d000)
    libacl.so.1 => /lib/x86_64-linux-gnu/libacl.so.1 (0x00007f3927914000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f392754f000)
    libpcre.so.3 => /lib/x86_64-linux-gnu/libpcre.so.3 (0x00007f3927311000)
    libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f392710c000)
    /lib64/ld-linux-x86-64.so.2 (0x00007f3927d65000)
    libattr.so.1 => /lib/x86_64-linux-gnu/libattr.so.1 (0x00007f3926f07000)

Thus, set your preload environment:

  export LD_PRELOAD=/home/patric/libselinux.so.1

Check your library again:

>ldd /bin/ls
    ...
    libselinux.so.1 =>
    /home/patric/libselinux.so.1 (0x00007fb9245d8000)
    ...

How to import a .cer certificate into a java keystore?

  • If you want to authenticate you need the private key - there is no other option.
  • A certificate is a public key with extra properties (like company name, country,...) that is signed by some Certificate authority that guarantees that the attached properties are true.
  • .CER files are certificates and don't have the private key. The private key is provided with a .PFX keystore file normally. If you really authenticate is because you already had imported the private key.
  • You normally can import .CER certificates without any problems with

    keytool -importcert -file certificate.cer -keystore keystore.jks -alias "Alias" 
    

Format an Integer using Java String Format

String.format("%03d", 1)  // => "001"
//              ¦¦¦   +-- print the number one
//              ¦¦+------ ... as a decimal integer
//              ¦+------- ... minimum of 3 characters wide
//              +-------- ... pad with zeroes instead of spaces

See java.util.Formatter for more information.

How do I force git to checkout the master branch and remove carriage returns after I've normalized files using the "text" attribute?

Ahah! Checkout the previous commit, then checkout the master.

git checkout HEAD^
git checkout -f master

Continuous CSS rotation animation on hover, animated back to 0deg on hover out

It took a few tries, but I was able to get your jsFiddle to work (for Webkit only).

There's still an issue with the animation speed when the user re-enters the div.

Basically, just set the current rotation value to a variable, then do some calculations on that value (to convert to degrees), then set that value back to the element on mouse move and mouse enter.

Check out the jsFiddle: http://jsfiddle.net/4Vz63/46/

Check out this article for more information, including how to add cross-browser compatibility: http://css-tricks.com/get-value-of-css-rotation-through-javascript/

Call to a member function fetch_assoc() on boolean in <path>

This error happen usually when tables in the query doesn't exist. Just check the table's spelling in the query, and it will work.

Substring a string from the end of the string

Try this:

var s = "Hello Marco !";

var corrected = s.Substring(0, s.Length - 2);

Left function in c#

Just write what you really wanted to know:

fac.GetCachedValue("Auto Print Clinical Warnings").ToLower().StartsWith("y")

It's much simpler than anything with substring.

How to sort a list of strings numerically?

Seamus Campbell's answer doesnot work on python2.x.
list1 = sorted(list1, key=lambda e: int(e)) using lambda function works well.

Extract year from date

if all your dates are the same width, you can put the dates in a vector and use substring

Date
a <- c("01/01/2009", "01/01/2010" , "01/01/2011")
substring(a,7,10) #This takes string and only keeps the characters beginning in position 7 to position 10

output

[1] "2009" "2010" "2011"

Remove directory which is not empty

[EDIT: using node.js v15.5.0]

Having just tried using some of the solutions posted here, I encountered the following deprecation warning:

(node:13202) [DEP0147] DeprecationWarning: In future versions of Node.js, fs.rmdir(path, { recursive: true }) will throw if path does not exist or is a file. Use fs.rm(path, { recursive: true, force: true }) instead

fs.rm(path, { recursive: true, force: true }); works nicely, with fs.rmSync(path, { recursive: true, force: true }); if you want to use the blocking version.

Remove items from one list in another

You can use Except:

List<car> list1 = GetTheList();
List<car> list2 = GetSomeOtherList();
List<car> result = list2.Except(list1).ToList();

You probably don't even need those temporary variables:

List<car> result = GetSomeOtherList().Except(GetTheList()).ToList();

Note that Except does not modify either list - it creates a new list with the result.

How to remove the last element added into the List?

You can use List<T>.RemoveAt method:

rows.RemoveAt(rows.Count -1);

What is a CSRF token? What is its importance and how does it work?

The Cloud Under blog has a good explanation of CSRF tokens. (archived)

Imagine you had a website like a simplified Twitter, hosted on a.com. Signed in users can enter some text (a tweet) into a form that’s being sent to the server as a POST request and published when they hit the submit button. On the server the user is identified by a cookie containing their unique session ID, so your server knows who posted the Tweet.

The form could be as simple as that:

 <form action="http://a.com/tweet" method="POST">
   <input type="text" name="tweet">
   <input type="submit">
 </form> 

Now imagine, a bad guy copies and pastes this form to his malicious website, let’s say b.com. The form would still work. As long

as a user is signed in to your Twitter (i.e. they’ve got a valid session cookie for a.com), the POST request would be sent to http://a.com/tweet and processed as usual when the user clicks the submit button.

So far this is not a big issue as long as the user is made aware about what the form exactly does, but what if our bad guy tweaks the form like this:

 <form action="https://example.com/tweet" method="POST">
   <input type="hidden" name="tweet" value="Buy great products at http://b.com/#iambad">
   <input type="submit" value="Click to win!">
 </form> 

Now, if one of your users ends up on the bad guy’s website and hits the “Click to win!” button, the form is submitted to

your website, the user is correctly identified by the session ID in the cookie and the hidden Tweet gets published.

If our bad guy was even worse, he would make the innocent user submit this form as soon they open his web page using JavaScript, maybe even completely hidden away in an invisible iframe. This basically is cross-site request forgery.

A form can easily be submitted from everywhere to everywhere. Generally that’s a common feature, but there are many more cases where it’s important to only allow a form being submitted from the domain where it belongs to.

Things are even worse if your web application doesn’t distinguish between POST and GET requests (e.g. in PHP by using $_REQUEST instead of $_POST). Don’t do that! Data altering requests could be submitted as easy as <img src="http://a.com/tweet?tweet=This+is+really+bad">, embedded in a malicious website or even an email.

How do I make sure a form can only be submitted from my own website? This is where the CSRF token comes in. A CSRF token is a random, hard-to-guess string. On a page with a form you want to protect, the server would generate a random string, the CSRF token, add it to the form as a hidden field and also remember it somehow, either by storing it in the session or by setting a cookie containing the value. Now the form would look like this:

    <form action="https://example.com/tweet" method="POST">
      <input type="hidden" name="csrf-token" value="nc98P987bcpncYhoadjoiydc9ajDlcn">
      <input type="text" name="tweet">
      <input type="submit">
    </form> 

When the user submits the form, the server simply has to compare the value of the posted field csrf-token (the name doesn’t

matter) with the CSRF token remembered by the server. If both strings are equal, the server may continue to process the form. Otherwise the server should immediately stop processing the form and respond with an error.

Why does this work? There are several reasons why the bad guy from our example above is unable to obtain the CSRF token:

Copying the static source code from our page to a different website would be useless, because the value of the hidden field changes with each user. Without the bad guy’s website knowing the current user’s CSRF token your server would always reject the POST request.

Because the bad guy’s malicious page is loaded by your user’s browser from a different domain (b.com instead of a.com), the bad guy has no chance to code a JavaScript, that loads the content and therefore our user’s current CSRF token from your website. That is because web browsers don’t allow cross-domain AJAX requests by default.

The bad guy is also unable to access the cookie set by your server, because the domains wouldn’t match.

When should I protect against cross-site request forgery? If you can ensure that you don’t mix up GET, POST and other request methods as described above, a good start would be to protect all POST requests by default.

You don’t have to protect PUT and DELETE requests, because as explained above, a standard HTML form cannot be submitted by a browser using those methods.

JavaScript on the other hand can indeed make other types of requests, e.g. using jQuery’s $.ajax() function, but remember, for AJAX requests to work the domains must match (as long as you don’t explicitly configure your web server otherwise).

This means, often you do not even have to add a CSRF token to AJAX requests, even if they are POST requests, but you will have to make sure that you only bypass the CSRF check in your web application if the POST request is actually an AJAX request. You can do that by looking for the presence of a header like X-Requested-With, which AJAX requests usually include. You could also set another custom header and check for its presence on the server side. That’s safe, because a browser would not add custom headers to a regular HTML form submission (see above), so no chance for Mr Bad Guy to simulate this behaviour with a form.

If you’re in doubt about AJAX requests, because for some reason you cannot check for a header like X-Requested-With, simply pass the generated CSRF token to your JavaScript and add the token to the AJAX request. There are several ways of doing this; either add it to the payload just like a regular HTML form would, or add a custom header to the AJAX request. As long as your server knows where to look for it in an incoming request and is able to compare it to the original value it remembers from the session or cookie, you’re sorted.

What is attr_accessor in Ruby?

Attributes and accessor methods

Attributes are class components that can be accessed from outside the object. They are known as properties in many other programming languages. Their values are accessible by using the "dot notation", as in object_name.attribute_name. Unlike Python and a few other languages, Ruby does not allow instance variables to be accessed directly from outside the object.

class Car
  def initialize
    @wheels = 4  # This is an instance variable
  end
end

c = Car.new
c.wheels     # Output: NoMethodError: undefined method `wheels' for #<Car:0x00000000d43500>

In the above example, c is an instance (object) of the Car class. We tried unsuccessfully to read the value of the wheels instance variable from outside the object. What happened is that Ruby attempted to call a method named wheels within the c object, but no such method was defined. In short, object_name.attribute_name tries to call a method named attribute_name within the object. To access the value of the wheels variable from the outside, we need to implement an instance method by that name, which will return the value of that variable when called. That's called an accessor method. In the general programming context, the usual way to access an instance variable from outside the object is to implement accessor methods, also known as getter and setter methods. A getter allows the value of a variable defined within a class to be read from the outside and a setter allows it to be written from the outside.

In the following example, we have added getter and setter methods to the Car class to access the wheels variable from outside the object. This is not the "Ruby way" of defining getters and setters; it serves only to illustrate what getter and setter methods do.

class Car
  def wheels  # getter method
    @wheels
  end

  def wheels=(val)  # setter method
    @wheels = val
  end
end

f = Car.new
f.wheels = 4  # The setter method was invoked
f.wheels  # The getter method was invoked
# Output: => 4

The above example works and similar code is commonly used to create getter and setter methods in other languages. However, Ruby provides a simpler way to do this: three built-in methods called attr_reader, attr_writer and attr_acessor. The attr_reader method makes an instance variable readable from the outside, attr_writer makes it writeable, and attr_acessor makes it readable and writeable.

The above example can be rewritten like this.

class Car
  attr_accessor :wheels
end

f = Car.new
f.wheels = 4
f.wheels  # Output: => 4

In the above example, the wheels attribute will be readable and writable from outside the object. If instead of attr_accessor, we used attr_reader, it would be read-only. If we used attr_writer, it would be write-only. Those three methods are not getters and setters in themselves but, when called, they create getter and setter methods for us. They are methods that dynamically (programmatically) generate other methods; that's called metaprogramming.

The first (longer) example, which does not employ Ruby's built-in methods, should only be used when additional code is required in the getter and setter methods. For instance, a setter method may need to validate data or do some calculation before assigning a value to an instance variable.

It is possible to access (read and write) instance variables from outside the object, by using the instance_variable_get and instance_variable_set built-in methods. However, this is rarely justifiable and usually a bad idea, as bypassing encapsulation tends to wreak all sorts of havoc.

Changing the highlight color when selecting text in an HTML text input

this is the code.

/*** Works on common browsers ***/
::selection {
    background-color: #352e7e;
    color: #fff;
}

/*** Mozilla based browsers ***/
::-moz-selection {
    background-color: #352e7e;
    color: #fff;
}

/***For Other Browsers ***/
::-o-selection {
    background-color: #352e7e;
    color: #fff;
}

::-ms-selection {
    background-color: #352e7e;
    color: #fff;
}

/*** For Webkit ***/
::-webkit-selection {
    background-color: #352e7e;
    color: #fff;
}

Message: Trying to access array offset on value of type null

This happens because $cOTLdata is not null but the index 'char_data' does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.

To check whether the index exists or not you can use isset():

isset($cOTLdata['char_data'])

Which means the line should look something like this:

$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;

Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).

Is it possible to sort a ES6 map object?

As far as I see it's currently not possible to sort a Map properly.

The other solutions where the Map is converted into an array and sorted this way have the following bug:

var a = new Map([[1, 2], [3,4]])
console.log(a);    // a = Map(2) {1 => 2, 3 => 4}

var b = a;
console.log(b);    // b = Map(2) {1 => 2, 3 => 4}

a = new Map();     // this is when the sorting happens
console.log(a, b); // a = Map(0) {}     b = Map(2) {1 => 2, 3 => 4}

The sorting creates a new object and all other pointers to the unsorted object get broken.

Setting up a websocket on Apache?

I can't answer all questions, but I will do my best.

As you already know, WS is only a persistent full-duplex TCP connection with framed messages where the initial handshaking is HTTP-like. You need some server that's listening for incoming WS requests and that binds a handler to them.

Now it might be possible with Apache HTTP Server, and I've seen some examples, but there's no official support and it gets complicated. What would Apache do? Where would be your handler? There's a module that forwards incoming WS requests to an external shared library, but this is not necessary with the other great tools to work with WS.

WS server trends now include: Autobahn (Python) and Socket.IO (Node.js = JavaScript on the server). The latter also supports other hackish "persistent" connections like long polling and all the COMET stuff. There are other little known WS server frameworks like Ratchet (PHP, if you're only familiar with that).

In any case, you will need to listen on a port, and of course that port cannot be the same as the Apache HTTP Server already running on your machine (default = 80). You could use something like 8080, but even if this particular one is a popular choice, some firewalls might still block it since it's not supposed to be Web traffic. This is why many people choose 443, which is the HTTP Secure port that, for obvious reasons, firewalls do not block. If you're not using SSL, you can use 80 for HTTP and 443 for WS. The WS server doesn't need to be secure; we're just using the port.

Edit: According to Iharob Al Asimi, the previous paragraph is wrong. I have no time to investigate this, so please see his work for more details.

About the protocol, as Wikipedia shows, it looks like this:

Client sends:

GET /mychat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat
Sec-WebSocket-Version: 13
Origin: http://example.com

Server replies:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat

and keeps the connection alive. If you can implement this handshaking and the basic message framing (encapsulating each message with a small header describing it), then you can use any client-side language you want. JavaScript is only used in Web browsers because it's built-in.

As you can see, the default "request method" is an initial HTTP GET, although this is not really HTTP and looses everything in common with HTTP after this handshaking. I guess servers that do not support

Upgrade: websocket
Connection: Upgrade

will reply with an error or with a page content.

How can I capitalize the first letter of each word in a string using JavaScript?

As of ECMA2017 or ES8

_x000D_
_x000D_
const titleCase = (string) => {_x000D_
  return string_x000D_
    .split(' ')_x000D_
    .map(word => word.substr(0,1).toUpperCase() + word.substr(1,word.length))_x000D_
    .join(' ');_x000D_
};_x000D_
_x000D_
let result = titleCase('test test test');_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_
Explanation:
1. First, we pass the string "test test test" to our function "titleCase".
2. We split a string on the space basis so the result of first function "split" will be ["test","test","test"]
3. As we got an array, we used map function for manipulation each word in the array. We capitalize the first character and add remaining character to it.
4. In the last, we join the array using space as we split the string by sapce.

Bad Gateway 502 error with Apache mod_proxy and Tomcat

Most likely you should increase Timeout parameter in apache conf (default value 120 sec)

Getting a union of two arrays in JavaScript

ES2015 version

Array.prototype.diff = function(a) {return this.filter(i => a.indexOf(i) < 0)};

Array.prototype.union = function(a) {return [...this.diff(a), ...a]}

How to sort an array based on the length of each element?

<script>
         arr = []
         arr[0] = "ab"
         arr[1] = "abcdefgh"
         arr[2] = "sdfds"
         arr.sort(function(a,b){
            return a.length<b.length
         })
         document.write(arr)

</script>

The anonymous function that you pass to sort tells it how to sort the given array.hope this helps.I know this is confusing but you can tell the sort function how to sort the elements of the array by passing it a function as a parameter telling it what to do

Is it possible to overwrite a function in PHP

Depending on situation where you need this, maybe you can use anonymous functions like this:

$greet = function($name)
{
    echo('Hello ' . $name);
};

$greet('World');

...then you can set new function to the given variable any time

how to calculate percentage in python

marks = raw_input('Enter your Obtain marks:')
outof = raw_input('Enter Out of marks:')
marks = int(marks)
outof = int(outof)
per = marks*100/outof
print 'Your Percentage is:'+str(per)

Note : raw_input() function is used to take input from console and its return string formatted value. So we need to convert into integer otherwise it give error of conversion.

How to check if a MySQL query using the legacy API was successful?

put only :

or die(mysqli_error());

after your query

and it will retern the error as echo

example

// "Your Query" means you can put "Select/Update/Delete/Set" queries here
$qfetch = mysqli_fetch_assoc(mysqli_query("your query")) or die(mysqli_error()); 



    if (mysqli_errno()) {
        echo 'error' . mysqli_error();
        die();
    }

UICollectionView Set number of columns

I made a collection layout.

To make the separator visible, Set the background color of the collection view to gray. One row per section.

Useage:

let layout = GridCollectionViewLayout()
layout.cellHeight = 50 // if not set, cellHeight = Collection.height/numberOfSections
layout.cellWidth = 50  // if not set, cellWidth = Collection.width/numberOfItems(inSection)
collectionView.collectionViewLayout = layout

Layout:

import UIKit

class GridCollectionViewLayout: UICollectionViewLayout {


var cellWidth : CGFloat = 0
var cellHeight : CGFloat = 0
var seperator: CGFloat = 1

private var cache = [UICollectionViewLayoutAttributes]()



override func prepare() {

    guard let collectionView = self.collectionView else {
        return
    }

    self.cache.removeAll()



        let numberOfSections = collectionView.numberOfSections

        if cellHeight <= 0
        {
            cellHeight = (collectionView.bounds.height - seperator*CGFloat(numberOfSections-1))/CGFloat(numberOfSections)
        }

        for section in 0..<collectionView.numberOfSections {

            let numberOfItems = collectionView.numberOfItems(inSection: section)

            let cellWidth2 : CGFloat
            if cellWidth <= 0
            {
                cellWidth2 = (collectionView.bounds.width - seperator*CGFloat(numberOfItems-1))/CGFloat(numberOfItems)
            }
            else
            {
                cellWidth2 = cellWidth
            }


            for row in 0..<numberOfItems {


                let indexPath = NSIndexPath(row: row, section: section)

                let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath as IndexPath)
                attributes.frame = CGRect(x: (cellWidth2+seperator)*CGFloat(row),
                                          y: (cellHeight+seperator)*CGFloat(section),
                                          width: cellWidth2,
                                          height: cellHeight)

                //row_temp.append(attributes)

                self.cache.append(attributes)
            }
            //self.itemAttributes.append(row_temp)
        }

}

override var collectionViewContentSize: CGSize {

    guard let collectionView = collectionView else
    {
        return CGSize.zero
    }

    if (collectionView.numberOfSections <= 0)
    {
        return collectionView.bounds.size
    }

    let width:CGFloat
    if cellWidth <= 0
    {
        width = collectionView.bounds.width
    }
    else
    {
        width = cellWidth*CGFloat(collectionView.numberOfItems(inSection: 0))
    }

    let numberOfSections = CGFloat(collectionView.numberOfSections)
    var height:CGFloat = 0
    height += numberOfSections * cellHeight
    height += (numberOfSections - 1) * seperator



    return CGSize(width: width, height: height)
}

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

    var layoutAttributes = [UICollectionViewLayoutAttributes]()

    for attributes in cache {
        if attributes.frame.intersects(rect) {
            layoutAttributes.append(attributes)
        }
    }
    return layoutAttributes
}

override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
    return cache[indexPath.item]
}
}

Callback function for JSONP with jQuery AJAX

$.ajax({
        url: 'http://url.of.my.server/submit',
        dataType: "jsonp",
        jsonp: 'callback',
        jsonpCallback: 'jsonp_callback'
    });

jsonp is the querystring parameter name that is defined to be acceptable by the server while the jsonpCallback is the javascript function name to be executed at the client.
When you use such url:

url: 'http://url.of.my.server/submit?callback=?'

the question mark ? at the end instructs jQuery to generate a random function while the predfined behavior of the autogenerated function will just invoke the callback -the sucess function in this case- passing the json data as a parameter.

$.ajax({
        url: 'http://url.of.my.server/submit?callback=?',
        success: function (data, status) {
            mySurvey.closePopup();
        },
        error: function (xOptions, textStatus) {
            mySurvey.closePopup();
        }
    });


The same goes here if you are using $.getJSON with ? placeholder it will generate a random function while the predfined behavior of the autogenerated function will just invoke the callback:

$.getJSON('http://url.of.my.server/submit?callback=?',function(data){
//process data here
});

Integrating Dropzone.js into existing HTML form with other fields

I want to contribute an answer here as I too have faced the same issue - we want the $_FILES element available as part of the same post as another form. My answer is based on @mrtnmgs however notes the comments added to that question.

Firstly: Dropzone posts its data via ajax

Just because you use the formData.append option still means that you must tackle the UX actions - i.e. this all happens behind the scenes and isn't a typical form post. Data is posted to your url parameter.

Secondly: If you therefore want to mimic a form post you will need to store the posted data

This requires server side code to store your $_POST or $_FILES in a session which is available to the user on another page load as the user will not go to the page where the posted data is received.

Thirdly: You need to redirect the user to the page where this data is actioned

Now you have posted your data, stored it in a session, you need to display/action it for the user in an additional page. You need to send the user to that page as well.

So for my example:

[Dropzone code: Uses Jquery]

$('#dropArea').dropzone({
    url:        base_url+'admin/saveProject',
    maxFiles:   1,
    uploadMultiple: false,
    autoProcessQueue:false,
    addRemoveLinks: true,
    init:       function(){
        dzClosure = this;

        $('#projectActionBtn').on('click',function(e) {
            dzClosure.processQueue(); /* My button isn't a submit */
        });

        // My project only has 1 file hence not sendingmultiple
        dzClosure.on('sending', function(data, xhr, formData) {
            $('#add_user input[type="text"],#add_user textarea').each(function(){
                formData.append($(this).attr('name'),$(this).val());
            })
        });

        dzClosure.on('complete',function(){
            window.location.href = base_url+'admin/saveProject';
        })
    },
});

Delete all records in a table of MYSQL in phpMyAdmin

Use this query:

DELETE FROM tableName;

Note: To delete some specific record you can give the condition in where clause in the query also.

OR you can use this query also:

truncate tableName;

Also remember that you should not have any relationship with other table. If there will be any foreign key constraint in the table then those record will not be deleted and will give the error.

How to return only 1 row if multiple duplicate rows and still return rows that are not duplicates?

From the title I'm guessing you only need one result per unique row? If this is the case, take a look at the GROUP BY clause (or SELECT DISTINCT).

git with development, staging and production branches

one of the best things about git is that you can change the work flow that works best for you.. I do use http://nvie.com/posts/a-successful-git-branching-model/ most of the time but you can use any workflow that fits your needs

clearing select using jquery

$('option', '#theSelect').remove();

C#: How do you edit items and subitems in a listview?

Click the items in the list view. Add a button that will edit the selected items. Add the code

try
{              
    LSTDEDUCTION.SelectedItems[0].SubItems[1].Text = txtcarName.Text;
    LSTDEDUCTION.SelectedItems[0].SubItems[0].Text = txtcarBrand.Text;
    LSTDEDUCTION.SelectedItems[0].SubItems[2].Text = txtCarName.Text;
}
catch{}

Multiplication on command line terminal

For more advanced and precise math consider using bc(1).

echo "3 * 2.19" | bc -l 
6.57

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

If you want to upload the file /Applications/XAMPP/htdocs/keypairfile.pem to ec2-user@publicdns:/var/www/html, you can simply do:

scp -Cr /Applications/XAMPP/htdocs/keypairfile.pem/uploads/ ec2-user@publicdns:/var/www/html/

Where:

  • -C - Compress data
  • -r - Recursive

Angular 5 Reactive Forms - Radio Button Group

I tried your code, you didn't assign/bind a value to your formControlName.

In HTML file:

<form [formGroup]="form">
   <label>
     <input type="radio" value="Male" formControlName="gender">
       <span>male</span>
   </label>
   <label>
     <input type="radio" value="Female" formControlName="gender">
       <span>female</span>
   </label>
</form>

In the TS file:

  form: FormGroup;
  constructor(fb: FormBuilder) {
    this.name = 'Angular2'
    this.form = fb.group({
      gender: ['', Validators.required]
    });
  }

Make sure you use Reactive form properly: [formGroup]="form" and you don't need the name attribute.

In my sample. words male and female in span tags are the values display along the radio button and Male and Female values are bind to formControlName

See the screenshot: enter image description here

To make it shorter:

<form [formGroup]="form">
  <input type="radio" value='Male' formControlName="gender" >Male
  <input type="radio" value='Female' formControlName="gender">Female
</form>

enter image description here

Hope it helps:)

Heroku + node.js error (Web process failed to bind to $PORT within 60 seconds of launch)

I realized that I don't need the port number in the request endpoint, so the endpoint was herokuapp.com and not herokuapp.com:5000.

The listen() call can be without host and callback:

server.listen(5000);

How to create a session using JavaScript?

I think you misunderstood the concept of session, session is a server side per-user-data-store which allows you to save user data on the server side.

thus, you have 2 options, resort to use cookies, which will give the illusion of session(but not quite the same), you can access cookies very simply by document.cookie .

but, if you want your server be aware of the session, you need to use some sort of server request probably the best way is to use AJAX to do this.

I would recommend you to re-read the definition of sessions.

docker error: /var/run/docker.sock: no such file or directory

The first /var/run/docker.sock refers to the same path in your boot2docker virtual machine. Correcly write for windows /var/run/docker.sock

Ruby sleep or delay less than a second?

Pass float to sleep, like sleep 0.1

Working with time DURATION, not time of day

With custom format of a cell you can insert a type like this: d "days", h:mm:ss, which will give you a result like 16 days, 13:56:15 in an excel-cell.

If you would like to show the duration in hours you use the following type [h]:mm:ss, which will lead to something like 397:56:15. Control check: 16 =(397 hours -13 hours)/24

enter image description here

What is the function of FormulaR1C1?

I find the most valuable feature of .FormulaR1C1 is sheer speed. Versus eg a couple of very large loops filling some data into a sheet, If you can convert what you are doing into a .FormulaR1C1 form. Then a single operation eg myrange.FormulaR1C1 = "my particular formuala" is blindingly fast (can be a thousand times faster). No looping and counting - just fill the range at high speed.

Inserting an image with PHP and FPDF

You can use $pdf->GetX() and $pdf->GetY() to get current cooridnates and use them to insert image.

$pdf->Image($image1, 5, $pdf->GetY(), 33.78);

or even

$pdf->Image($image1, 5, null, 33.78);

(ALthough in first case you can add a number to create a bit of a space)

$pdf->Image($image1, 5, $pdf->GetY() + 5, 33.78);

how to remove empty strings from list, then remove duplicate values from a list

To simplify Amiram Korach's solution:

dtList.RemoveAll(s => string.IsNullOrWhiteSpace(s))

No need to use Distinct() or ToList()

When to use LinkedList over ArrayList in Java?

In addition to the other good arguments above, you should notice ArrayList implements RandomAccess interface, while LinkedList implements Queue.

So, somehow they address slightly different problems, with difference of efficiency and behavior (see their list of methods).

Why doesn't JavaScript support multithreading?

It's the implementations that doesn't support multi-threading. Currently Google Gears is providing a way to use some form of concurrency by executing external processes but that's about it.

The new browser Google is supposed to release today (Google Chrome) executes some code in parallel by separating it in process.

The core language, of course can have the same support as, say Java, but support for something like Erlang's concurrency is nowhere near the horizon.

How to detect tableView cell touched or clicked in swift

A of couple things that need to happen...

  1. The view controller needs to extend the type UITableViewDelegate

  2. The view controller needs to include the didSelectRowAt function.

  3. The table view must have the view controller assigned as its delegate.


Below is one place where assigning the delegate could take place (within the view controller).

override func loadView() {
    tableView.dataSource = self
    tableView.delegate = self
    view = tableView
}

And a simple implementation of the didSelectRowAt function.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("row: \(indexPath.row)")
}

How to use patterns in a case statement?

Brace expansion doesn't work, but *, ? and [] do. If you set shopt -s extglob then you can also use extended pattern matching:

  • ?() - zero or one occurrences of pattern
  • *() - zero or more occurrences of pattern
  • +() - one or more occurrences of pattern
  • @() - one occurrence of pattern
  • !() - anything except the pattern

Here's an example:

shopt -s extglob
for arg in apple be cd meet o mississippi
do
    # call functions based on arguments
    case "$arg" in
        a*             ) foo;;    # matches anything starting with "a"
        b?             ) bar;;    # matches any two-character string starting with "b"
        c[de]          ) baz;;    # matches "cd" or "ce"
        me?(e)t        ) qux;;    # matches "met" or "meet"
        @(a|e|i|o|u)   ) fuzz;;   # matches one vowel
        m+(iss)?(ippi) ) fizz;;   # matches "miss" or "mississippi" or others
        *              ) bazinga;; # catchall, matches anything not matched above
    esac
done

remove table row with specific id

Try

$('table#test tr#3').remove();

How to create number input field in Flutter?

You can Easily change the Input Type using the keyboardType Parameter and you have a lot of possibilities check the documentation TextInputType so you can use the number or phone value

 new TextField(keyboardType: TextInputType.number)

How to use random in BATCH script?

here is a example i created for you, it should display a dialog asking you to select a number 1-10, depending on the number you select, it will generate a random number example to a batch file that you named. If you select "1" then you will get a random 1 digit number example. if you select "10" then you will get a random 10 digit number example.

@echo off
color f0
set /p "FileName= Enter Filename (Without Extension) : "
echo @echo off >> %FileName%.bat
echo File Created!
pause
cls
:CommandLine
set /p "calc= ~%ComputerName%: Enter a number to recieve the amount of  random digits :"
if %calc%==genrand_help goto GenerateRandomHelp
if %calc%==1 echo echo %%RANDOM:~-1%% >> %FileName%.bat
if %calc%==2 echo echo %%RANDOM:~-1%%%%RANDOM:~-1%% >> %FileName%.bat 
if %calc%==3 echo echo %%RANDOM:~-1%%%%RANDOM:~-1%%%RANDOM:~-1%% >>  %FileName%.bat
if %calc%==4 echo echo %%RANDOM:~-1%%%%RANDOM:~-1%%%%RANDOM:~-1%%%%RANDOM:~-1%% >> %FileName%.bat
if %calc%==5 echo echo %%Random%% >> %FileName%.bat
if %calc%==6 echo echo %%Random%%%%RANDOM:~-1%% >> %FileName%.bat
if %calc%==7 echo echo %%Random%%%%RANDOM:~-1%%%%RANDOM:~-1%% >> %FileName%.bat 
if %calc%==8 echo echo %%Random%%%%RANDOM:~-1%%%%RANDOM:~-1%%%%RANDOM:~-1%% >> %FileName%.bat
if %calc%==9 echo echo  %%Random%%%%RANDOM:~-1%%%%RANDOM:~-1%%%%RANDOM:~-1%%%%RANDOM:~-1%% >>  %FileName%.bat
if %calc%==10 echo echo %%Random%%%%Random%% >> %FileName%.bat  
goto CommandLine

array.select() in javascript

Array.filter is not implemented in many browsers,It is better to define this function if it does not exist.

The source code for Array.prototype is posted in MDN

if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisp */)
  {
    "use strict";

    if (this == null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun != "function")
      throw new TypeError();

    var res = [];
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in t)
      {
        var val = t[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, t))
          res.push(val);
      }
    }

    return res;
  };
}

see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter for more details

Meaning of end='' in the statement print("\t",end='')?

The default value of end is \n meaning that after the print statement it will print a new line. So simply stated end is what you want to be printed after the print statement has been executed

Eg: - print ("hello",end=" +") will print hello +

Write variable to a file in Ansible

Unless you are writing very small files, you should probably use templates.

Example:

- name: copy upstart script
  template: 
    src: myCompany-service.conf.j2 
    dest: "/etc/init/myCompany-service.conf"

jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF

You can create the required headers in a filter too.

@WebFilter(urlPatterns="/rest/*")
public class AllowAccessFilter implements Filter {
    @Override
    public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain chain) throws IOException, ServletException {
        System.out.println("in AllowAccessFilter.doFilter");
        HttpServletRequest request = (HttpServletRequest)sRequest;
        HttpServletResponse response = (HttpServletResponse)sResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type"); 
        chain.doFilter(request, response);
    }
    ...
}

How do I toggle an element's class in pure JavaScript?

Here is solution implemented with ES6

const toggleClass = (el, className) => el.classList.toggle(className);

usage example

toggleClass(document.querySelector('div.active'), 'active'); // The div container will not have the 'active' class anymore

Correct way of looping through C++ arrays

How about:

#include <iostream>
#include <array>
#include <algorithm>

int main ()
{
    std::array<std::string, 3> text = {"Apple", "Banana", "Orange"};
    std::for_each(text.begin(), text.end(), [](std::string &string){ std::cout << string << "\n"; });

    return 0;
}

Compiles and works with C++ 11 and has no 'raw' looping :)

Is there an equivalent for var_dump (PHP) in Javascript?

If you use Firebug, you can use console.log to output an object and get a hyperlinked, explorable item in the console.

Where to get "UTF-8" string literal in Java?

If you are using OkHttp for Java/Android you can use the following constant:

import com.squareup.okhttp.internal.Util;

Util.UTF_8; // Charset
Util.UTF_8.name(); // String

Convert an image to grayscale in HTML/CSS

Update: I made this into a full GitHub repo, including JavaScript polyfill for IE10 and IE11: https://github.com/karlhorky/gray

I originally used SalmanPK's answer, but then created the variation below to eliminate the extra HTTP request required for the SVG file. The inline SVG works in Firefox versions 10 and above, and versions lower than 10 no longer account for even 1% of the global browser market.

I have since been keeping the solution updated on this blog post, adding support for fading back to color, IE 10/11 support with SVG, and partial grayscale in the demo.

img.grayscale {
  /* Firefox 10+, Firefox on Android */
  filter: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg'><filter id='grayscale'><feColorMatrix type='matrix' values='0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0'/></filter></svg>#grayscale");

  /* IE 6-9 */
  filter: gray;

  /* Chrome 19+, Safari 6+, Safari 6+ iOS */
  -webkit-filter: grayscale(100%);
}

img.grayscale.disabled {
  filter: none;
  -webkit-filter: grayscale(0%);
}

Open popup and refresh parent page on close popup

If your app runs on an HTML5 enabled browser. You can use postMessage. The example given there is quite similar to yours.

Stop absolutely positioned div from overlapping text

Thing which works for me is to use padding-bottom on the sibling just before the absolutely-positioned child. Like in your case, it will be like this:

<div style="position: relative; width:600px;">
    <p>Content of unknown length, but quite quite quite quite quite quite quite quite quite quite quite quite quite quite quite quite long</p>
    <div style="padding-bottom: 100px;">Content of unknown height</div>
    <div class="btn" style="position: absolute; right: 0; bottom: 0; width: 200px; height: 100px;background-color: red;"></div>
</div>

How to check if all of the following items are in a list?

What if your lists contain duplicates like this:

v1 = ['s', 'h', 'e', 'e', 'p']
v2 = ['s', 's', 'h']

Sets do not contain duplicates. So, the following line returns True.

set(v2).issubset(v1)

To count for duplicates, you can use the code:

v1 = sorted(v1)
v2 = sorted(v2)


def is_subseq(v2, v1):
    """Check whether v2 is a subsequence of v1."""
    it = iter(v1)
    return all(c in it for c in v2) 

So, the following line returns False.

is_subseq(v2, v1)

Root password inside a Docker container

I'd suggest a better solution is to give the --add-host NAME:IP argument to docker run when starting the container. That will update the /etc/hosts/ file without any need to become root.

Otherwise, you can override the the USER setting by giving the -u USER flag to docker run. I would advise against this however, as you shouldn't really be changing things in a running container. Instead, make your changes in a Dockerfile and build a new image.

Android error: Failed to install *.apk on device *: timeout

don't use USB 3.0 ports for connection beetwen PC and Android phone!

USB 3.0 - Port with blue tongue

USB 2.0 - Port with black tongue

JavaScript Editor Plugin for Eclipse

Complete the following steps in Eclipse to get plugins for JavaScript files:

  1. Open Eclipse -> Go to "Help" -> "Install New Software"
  2. Select the repository for your version of Eclipse. I have Juno so I selected http://download.eclipse.org/releases/juno
  3. Expand "Programming Languages" -> Check the box next to "JavaScript Development Tools"
  4. Click "Next" -> "Next" -> Accept the Terms of the License Agreement -> "Finish"
  5. Wait for the software to install, then restart Eclipse (by clicking "Yes" button at pop up window)
  6. Once Eclipse has restarted, open "Window" -> "Preferences" -> Expand "General" and "Editors" -> Click "File Associations" -> Add ".js" to the "File types:" list, if it is not already there
  7. In the same "File Associations" dialog, click "Add" in the "Associated editors:" section
  8. Select "Internal editors" radio at the top
  9. Select "JavaScript Viewer". Click "OK" -> "OK"

To add JavaScript Perspective: (Optional)
10. Go to "Window" -> "Open Perspective" -> "Other..."
11. Select "JavaScript". Click "OK"

To open .html or .js file with highlighted JavaScript syntax:
12. (Optional) Select JavaScript Perspective
13. Browse and Select .html or .js file in Script Explorer in [JavaScript Perspective] (Or Package Explorer [Java Perspective] Or PyDev Package Explorer [PyDev Perspective] Don't matter.)
14. Right-click on .html or .js file -> "Open With" -> "Other..."
15. Select "Internal editors"
16. Select "Java Script Editor". Click "OK" (see JavaScript syntax is now highlighted )

Setting a PHP $_SESSION['var'] using jQuery

A lot of responses on here are addressing the how but not the why. PHP $_SESSION key/value pairs are stored on the server. This differs from a cookie, which is stored on the browser. This is why you are able to access values in a cookie from both PHP and JavaScript. To make matters worse, AJAX requests from the browser do not include any of the cookies you have set for the website. So, you will have to make JavaScript pull the Session ID cookie and include it in every AJAX request for the server to be able to make heads or tails of it. On the bright side, PHP Sessions are designed to fail-over to a HTTP GET or POST variable if cookies are not sent along with the HTTP headers. I would look into some of the principles of RESTful web applications and use of of the design patterns that are common with those kinds of applications instead of trying to mangle with the session handler.

MySQL LEFT JOIN Multiple Conditions

Correct answer is simply:

SELECT a.group_id
FROM a 
LEFT JOIN b ON a.group_id=b.group_id  and b.user_id = 4
where b.user_id is null
  and a.keyword like '%keyword%'

Here we are checking user_id = 4 (your user id from the session). Since we have it in the join criteria, it will return null values for any row in table b that does not match the criteria - ie, any group that that user_id is NOT in.

From there, all we need to do is filter for the null values, and we have all the groups that your user is not in.

demo here

How to re-render flatlist?

For quick and simple solution Try:

  1. set extra data to a boolean value.

    extraData={this.state.refresh}

  2. Toggle the value of boolean state when you want to re-render/refresh list

    this.setState({ 
        refresh: !this.state.refresh
    })
    

New to MongoDB Can not run command mongo

After several attempts this works for me on Windows 7 env.:

Initially directory to which you have copied all MongDB sources has such view:

bsondump.exe
mongo.exe
mongod.exe
mongod.pdb
mongodump.exe
mongoexport.exe
mongofiles.exe
mongoimport.exe
mongooplog.exe
mongoperf.exe
mongorestore.exe
mongos.exe
mongos.pdb
mongostat.exe
mongotop.exe

All you need is to add data directory and db directory nested( data/db ) Final view should look like this:

data
bsondump.exe
mongo.exe
mongod.exe
mongod.pdb
mongodump.exe
mongoexport.exe
mongofiles.exe
mongoimport.exe
mongooplog.exe
mongoperf.exe
mongorestore.exe
mongos.exe
mongos.pdb
mongostat.exe
mongotop.exe

Than simply type in directory where MongoDB sources and data/db dirs exist this command:

C:\my_mongo_dir\bin>mongod --dbpath .\data\db

Error:(9, 5) error: resource android:attr/dialogCornerRadius not found

Check your dependencies for uses of + in the versions. Some dependency could be using com.android.support:appcompat-v7:+. This leads to problems when a new version gets released and could break features.

The solution for this would be to either use com.android.support:appcompat-v7:{compileSdkVersion}.+ or don't use + at all and use the full version (ex. com.android.support:appcompat-v7:26.1.0).

If you cannot see a line in your build.gradle files for this, run in android studio terminal to give an overview of what each dependency uses

gradlew -q dependencies app:dependencies --configuration debugAndroidTestCompileClasspath (include androidtest dependencies)

OR

gradlew -q dependencies app:dependencies --configuration debugCompileClasspath (regular dependencies for debug)

which results in something that looks close to this

------------------------------------------------------------
Project :app
------------------------------------------------------------

debugCompileClasspath - Resolved configuration for compilation for variant: debug
...
+--- com.android.support:appcompat-v7:26.1.0
|    +--- com.android.support:support-annotations:26.1.0
|    +--- com.android.support:support-v4:26.1.0 (*)
|    +--- com.android.support:support-vector-drawable:26.1.0
|    |    +--- com.android.support:support-annotations:26.1.0
|    |    \--- com.android.support:support-compat:26.1.0 (*)
|    \--- com.android.support:animated-vector-drawable:26.1.0
|         +--- com.android.support:support-vector-drawable:26.1.0 (*)
|         \--- com.android.support:support-core-ui:26.1.0 (*)
+--- com.android.support:design:26.1.0
|    +--- com.android.support:support-v4:26.1.0 (*)
|    +--- com.android.support:appcompat-v7:26.1.0 (*)
|    +--- com.android.support:recyclerview-v7:26.1.0
|    |    +--- com.android.support:support-annotations:26.1.0
|    |    +--- com.android.support:support-compat:26.1.0 (*)
|    |    \--- com.android.support:support-core-ui:26.1.0 (*)
|    \--- com.android.support:transition:26.1.0
|         +--- com.android.support:support-annotations:26.1.0
|         \--- com.android.support:support-v4:26.1.0 (*)
+--- com.android.support.constraint:constraint-layout:1.0.2
|    \--- com.android.support.constraint:constraint-layout-solver:1.0.2

(*) - dependencies omitted (listed previously)

If you have no control over changing the version, Try forcing it to use a specific version.

configurations.all {
    resolutionStrategy {
        force "com.android.support:appcompat-v7:26.1.0"
        force "com.android.support:support-v4:26.1.0"
    }
}

The force dependency may need to be different depending on what is being set to 28.0.0

How to randomize two ArrayLists in the same fashion?

This can be done using the shuffle method:

private List<Integer> getJumbledList() {
     List<Integer> myArrayList2 = new ArrayList<Integer>();
        myArrayList2.add(8);
        myArrayList2.add(4);
        myArrayList2.add(9);
        Collections.shuffle(myArrayList2);
        return myArrayList2;

xlrd.biffh.XLRDError: Excel xlsx file; not supported

The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:

pip install xlrd==1.2.0

When to use pthread_exit() and when to use pthread_join() in Linux?

pthread_exit() will terminate the calling thread and exit from that(but resources used by calling thread is not released to operating system if it is not detached from main thread.)

pthrade_join() will wait or block the calling thread until target thread is not terminated. In simple word it will wait for to exit the target thread.

In your code, if you put sleep(or delay) in PrintHello function before pthread_exit(), then main thread may be exit and terminate full process, Although your PrintHello function is not completed it will terminate. If you use pthrade_join() function in main before calling pthread_exit() from main it will block main thread and wait to complete your calling thread (PrintHello).

How to read numbers from file in Python?

is working with both python2(e.g. Python 2.7.10) and python3(e.g. Python 3.6.4)

with open('in.txt') as f:
  rows,cols=np.fromfile(f, dtype=int, count=2, sep=" ")
  data = np.fromfile(f, dtype=int, count=cols*rows, sep=" ").reshape((rows,cols))

another way: is working with both python2(e.g. Python 2.7.10) and python3(e.g. Python 3.6.4), as well for complex matrices see the example below (only change int to complex)

with open('in.txt') as f:
   data = []
   cols,rows=list(map(int, f.readline().split()))
   for i in range(0, rows):
      data.append(list(map(int, f.readline().split()[:cols])))
print (data)

I updated the code, this method is working for any number of matrices and any kind of matrices(int,complex,float) in the initial in.txt file.

This program yields matrix multiplication as an application. Is working with python2, in order to work with python3 make the following changes

print to print()

and

print "%7g" %a[i,j],    to     print ("%7g" %a[i,j],end="")

the script:

import numpy as np

def printMatrix(a):
   print ("Matrix["+("%d" %a.shape[0])+"]["+("%d" %a.shape[1])+"]")
   rows = a.shape[0]
   cols = a.shape[1]
   for i in range(0,rows):
      for j in range(0,cols):
         print "%7g" %a[i,j],
      print
   print      

def readMatrixFile(FileName):
   rows,cols=np.fromfile(FileName, dtype=int, count=2, sep=" ")
   a = np.fromfile(FileName, dtype=float, count=rows*cols, sep=" ").reshape((rows,cols))
   return a

def readMatrixFileComplex(FileName):
   data = []
   rows,cols=list(map(int, FileName.readline().split()))
   for i in range(0, rows):
      data.append(list(map(complex, FileName.readline().split()[:cols])))
   a = np.array(data)
   return a

f = open('in.txt')
a=readMatrixFile(f)
printMatrix(a)
b=readMatrixFile(f)
printMatrix(b)
a1=readMatrixFile(f)
printMatrix(a1)
b1=readMatrixFile(f)
printMatrix(b1)
f.close()

print ("matrix multiplication")
c = np.dot(a,b)
printMatrix(c)
c1 = np.dot(a1,b1)
printMatrix(c1)

with open('complex_in.txt') as fid:
  a2=readMatrixFileComplex(fid)
  print(a2)
  b2=readMatrixFileComplex(fid)
  print(b2)

print ("complex matrix multiplication")
c2 = np.dot(a2,b2)
print(c2)
print ("real part of complex matrix")
printMatrix(c2.real)
print ("imaginary part of complex matrix")
printMatrix(c2.imag)

as input file I take in.txt:

4 4
1 1 1 1
2 4 8 16
3 9 27 81
4 16 64 256
4 3
4.02 -3.0 4.0
-13.0 19.0 -7.0
3.0 -2.0 7.0
-1.0 1.0 -1.0
3 4
1 2 -2 0
-3 4 7 2
6 0 3 1
4 2
-1 3
0 9
1 -11
4 -5

and complex_in.txt

3 4
1+1j 2+2j -2-2j 0+0j
-3-3j 4+4j 7+7j 2+2j
6+6j 0+0j 3+3j 1+1j
4 2
-1-1j 3+3j
0+0j 9+9j
1+1j -11-11j
4+4j -5-5j

and the output look like:

Matrix[4][4]
     1      1      1      1
     2      4      8     16
     3      9     27     81
     4     16     64    256

Matrix[4][3]
  4.02     -3      4
   -13     19     -7
     3     -2      7
    -1      1     -1

Matrix[3][4]
     1      2     -2      0
    -3      4      7      2
     6      0      3      1

Matrix[4][2]
    -1      3
     0      9
     1    -11
     4     -5

matrix multiplication
Matrix[4][3]
  -6.98      15       3
 -35.96      70      20
-104.94     189      57
-255.92     420      96

Matrix[3][2]
    -3     43
    18    -60
     1    -20

[[ 1.+1.j  2.+2.j -2.-2.j  0.+0.j]
 [-3.-3.j  4.+4.j  7.+7.j  2.+2.j]
 [ 6.+6.j  0.+0.j  3.+3.j  1.+1.j]]
[[ -1. -1.j   3. +3.j]
 [  0. +0.j   9. +9.j]
 [  1. +1.j -11.-11.j]
 [  4. +4.j  -5. -5.j]]
complex matrix multiplication
[[ 0.  -6.j  0. +86.j]
 [ 0. +36.j  0.-120.j]
 [ 0.  +2.j  0. -40.j]]
real part of complex matrix
Matrix[3][2]
      0       0
      0       0
      0       0

imaginary part of complex matrix
Matrix[3][2]
     -6      86
     36    -120
      2     -40

How do I obtain crash-data from my Android application?

For sample applications and debugging purposes, I use a simple solution that allows me to write the stacktrace to the sd card of the device and/or upload it to a server. This solution has been inspired by Project android-remote-stacktrace (specifically, the save-to-device and upload-to-server parts) and I think it solves the problem mentioned by Soonil. It's not optimal, but it works and you can improve it if you want to use it in a production application. If you decide to upload the stacktraces to the server, you can use a php script (index.php) to view them. If you're interested, you can find all the sources below - one java class for your application and two optional php scrips for the server hosting the uploaded stacktraces.

In a Context (e.g. the main Activity), call

if(!(Thread.getDefaultUncaughtExceptionHandler() instanceof CustomExceptionHandler)) {
    Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(
            "/sdcard/<desired_local_path>", "http://<desired_url>/upload.php"));
}

CustomExceptionHandler

public class CustomExceptionHandler implements UncaughtExceptionHandler {

    private UncaughtExceptionHandler defaultUEH;

    private String localPath;

    private String url;

    /* 
     * if any of the parameters is null, the respective functionality 
     * will not be used 
     */
    public CustomExceptionHandler(String localPath, String url) {
        this.localPath = localPath;
        this.url = url;
        this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
    }

    public void uncaughtException(Thread t, Throwable e) {
        String timestamp = TimestampFormatter.getInstance().getTimestamp();
        final Writer result = new StringWriter();
        final PrintWriter printWriter = new PrintWriter(result);
        e.printStackTrace(printWriter);
        String stacktrace = result.toString();
        printWriter.close();
        String filename = timestamp + ".stacktrace";

        if (localPath != null) {
            writeToFile(stacktrace, filename);
        }
        if (url != null) {
            sendToServer(stacktrace, filename);
        }

        defaultUEH.uncaughtException(t, e);
    }

    private void writeToFile(String stacktrace, String filename) {
        try {
            BufferedWriter bos = new BufferedWriter(new FileWriter(
                    localPath + "/" + filename));
            bos.write(stacktrace);
            bos.flush();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendToServer(String stacktrace, String filename) {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("filename", filename));
        nvps.add(new BasicNameValuePair("stacktrace", stacktrace));
        try {
            httpPost.setEntity(
                    new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
            httpClient.execute(httpPost);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

upload.php

<?php
    $filename = isset($_POST['filename']) ? $_POST['filename'] : "";
    $message = isset($_POST['stacktrace']) ? $_POST['stacktrace'] : "";
    if (!ereg('^[-a-zA-Z0-9_. ]+$', $filename) || $message == ""){
        die("This script is used to log debug data. Please send the "
                . "logging message and a filename as POST variables.");
    }
    file_put_contents($filename, $message . "\n", FILE_APPEND);
?>

index.php

<?php
    $myDirectory = opendir(".");
    while($entryName = readdir($myDirectory)) {
        $dirArray[] = $entryName;
    }
    closedir($myDirectory);
    $indexCount = count($dirArray);
    sort($dirArray);
    print("<TABLE border=1 cellpadding=5 cellspacing=0 \n");
    print("<TR><TH>Filename</TH><TH>Filetype</th><th>Filesize</TH></TR>\n");
    for($index=0; $index < $indexCount; $index++) {
        if ((substr("$dirArray[$index]", 0, 1) != ".") 
                && (strrpos("$dirArray[$index]", ".stacktrace") != false)){ 
            print("<TR><TD>");
            print("<a href=\"$dirArray[$index]\">$dirArray[$index]</a>");
            print("</TD><TD>");
            print(filetype($dirArray[$index]));
            print("</TD><TD>");
            print(filesize($dirArray[$index]));
            print("</TD></TR>\n");
        }
    }
    print("</TABLE>\n");
?>

Best way to remove duplicate entries from a data table

    /* To eliminate Duplicate rows */
    private void RemoveDuplicates(DataTable dt)
    {

        if (dt.Rows.Count > 0)
        {
            for (int i = dt.Rows.Count - 1; i >= 0; i--)
            {
                if (i == 0)
                {
                    break;
                }
                for (int j = i - 1; j >= 0; j--)
                {
                    if (Convert.ToInt32(dt.Rows[i]["ID"]) == Convert.ToInt32(dt.Rows[j]["ID"]) && dt.Rows[i]["Name"].ToString() == dt.Rows[j]["Name"].ToString())
                    {
                        dt.Rows[i].Delete();
                        break;
                    }
                }
            }
            dt.AcceptChanges();
        }
    }

.war vs .ear file

JAR Files

A JAR (short for Java Archive) file permits the combination of several files into a single one. Files with the '.jar'; extension are utilized by software developers to distribute Java classes and various metadata. These also hold libraries and resource files, as well as accessory files (such as property files).

Users can extract and create JAR files with Java Development Kit's (JDK) '.jar' command. ZIP tools may also be used.

JAR files have optional manifest files. Entries within the manifest file prescribe the JAR file's use. A 'main' class specification for a file class denotes the file as a detached or ‘stand-alone' program.

WAR Files

A WAR (or Web Application archive) files can comprise XML (extensible Markup Language) files, Java classes, as well as Java Server pages for purposes of Internet application. It is also employed to mark libraries and Web pages which make up a Web application. Files with the ‘.war' extension contain the Web app for use with server or JSP (Java Server Page) containers. It has JSP, HTML (Hypertext Markup Language), JavaScript, and various files for creating the aforementioned Web apps.

A WAR file is structured as such to allow for special directories and files. It may also have a digital signature (much like that of a JAR file) to show the veracity of the code.

EAR Files

An EAR (Enterprise Archive) file merges JAR and WAR files into a single archive. These files with the ‘.ear' extension have a directory for metadata. The modules are packaged into on archive for smooth and simultaneous operation of the different modules within an app server.

The EAR file also has deployment descriptors (which are XML files) which effectively dictate the deployment of the different modules.

enter image description here

How can I create a Java 8 LocalDate from a long Epoch time in Milliseconds?

You can start with Instant.ofEpochMilli(long):

LocalDate date =
  Instant.ofEpochMilli(startDateLong)
  .atZone(ZoneId.systemDefault())
  .toLocalDate();

Use own username/password with git and bitbucket

I figured I should share my solution, since I wasn't able to find it anywhere, and only figured it out through trial and error.

I indeed was able to transfer ownership of the repository to a team on BitBucket.

Don't add the remote URL that BitBuckets suggests:

git remote add origin https://[email protected]/teamName/repo.git

Instead, add the remote URL without your username:

git remote add origin https://bitbucket.org/teamName/repo.git

This way, when you go to pull from or push to a repo, it prompts you for your username, then for your password: everyone on the team has access to it under their own credentials. This approach only works with teams on BitBucket, even though you can manage user permissions on single-owner repos.

jQuery iframe load() event?

use iframe onload event

$('#theiframe').on("load", function() {
    alert(1);
});

How do I run Java .class files?

You need to set the classpath to find your compiled class:

java -cp C:\Users\Matt\workspace\HelloWorld2\bin HelloWorld2

Get a random item from a JavaScript array

jQuery is JavaScript! It's just a JavaScript framework. So to find a random item, just use plain old JavaScript, for example,

var randomItem = items[Math.floor(Math.random()*items.length)]

How to trim a string to N chars in Javascript?

Why not just use substring... string.substring(0, 7); The first argument (0) is the starting point. The second argument (7) is the ending point (exclusive). More info here.

var string = "this is a string";
var length = 7;
var trimmedString = string.substring(0, length);

CSS: fixed to bottom and centered

There are 2 potential issues that I see:

1 - IE has had trouble with position:fixed in the past. If you are using IE7+ with a valid doctype or a non-IE browser this isn't part of the problem

2 - You need to specify a width for the footer if you want the footer object to be centered. Otherwise it defaults to the full width of the page and the auto margin for the left and right get set to 0. If you want the footer bar to take up the width (like the StackOverflow notice bar) and center the text, then you need to add "text-align: center" to your definition.

Git status ignore line endings / identical files / windows & linux environment / dropbox / mled

Try setting core.autocrlf value like this :

git config --global core.autocrlf true

How to show shadow around the linearlayout in Android?

Create a new XML by example named "shadow.xml" at DRAWABLE with the following code (you can modify it or find another better):

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/middle_grey"/>
        </shape>
    </item>

    <item android:left="2dp"
          android:right="2dp"
          android:bottom="2dp">
        <shape android:shape="rectangle">
            <solid android:color="@color/white"/>
        </shape>
    </item>

</layer-list>

After creating the XML in the LinearLayout or another Widget you want to create shade, you use the BACKGROUND property to see the efect. It would be something like :

<LinearLayout
    android:orientation="horizontal"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:paddingRight="@dimen/margin_med"
    android:background="@drawable/shadow"
    android:minHeight="?attr/actionBarSize"
    android:gravity="center_vertical">

How do JavaScript closures work?

A function in JavaScript is not just a reference to a set of instructions (as in C language), but it also includes a hidden data structure which is composed of references to all nonlocal variables it uses (captured variables). Such two-piece functions are called closures. Every function in JavaScript can be considered a closure.

Closures are functions with a state. It is somewhat similar to "this" in the sense that "this" also provides state for a function but function and "this" are separate objects ("this" is just a fancy parameter, and the only way to bind it permanently to a function is to create a closure). While "this" and function always live separately, a function cannot be separated from its closure and the language provides no means to access captured variables.

Because all these external variables referenced by a lexically nested function are actually local variables in the chain of its lexically enclosing functions (global variables can be assumed to be local variables of some root function), and every single execution of a function creates new instances of its local variables, it follows that every execution of a function returning (or otherwise transferring it out, such as registering it as a callback) a nested function creates a new closure (with its own potentially unique set of referenced nonlocal variables which represent its execution context).

Also, it must be understood that local variables in JavaScript are created not on the stack frame, but on the heap and destroyed only when no one is referencing them. When a function returns, references to its local variables are decremented, but they can still be non-null if during the current execution they became part of a closure and are still referenced by its lexically nested functions (which can happen only if the references to these nested functions were returned or otherwise transferred to some external code).

An example:

function foo (initValue) {
   //This variable is not destroyed when the foo function exits.
   //It is 'captured' by the two nested functions returned below.
   var value = initValue;

   //Note that the two returned functions are created right now.
   //If the foo function is called again, it will return
   //new functions referencing a different 'value' variable.
   return {
       getValue: function () { return value; },
       setValue: function (newValue) { value = newValue; }
   }
}

function bar () {
    //foo sets its local variable 'value' to 5 and returns an object with
    //two functions still referencing that local variable
    var obj = foo(5);

    //Extracting functions just to show that no 'this' is involved here
    var getValue = obj.getValue;
    var setValue = obj.setValue;

    alert(getValue()); //Displays 5
    setValue(10);
    alert(getValue()); //Displays 10

    //At this point getValue and setValue functions are destroyed
    //(in reality they are destroyed at the next iteration of the garbage collector).
    //The local variable 'value' in the foo is no longer referenced by
    //anything and is destroyed too.
}

bar();

Test method is inconclusive: Test wasn't run. Error?

In my case I had an error in my application configuration file app.config. I had misplaced appsettings above the configSections instead of placing it inside. So a corrupt configuration file could be the cause of Resharper not running your tests responding Inconclusive.

Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'

I had the same problem. This is related to hibernate. I changed the database from dev to production in hibernate.cfg.xml but there were catalog attribute in other hbm.xml files with the old database name and it was causing the issue.

Instead of telling incorrect database name, it showed Permission denied error.

So make sure to change the database name everywhere or just remove the catalog attribute

Differences between Emacs and Vim

A jaundiced point of view:

vi (not vim) is a professional necessity. You always have some form of vi easily available, no matter what the environment. You can be in vi when in emacs, you can be in vi to build bash commands in unix-land.

Even Microsquish has to support vi (although they do a good job of hiding it) because of gov't and corporate compliance with published standards.

In my opinion, if you are in a hands-on job in a busy environment--not a hothouse flower confined to one fancy rig in a development environment, or in academia--knowing a lot about a fancy editor is a job handicap. Don't learn all the fancy tricks in vim or emacs, and don't develop a bunch of macros to make the editing environment bend to your will. It's an enormous time sink that gets in your way when you attend to different machines that you probably can't justify in a factory environment.

Read Bill Joy's paper--it is a very competent, perhaps even beautiful, engineering exercise in editing plain text very, very fast. Parito's rule applies here: 80% of the fruit is in 20% of the baskets. Editing plain text very very fast is the crux of editing competence--all else is optional--and sometimes hurtful.

Ant if else condition?

You can also do this with ant contrib's if task.

<if>
    <equals arg1="${condition}" arg2="true"/>
    <then>
        <copy file="${some.dir}/file" todir="${another.dir}"/>
    </then>
    <elseif>
        <equals arg1="${condition}" arg2="false"/>
        <then>
            <copy file="${some.dir}/differentFile" todir="${another.dir}"/>
        </then>
    </elseif>
    <else>
        <echo message="Condition was neither true nor false"/>
    </else>
</if>

What is the difference between a "line feed" and a "carriage return"?

Both of these are primary from the old printing days.

Carriage return is from the days of the teletype printers/old typewriters, where literally the carriage would return to the next line, and push the paper up. This is what we now call \r.

Line feed LF signals the end of the line, it signals that the line has ended - but doesn't move the cursor to the next line. In other words, it doesn't "return" the cursor/printer head to the next line.

For more sundry details, the mighty wikipedia to the rescue.

How to customize the background color of a UITableViewCell?

Customizing the background of a table view cell eventually becomes and "all or nothing" approach. It's very difficult to change the color or image used for the background of a content cell in a way that doesn't look strange.

The reason is that the cell actually spans the width of the view. The rounded corners are just part of its drawing style and the content view sits in this area.

If you change the color of the content cell you will end up with white bits visible at the corners. If you change the color of the entire cell, you will have a block of color spanning the width of the view.

You can definitely customize a cell, but it's not quite as easy as you may think at first.

How do I share a global variable between c files?

Use the extern keyword to declare the variable in the other .c file. E.g.:

extern int counter;

means that the actual storage is located in another file. It can be used for both variables and function prototypes.

Call javascript from MVC controller action

You can call a controller action from a JavaScript function but not vice-versa. How would the server know which client to target? The server simply responds to requests.

An example of calling a controller action from JavaScript (using the jQuery JavaScript library) in the response sent to the client.

$.ajax({
           type: "POST",
           url: "/Controller/Action", // the URL of the controller action method
           data: null, // optional data
           success: function(result) {
                // do something with result
           },                
           error : function(req, status, error) {
                // do something with error   
           }
       });

The type initializer for 'CrystalDecisions.CrystalReports.Engine.ReportDocument' threw an exception

  1. Download cr redist 2005 or 2008(which is your tool) or copy from C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\BootStrapper\Packages\CrystalReports

  2. Download c++ redist 2005 or 2008(which is your tool)

  3. Install both and restart your system

  4. Problem solved.

Android offline documentation and sample codes

This thread is a little old, and I am brand new to this, but I think I found the preferred solution.

First, I assume that you are using Eclipse and the Android ADT plugin.

In Eclipse, choose Window/Android SDK Manager. In the display, expand the entry for the MOST RECENT PLATFORM, even if that is not the platform that your are developing for. As of Jan 2012, it is "Android 4.0.3 (API 15)". When expanded, the first entry is "Documentation for Android SDK" Click the checkbox next to it, and then click the "Install" button.

When done, you should have a new directory in your "android-sdks" called "doc". Look for "offline.html" in there. Since this is packaged with the most recent version, it will document the most recent platform, but it should also show the APIs for previous versions.

A url resource that is a dot (%2E)

It is not possible. §2.3 says that "." is an unreserved character and that "URIs that differ in the replacement of an unreserved character with its corresponding percent-encoded US-ASCII octet are equivalent". Therefore, /%2E%2E/ is the same as /../, and that will get normalized away.

(This is a combination of an answer by bobince and a comment by slowpoison.)

Case-insensitive string comparison in C++

I've had good experience using the International Components for Unicode libraries - they're extremely powerful, and provide methods for conversion, locale support, date and time rendering, case mapping (which you don't seem to want), and collation, which includes case- and accent-insensitive comparison (and more). I've only used the C++ version of the libraries, but they appear to have a Java version as well.

Methods exist to perform normalized compares as referred to by @Coincoin, and can even account for locale - for example (and this a sorting example, not strictly equality), traditionally in Spanish (in Spain), the letter combination "ll" sorts between "l" and "m", so "lz" < "ll" < "ma".

Get the element triggering an onclick event in jquery?

It's top google stackoverflow question, but all answers are not jQuery related!

$(".someclass").click(
    function(event)
    {
        console.log(event, this);
    }
);

'event' contains 2 important values:

event.currentTarget - element to which event is triggered ('.someclass' element)

event.target - element clicked (in case when inside '.someclass' [div] are other elements and you clicked on of them)

this - is set to triggered element ('.someclass'), but it's JavaScript element, not jQuery element, so if you want to use some jQuery function on it, you must first change it to jQuery element: $(this)

When your refresh the page and reload the scripts again; this method not work. You have to use jquery "unbind" method.

Generate random numbers with a given (numerical) distribution

Since Python 3.6, there's a solution for this in Python's standard library, namely random.choices.

Example usage: let's set up a population and weights matching those in the OP's question:

>>> from random import choices
>>> population = [1, 2, 3, 4, 5, 6]
>>> weights = [0.1, 0.05, 0.05, 0.2, 0.4, 0.2]

Now choices(population, weights) generates a single sample:

>>> choices(population, weights)
4

The optional keyword-only argument k allows one to request more than one sample at once. This is valuable because there's some preparatory work that random.choices has to do every time it's called, prior to generating any samples; by generating many samples at once, we only have to do that preparatory work once. Here we generate a million samples, and use collections.Counter to check that the distribution we get roughly matches the weights we gave.

>>> million_samples = choices(population, weights, k=10**6)
>>> from collections import Counter
>>> Counter(million_samples)
Counter({5: 399616, 6: 200387, 4: 200117, 1: 99636, 3: 50219, 2: 50025})

Pushing from local repository to GitHub hosted remote

This worked for my GIT version 1.8.4:

  1. From the local repository folder, right click and select 'Git Commit Tool'.
  2. There, select the files you want to upload, under 'Unstaged Changes' and click 'Stage Changed' button. (You can initially click on 'Rescan' button to check what files are modified and not uploaded yet.)
  3. Write a Commit Message and click 'Commit' button.
  4. Now right click in the folder again and select 'Git Bash'.
  5. Type: git push origin master and enter your credentials. Done.

How to refresh a Page using react-route Link

If you just put '/' in the href it will reload the current window.

_x000D_
_x000D_
<a href="/">
  Reload the page
</a>
_x000D_
_x000D_
_x000D_

How can I open an Excel file in Python?

import pandas as pd 
import os 
files = os.listdir('path/to/files/directory/')
desiredFile = files[i]
filePath = 'path/to/files/directory/%s'
Ofile = filePath % desiredFile
xls_import = pd.read_csv(Ofile)

Now you can use the power of pandas DataFrames!

Cannot set property 'display' of undefined

document.getElementsByClassName('btn-pageMenu') delivers a nodeList. You should use: document.getElementsByClassName('btn-pageMenu')[0].style.display (if it's the first element from that list you want to change.

If you want to change style.display for all nodes loop through the list:

var elems = document.getElementsByClassName('btn-pageMenu');
for (var i=0;i<elems.length;i+=1){
  elems[i].style.display = 'block';
}

to be complete: if you use jquery it is as simple as:

?$('.btn-pageMenu').css('display'???????????????????????????,'block');??????

On logout, clear Activity history stack, preventing "back" button from opening logged-in-only Activities

It seems a rite of passage that a new Android programmer spends a day researching this issue and reading all of these StackOverflow threads. I am now newly initiated and I leave here trace of my humble experience to help a future pilgrim.

First, there is no obvious or immediate way to do this per my research (as of September 2012). You'd think you could simple startActivity(new Intent(this, LoginActivity.class), CLEAR_STACK) but no.

You CAN do startActivity(new Intent(this, LoginActivity.class)) with FLAG_ACTIVITY_CLEAR_TOP - and this will cause the framework to search down the stack, find your earlier original instance of LoginActivity, recreate it and clear the rest of the (upwards) stack. And since Login is presumably at the bottom of the stack, you now have an empty stack and the Back button just exits the application.

BUT - this only works if you previously left that original instance of LoginActivity alive at the base of your stack. If, like many programmers, you chose to finish() that LoginActivity once the user has successfully logged in, then it's no longer on the base of the stack and the FLAG_ACTIVITY_CLEAR_TOP semantics do not apply ... you end up creating a new LoginActivity on top of the existing stack. Which is almost certainly NOT what you want (weird behavior where the user can 'back' their way out of login into a previous screen).

So if you have previously finish()'d the LoginActivity, you need to pursue some mechanism for clearing your stack and then starting a new LoginActivity. It seems like the answer by @doreamon in this thread is the best solution (at least to my humble eye):

https://stackoverflow.com/a/9580057/614880

I strongly suspect that the tricky implications of whether you leave LoginActivity alive are causing a lot of this confusion.

Good Luck.

Difference between JSON.stringify and JSON.parse

JSON.stringify(obj [, replacer [, space]]) - Takes any serializable object and returns the JSON representation as a string.

JSON.parse(string) - Takes a well formed JSON string and returns the corresponding JavaScript object.

Vertical Menu in Bootstrap

With Bootstrap 2.0 you can give your tabs the "stackable" class, which makes them stack vertically.

Loop through an array of strings in Bash?

Simple way :

arr=("sharlock"  "bomkesh"  "feluda" )  ##declare array

len=${#arr[*]}  # it returns the array length

#iterate with while loop
i=0
while [ $i -lt $len ]
do
    echo ${arr[$i]}
    i=$((i+1))
done


#iterate with for loop
for i in $arr
do
  echo $i
done

#iterate with splice
 echo ${arr[@]:0:3}

What ports does RabbitMQ use?

What ports is RabbitMQ using?

Default: 5672, the manual has the answer. It's defined in the RABBITMQ_NODE_PORT variable.

https://www.rabbitmq.com/configure.html#define-environment-variables

The number might be differently if changed by someone in the rabbitmq configuration file:

vi /etc/rabbitmq/rabbitmq-env.conf

Ask the computer to tell you:

sudo nmap -p 1-65535 localhost

Starting Nmap 5.51 ( http://nmap.org ) at 2014-09-19 13:50 EDT
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00041s latency).
PORT      STATE         SERVICE
443/tcp   open          https
5672/tcp  open          amqp
15672/tcp open  unknown
35102/tcp open  unknown
59440/tcp open  unknown

Oh look, 5672, and 15672

Use netstat:

netstat -lntu
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State
tcp        0      0 0.0.0.0:15672               0.0.0.0:*                   LISTEN
tcp        0      0 0.0.0.0:55672               0.0.0.0:*                   LISTEN
tcp        0      0 :::5672                     :::*                        LISTEN

Oh look 5672.

use lsof:

eric@dev ~$ sudo lsof -i | grep beam
beam.smp  21216    rabbitmq   17u  IPv4 33148214      0t0  TCP *:55672 (LISTEN)
beam.smp  21216    rabbitmq   18u  IPv4 33148219      0t0  TCP *:15672 (LISTEN)

use nmap from a different machine, find out if 5672 is open:

sudo nmap -p 5672 10.0.1.71
Starting Nmap 5.51 ( http://nmap.org ) at 2014-09-19 13:19 EDT
Nmap scan report for 10.0.1.71
Host is up (0.00011s latency).
PORT     STATE SERVICE
5672/tcp open  amqp
MAC Address: 0A:40:0E:8C:75:6C (Unknown)    
Nmap done: 1 IP address (1 host up) scanned in 0.13 seconds

Try to connect to a port manually with telnet, 5671 is CLOSED:

telnet localhost 5671
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused

Try to connect to a port manually with telnet, 5672 is OPEN:

telnet localhost 5672
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.

Check your firewall:

sudo cat /etc/sysconfig/iptables  

It should tell you what ports are made open:

-A INPUT -p tcp -m tcp --dport 5672 -j ACCEPT

Reapply your firewall:

sudo service iptables restart
iptables: Setting chains to policy ACCEPT: filter          [  OK  ]
iptables: Flushing firewall rules:                         [  OK  ]
iptables: Unloading modules:                               [  OK  ]
iptables: Applying firewall rules:                         [  OK  ]

How do I convert a column of text URLs into active hyperlinks in Excel?

Pretty easy way for rather short lists:

  1. Double click on the box where the url is
  2. Enter

You have your link ;)

What to return if Spring MVC controller method doesn't return value?

You can return "ResponseEntity" object. Using "ResponseEntity" object is very convenient both at the time of constructing the response object (that contains Response Body and HTTP Status Code) and at the time of getting information out of the response object.

Methods like getHeaders(), getBody(), getContentType(), getStatusCode() etc makes the work of reading the ResponseEntity object very easy.

You should be using ResponseEntity object with a http status code of 204(No Content), which is specifically to specify that the request has been processed properly and the response body is intentionally blank. Using appropriate Status Codes to convey the right information is very important, especially if you are making an API that is going to be used by multiple client applications.

ThreeJS: Remove object from scene

THIS WORKS GREAT - I tested it so, please SET NAME for every object

give the name to the object upon creation

    mesh.name = 'nameMeshObject';

and use this if you have to delete an object

    delete3DOBJ('nameMeshObject');



    function delete3DOBJ(objName){
        var selectedObject = scene.getObjectByName(objName);
        scene.remove( selectedObject );
        animate();
    }

open a new scene , add object open new scene , add object

delete an object and create new delete object and create new

Tomcat Server Error - Port 8080 already in use

For Ubuntu users with the same problem (e.g. Eclipse crash during debug) do a netstat -a -p | grep 8095 (or any other port number if the Tomcat server), then kill -9 that process.

Applying a single font to an entire website with CSS

Ensure that mobile devices won't change the font with their default font by using important along with the universal selector * :

* { font-family: Algerian !important;}

.htaccess: Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

or defined by a module not included in the server configuration

Check to make sure you have mod_rewrite enabled.

From: https://webdevdoor.com/php/mod_rewrite-windows-apache-url-rewriting

  1. Find the httpd.conf file (usually you will find it in a folder called conf, config or something along those lines)
  2. Inside the httpd.conf file uncomment the line LoadModule rewrite_module modules/mod_rewrite.so (remove the pound '#' sign from in front of the line)
  3. Also find the line ClearModuleList is uncommented then find and make sure that the line AddModule mod_rewrite.c is not commented out.

If the LoadModule rewrite_module modules/mod_rewrite.so line is missing from the httpd.conf file entirely, just add it.

Sample command

To enable the module in a standard ubuntu do this:

a2enmod rewrite
systemctl restart apache2

Fixed digits after decimal with f-strings

Include the type specifier in your format expression:

>>> a = 10.1234
>>> f'{a:.2f}'
'10.12'

Java 8 stream map to list of keys sorted by values

Map<Integer, String> map = new HashMap<>();
map.put(1, "B");
map.put(2, "C");
map.put(3, "D");
map.put(4, "A");

List<String> list = map.values()
                       .stream()
                       .sorted()
                       .collect(Collectors.toList());

Output: [A, B, C, D]

You cannot call a method on a null-valued expression

The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5. From the comment you put this needed to be declared elsewhere in your code

$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider

The error was because you are trying to execute a method that does not exist.

PS C:\Users\Matt> $md5 | gm


   TypeName: System.Security.Cryptography.MD5CryptoServiceProvider

Name                       MemberType Definition                                                                                                                            
----                       ---------- ----------                                                                                                                            
Clear                      Method     void Clear()                                                                                                                          
ComputeHash                Method     byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...

The .ComputeHash() of $md5.ComputeHash() was the null valued expression. Typing in gibberish would create the same effect.

PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

PowerShell by default allows this to happen as defined its StrictMode

When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.

Compare data of two Excel Columns A & B, and show data of Column A that do not exist in B

All values of column A that are not present in column B will have a red background. Hope that it helps as starting point.

Sub highlight_missings()
Dim i As Long, lastA As Long, lastB As Long
Dim compare As Variant
Range("A:A").ClearFormats
lastA = Range("A65536").End(xlUp).Row
lastB = Range("B65536").End(xlUp).Row

For i = 2 To lastA
    compare = Application.Match(Range("a" & i), Range("B2:B" & lastB), 0)
        If IsError(compare) Then
            Range("A" & i).Interior.ColorIndex = 3
        End If
Next i
End Sub

MySQL LEFT JOIN 3 tables

Try this definitely work.

SELECT p.PersonID AS person_id,
   p.Name, p.SS, 
   f.FearID AS fear_id,
   f.Fear 
   FROM person_fear AS pf 
      LEFT JOIN persons AS p ON pf.PersonID = p.PersonID 
      LEFT JOIN fears AS f ON pf.PersonID = f.FearID 
   WHERE f.FearID = pf.FearID AND p.PersonID = pf.PersonID

Call a url from javascript

If you need to be checking external pages, you won't be able to get away with a pure javascript solution, since any requests to external URLs are blocked. You can get away with it by using JSONP, but that won't work unless the page you're requesting only serves up JSON.

You need to have a proxy on your own server to get the external links for you. This is actually rather simple with any server-side language.

<?php
$contents = file_get_contents($_GET['url']); // please do some sanitation here...
                                             // i'm just showing an example.
echo $contents;
?>

If you needed to check server response codes (eg: 404, 301, etc), then using a library such as cURL in your server-side script could retrieve that information and then pass it onto your javascript app.

Thinking about it now, there probably could be JSONP-enabled proxies out there for you to use, should the "setting up my own proxy" option not be viable.

Python sockets error TypeError: a bytes-like object is required, not 'str' with send function

You can change the send line to this:

c.send(b'Thank you for connecting')

The b makes it bytes instead.

check output from CalledProcessError

This will return true only if host responds to ping. Works on windows and linux

def ping(host):
    """
    Returns True if host (str) responds to a ping request.
    NB on windows ping returns true for success and host unreachable
    """
    param = '-n' if platform.system().lower()=='windows' else '-c'
    result = False
    try:
        out = subprocess.check_output(['ping', param, '1', host])
        #ping exit code 0
        if 'Reply from {}'.format(host) in str(out):
            result = True          
    except  subprocess.CalledProcessError:
        #ping exit code not 0
            result = False
    #print(str(out))
    return result

Using :after to clear floating elements

Write like this:

.wrapper:after {
    content: '';
    display: block;
    clear: both;
}

Check this http://jsfiddle.net/EyNnk/1/

How to find sum of multiple columns in a table in SQL Server 2005?

Another example using COALESCE. http://sqlmag.com/t-sql/coalesce-vs-isnull

SELECT (COALESCE(SUM(val1),0) + COALESCE(SUM(val2), 0)
+ COALESCE(SUM(val3), 0) + COALESCE(SUM(val4), 0)) AS 'TOTAL'
FROM Emp

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

Difference between == and ===

The difference between the loosely == equal operator and the strict === identical operator is exactly explained in the manual:

Comparison Operators

+----------------------------------------------------------------------------------+
¦ Example  ¦ Name      ¦ Result                                                    ¦
+----------+-----------+-----------------------------------------------------------¦
¦$a ==  $b ¦ Equal     ¦ TRUE if $a is equal to $b after type juggling.            ¦
¦$a === $b ¦ Identical ¦ TRUE if $a is equal to $b, and they are of the same type. ¦
+----------------------------------------------------------------------------------+

Loosely == equal comparison

If you are using the == operator, or any other comparison operator which uses loosely comparison such as !=, <> or ==, you always have to look at the context to see what, where and why something gets converted to understand what is going on.

Converting rules

Type comparison table

As reference and example you can see the comparison table in the manual:

Loose comparisons with ==

+-----------------------------------------------------------------------------------------------------------+
¦         ¦ TRUE  ¦ FALSE ¦   1   ¦   0   ¦  -1   ¦  "1"  ¦  "0"  ¦ "-1"  ¦ NULL  ¦ array() ¦ "php" ¦  ""   ¦
+---------+-------+-------+-------+-------+-------+-------+-------+-------+-------+---------+-------+-------¦
¦ TRUE    ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE   ¦ TRUE  ¦ FALSE ¦
¦ FALSE   ¦ FALSE ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ TRUE    ¦ FALSE ¦ TRUE  ¦
¦ 1       ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ 0       ¦ FALSE ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE   ¦ TRUE  ¦ TRUE  ¦
¦ -1      ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ "1"     ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ "0"     ¦ FALSE ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ "-1"    ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ NULL    ¦ FALSE ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ TRUE    ¦ FALSE ¦ TRUE  ¦
¦ array() ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ TRUE    ¦ FALSE ¦ FALSE ¦
¦ "php"   ¦ TRUE  ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ TRUE  ¦ FALSE ¦
¦ ""      ¦ FALSE ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE   ¦ FALSE ¦ TRUE  ¦
+-----------------------------------------------------------------------------------------------------------+

Strict === identical comparison

If you are using the === operator, or any other comparison operator which uses strict comparison such as !== or ===, then you can always be sure that the types won't magically change, because there will be no converting going on. So with strict comparison the type and value have to be the same, not only the value.

Type comparison table

As reference and example you can see the comparison table in the manual:

Strict comparisons with ===

+-----------------------------------------------------------------------------------------------------------+
¦         ¦ TRUE  ¦ FALSE ¦   1   ¦   0   ¦  -1   ¦  "1"  ¦  "0"  ¦ "-1"  ¦ NULL  ¦ array() ¦ "php" ¦  ""   ¦
+---------+-------+-------+-------+-------+-------+-------+-------+-------+-------+---------+-------+-------¦
¦ TRUE    ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ FALSE   ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ 1       ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ 0       ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ -1      ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ "1"     ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ "0"     ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ "-1"    ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ NULL    ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ array() ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE    ¦ FALSE ¦ FALSE ¦
¦ "php"   ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ TRUE  ¦ FALSE ¦
¦ ""      ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ TRUE  ¦
+-----------------------------------------------------------------------------------------------------------+

jQuery issue - #<an Object> has no method

This problem can also arise if you include jQuery more than once.

Messages Using Command prompt in Windows 7

You can use the net send command to send a message over a network.

example:

net send * How Are You

you can use the above statement to send a message to all members of your domain.But if you want to send a message to a single user named Mike, you can use

 net send mike hello!

this will send hello! to the user named Mike.

How to replace multiple substrings of a string?

Here is another way of doing it with a dictionary:

listA="The cat jumped over the house".split()
modify = {word:word for number,word in enumerate(listA)}
modify["cat"],modify["jumped"]="dog","walked"
print " ".join(modify[x] for x in listA)

javac : command not found

You have installed the Java Runtime Environment(JRE) but it doesn't contain javac.

So on the terminal get access to the root user sudo -i and enter the password. Type yum install java-devel, hence it will install packages of javac in fedora.

Google Maps: how to get country, state/province/region, city given a lat/long value?

I found the GeoCoder javascript a little buggy when I included it in my jsp files.

You can also try this:



    var lat = "43.7667855" ;
    var long = "-79.2157321" ;
    var url = "https://maps.googleapis.com/maps/api/geocode/json?latlng="
       +lat+","+long+"&sensor=false";
    $.get(url).success(function(data) {
       var loc1 = data.results[0];
       var county, city;
         $.each(loc1, function(k1,v1) {
            if (k1 == "address_components") {
               for (var i = 0; i < v1.length; i++) {
                  for (k2 in v1[i]) {
                     if (k2 == "types") {
                        var types = v1[i][k2];
                        if (types[0] =="sublocality_level_1") {
                            county = v1[i].long_name;
                            //alert ("county: " + county);
                        } 
                        if (types[0] =="locality") {
                           city = v1[i].long_name;
                           //alert ("city: " + city);
                       } 
                     }

                  }          

               }

            }

         });
         $('#city').html(city); 
    }); 

Why do I get TypeError: can't multiply sequence by non-int of type 'float'?

raw_input returns a string (a sequence of characters). In Python, multiplying a string and a float makes no defined meaning (while multiplying a string and an integer has a meaning: "AB" * 3 is "ABABAB"; how much is "L" * 3.14 ? Please do not reply "LLL|"). You need to parse the string to a numerical value.

You might want to try:

salesAmount = float(raw_input("Insert sale amount here\n"))

Row count where data exists

I found this method on http://www.mrexcel.com/

This computes the number of non-blank cells in column A of worksheet named "Data"

With Worksheets("Data")
  Ndt =Application.Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count
  debug.print Ndt
End With

The result is printed to the immediate window. You need to subtract 1 (or more) if column A has a header line (or lines) you do not wish to count.

How to convert a currency string to a double with jQuery or Javascript?

This example run ok

_x000D_
_x000D_
var currency = "$1,123,456.00";
var number = Number(currency.replace(/[^0-9\.]+/g,""));
console.log(number);
_x000D_
_x000D_
_x000D_

How to find cube root using Python?

You could use x ** (1. / 3) to compute the (floating-point) cube root of x.

The slight subtlety here is that this works differently for negative numbers in Python 2 and 3. The following code, however, handles that:

def is_perfect_cube(x):
    x = abs(x)
    return int(round(x ** (1. / 3))) ** 3 == x

print(is_perfect_cube(63))
print(is_perfect_cube(64))
print(is_perfect_cube(65))
print(is_perfect_cube(-63))
print(is_perfect_cube(-64))
print(is_perfect_cube(-65))
print(is_perfect_cube(2146689000)) # no other currently posted solution
                                   # handles this correctly

This takes the cube root of x, rounds it to the nearest integer, raises to the third power, and finally checks whether the result equals x.

The reason to take the absolute value is to make the code work correctly for negative numbers across Python versions (Python 2 and 3 treat raising negative numbers to fractional powers differently).

jQuery posting JSON

'data' should be a stringified JavaScript object:

data: JSON.stringify({ "userName": userName, "password" : password })

To send your formData, pass it to stringify:

data: JSON.stringify(formData)

Some servers also require the application/json content type:

contentType: 'application/json'

There's also a more detailed answer to a similar question here: Jquery Ajax Posting json to webservice

executing a function in sql plus

One option would be:

SET SERVEROUTPUT ON

EXEC DBMS_OUTPUT.PUT_LINE(your_fn_name(your_fn_arguments));

How can I SELECT multiple columns within a CASE WHEN on SQL Server?

No, CASE is a function, and can only return a single value. I think you are going to have to duplicate your CASE logic.

The other option would be to wrap the whole query with an IF and have two separate queries to return results. Without seeing the rest of the query, it's hard to say if that would work for you.

Plot size and resolution with R markdown, knitr, pandoc, beamer

Figure sizes are specified in inches and can be included as a global option of the document output format. For example:

---
title: "My Document"
output:
  html_document:
    fig_width: 6
    fig_height: 4
---

And the plot's size in the graphic device can be increased at the chunk level:

```{r, fig.width=14, fig.height=12}          #Expand the plot width to 14 inches

ggplot(aes(x=mycolumn1, y=mycolumn2)) +     #specify the x and y aesthetic
geom_line(size=2) +                         #makes the line thicker
theme_grey(base_size = 25)                  #increases the size of the font
```

You can also use the out.width and out.height arguments to directly define the size of the plot in the output file:

```{r, out.width="200px", out.height="200px"} #Expand the plot width to 200 pixels

ggplot(aes(x=mycolumn1, y=mycolumn2)) +     #specify the x and y aesthetic
geom_line(size=2) +                         #makes the line thicker
theme_grey(base_size = 25)                  #increases the size of the font
```

Reading from stdin

You can do something like this to read 10 bytes:

char buffer[10];
read(STDIN_FILENO, buffer, 10);

remember read() doesn't add '\0' to terminate to make it string (just gives raw buffer).

To read 1 byte at a time:

char ch;
while(read(STDIN_FILENO, &ch, 1) > 0)
{
 //do stuff
}

and don't forget to #include <unistd.h>, STDIN_FILENO defined as macro in this file.

There are three standard POSIX file descriptors, corresponding to the three standard streams, which presumably every process should expect to have:

Integer value   Name
       0        Standard input (stdin)
       1        Standard output (stdout)
       2        Standard error (stderr)

So instead STDIN_FILENO you can use 0.

Edit:
In Linux System you can find this using following command:

$ sudo grep 'STDIN_FILENO' /usr/include/* -R | grep 'define'
/usr/include/unistd.h:#define   STDIN_FILENO    0   /* Standard input.  */

Notice the comment /* Standard input. */

Get JSON Data from URL Using Android?

Easy way to get JSON especially for Android SDK 23:

public class MainActivity extends AppCompatActivity {

Button btnHit;
TextView txtJson;
ProgressDialog pd;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnHit = (Button) findViewById(R.id.btnHit);
    txtJson = (TextView) findViewById(R.id.tvJsonItem);

    btnHit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new JsonTask().execute("Url address here");
        }
    });


}


private class JsonTask extends AsyncTask<String, String, String> {

    protected void onPreExecute() {
        super.onPreExecute();

        pd = new ProgressDialog(MainActivity.this);
        pd.setMessage("Please wait");
        pd.setCancelable(false);
        pd.show();
    }

    protected String doInBackground(String... params) {


        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();


            InputStream stream = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();
            String line = "";

            while ((line = reader.readLine()) != null) {
                buffer.append(line+"\n");
                Log.d("Response: ", "> " + line);   //here u ll get whole response...... :-) 

            }

            return buffer.toString();


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (pd.isShowing()){
            pd.dismiss();
        }
        txtJson.setText(result);
    }
}
}

Change route params without reloading in Angular 2

In my case I needed to remove a query param of the url to prevent user to see it.

I found replaceState safer than location.go because the path with the old query params disappeared of the stack and user can be redo the query related with this query. So, I prefer it to do it:

this.location.replaceState(this.router.url.split('?')[0]);

Whit location.go, go to back with the browser will return to your old path with the query params and will keep it in the navigation stack.

this.location.go(this.router.url.split('?')[0]);

Response Buffer Limit Exceeded

I faced the same kind of issue, my IIS version is 8.5. Increased the Response Buffering Limit under the ASP -> Limit Properties solved the issue.

  1. In IIS 8.5, select your project, you can see the options in the right hand side. In that under the IIS, you can see the ASP option.

ASP option

  1. In the option window increase the Response Buffering Limit to 40194304 (approximately 40 MB) .

Increase buffer limit

  1. Navigate away from the option, in the right hand side top you can see the Actions menu, Select Apply. It solved my problem.

Apply settings

pip install returning invalid syntax

In windows, you have to run pip install command from( python path)/ scripts path in cmd prompt

C:/python27/scripts

pip install pandas

Getting the Facebook like/share count for a given URL

For latest 2.1 Graph API, an example to get likes for imdb.com will be

Using this to get the id https://developers.facebook.com/tools/explorer/?method=GET&path=%3Fid%3Dhttp%253A%252F%252Fwww.imdb.com%3Ffields%3Dlikes&version=v2.1

and then get the likes

https://developers.facebook.com/tools/explorer/?method=GET&path=414652589771%2Flikes&version=v2.1

Document

URL /?id={url}

Represents an external URL as it relates to the Facebook social graph - shares and comments from the URL on Facebook, and any Open Graph objects associated with the URL.

Reference http://harshtechtalk.com/how-get-likes-count-posts-comments-facebook-graph-api/

How to change the default port of mysql from 3306 to 3360

Actually, you can just run the service using /mysqld --PORT 1234, it would force mysql to run on the specified port without change the cnf/ini file.

I just cought a case that cnf didn't work. It was weired... so I just use the cmd line as the shortcut and it works!

Ascii/Hex convert in bash

$> printf "%x%x\n" "'A" "'a"
4161

jQuery Selector: Id Ends With?

An example: to select all <a>s with ID ending in _edit:

jQuery("a[id$=_edit]")

or

jQuery("a[id$='_edit']")

How should I unit test multithreaded code?

I've done a lot of this, and yes it sucks.

Some tips:

  • GroboUtils for running multiple test threads
  • alphaWorks ConTest to instrument classes to cause interleavings to vary between iterations
  • Create a throwable field and check it in tearDown (see Listing 1). If you catch a bad exception in another thread, just assign it to throwable.
  • I created the utils class in Listing 2 and have found it invaluable, especially waitForVerify and waitForCondition, which will greatly increase the performance of your tests.
  • Make good use of AtomicBoolean in your tests. It is thread safe, and you'll often need a final reference type to store values from callback classes and suchlike. See example in Listing 3.
  • Make sure to always give your test a timeout (e.g., @Test(timeout=60*1000)), as concurrency tests can sometimes hang forever when they're broken.

Listing 1:

@After
public void tearDown() {
    if ( throwable != null )
        throw throwable;
}

Listing 2:

import static org.junit.Assert.fail;
import java.io.File;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Random;
import org.apache.commons.collections.Closure;
import org.apache.commons.collections.Predicate;
import org.apache.commons.lang.time.StopWatch;
import org.easymock.EasyMock;
import org.easymock.classextension.internal.ClassExtensionHelper;
import static org.easymock.classextension.EasyMock.*;

import ca.digitalrapids.io.DRFileUtils;

/**
 * Various utilities for testing
 */
public abstract class DRTestUtils
{
    static private Random random = new Random();

/** Calls {@link #waitForCondition(Integer, Integer, Predicate, String)} with
 * default max wait and check period values.
 */
static public void waitForCondition(Predicate predicate, String errorMessage) 
    throws Throwable
{
    waitForCondition(null, null, predicate, errorMessage);
}

/** Blocks until a condition is true, throwing an {@link AssertionError} if
 * it does not become true during a given max time.
 * @param maxWait_ms max time to wait for true condition. Optional; defaults
 * to 30 * 1000 ms (30 seconds).
 * @param checkPeriod_ms period at which to try the condition. Optional; defaults
 * to 100 ms.
 * @param predicate the condition
 * @param errorMessage message use in the {@link AssertionError}
 * @throws Throwable on {@link AssertionError} or any other exception/error
 */
static public void waitForCondition(Integer maxWait_ms, Integer checkPeriod_ms, 
    Predicate predicate, String errorMessage) throws Throwable 
{
    waitForCondition(maxWait_ms, checkPeriod_ms, predicate, new Closure() {
        public void execute(Object errorMessage)
        {
            fail((String)errorMessage);
        }
    }, errorMessage);
}

/** Blocks until a condition is true, running a closure if
 * it does not become true during a given max time.
 * @param maxWait_ms max time to wait for true condition. Optional; defaults
 * to 30 * 1000 ms (30 seconds).
 * @param checkPeriod_ms period at which to try the condition. Optional; defaults
 * to 100 ms.
 * @param predicate the condition
 * @param closure closure to run
 * @param argument argument for closure
 * @throws Throwable on {@link AssertionError} or any other exception/error
 */
static public void waitForCondition(Integer maxWait_ms, Integer checkPeriod_ms, 
    Predicate predicate, Closure closure, Object argument) throws Throwable 
{
    if ( maxWait_ms == null )
        maxWait_ms = 30 * 1000;
    if ( checkPeriod_ms == null )
        checkPeriod_ms = 100;
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    while ( !predicate.evaluate(null) ) {
        Thread.sleep(checkPeriod_ms);
        if ( stopWatch.getTime() > maxWait_ms ) {
            closure.execute(argument);
        }
    }
}

/** Calls {@link #waitForVerify(Integer, Object)} with <code>null</code>
 * for {@code maxWait_ms}
 */
static public void waitForVerify(Object easyMockProxy)
    throws Throwable
{
    waitForVerify(null, easyMockProxy);
}

/** Repeatedly calls {@link EasyMock#verify(Object[])} until it succeeds, or a
 * max wait time has elapsed.
 * @param maxWait_ms Max wait time. <code>null</code> defaults to 30s.
 * @param easyMockProxy Proxy to call verify on
 * @throws Throwable
 */
static public void waitForVerify(Integer maxWait_ms, Object easyMockProxy)
    throws Throwable
{
    if ( maxWait_ms == null )
        maxWait_ms = 30 * 1000;
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    for(;;) {
        try
        {
            verify(easyMockProxy);
            break;
        }
        catch (AssertionError e)
        {
            if ( stopWatch.getTime() > maxWait_ms )
                throw e;
            Thread.sleep(100);
        }
    }
}

/** Returns a path to a directory in the temp dir with the name of the given
 * class. This is useful for temporary test files.
 * @param aClass test class for which to create dir
 * @return the path
 */
static public String getTestDirPathForTestClass(Object object) 
{

    String filename = object instanceof Class ? 
        ((Class)object).getName() :
        object.getClass().getName();
    return DRFileUtils.getTempDir() + File.separator + 
        filename;
}

static public byte[] createRandomByteArray(int bytesLength)
{
    byte[] sourceBytes = new byte[bytesLength];
    random.nextBytes(sourceBytes);
    return sourceBytes;
}

/** Returns <code>true</code> if the given object is an EasyMock mock object 
 */
static public boolean isEasyMockMock(Object object) {
    try {
        InvocationHandler invocationHandler = Proxy
                .getInvocationHandler(object);
        return invocationHandler.getClass().getName().contains("easymock");
    } catch (IllegalArgumentException e) {
        return false;
    }
}
}

Listing 3:

@Test
public void testSomething() {
    final AtomicBoolean called = new AtomicBoolean(false);
    subject.setCallback(new SomeCallback() {
        public void callback(Object arg) {
            // check arg here
            called.set(true);
        }
    });
    subject.run();
    assertTrue(called.get());
}

Insert multiple lines into a file after specified pattern using shell script

This answer is easy to understand

  • Copy before the pattern
  • Add your lines
  • Copy after the pattern
  • Replace original file

    FILENAME='app/Providers/AuthServiceProvider.php'

STEP 1 copy until the pattern

sed '/THEPATTERNYOUARELOOKINGFOR/Q' $FILENAME >>${FILENAME}_temp

STEP 2 add your lines

cat << 'EOL' >> ${FILENAME}_temp

HERE YOU COPY AND
PASTE MULTIPLE
LINES, ALSO YOU CAN
//WRITE COMMENTS

AND NEW LINES
AND SPECIAL CHARS LIKE $THISONE

EOL

STEP 3 add the rest of the file

grep -A 9999 'THEPATTERNYOUARELOOKINGFOR' $FILENAME >>${FILENAME}_temp

REPLACE original file

mv ${FILENAME}_temp $FILENAME

if you need variables, in step 2 replace 'EOL' with EOL

cat << EOL >> ${FILENAME}_temp

this variable will expand: $variable1

EOL

How to use cURL to send Cookies?

You are using a wrong format in your cookie file. As curl documentation states, it uses an old Netscape cookie file format, which is different from the format used by web browsers. If you need to create a curl cookie file manually, this post should help you. In your example the file should contain following line

127.0.0.1   FALSE   /   FALSE   0   USER_TOKEN  in

having 7 TAB-separated fields meaning domain, tailmatch, path, secure, expires, name, value.

SAP Crystal Reports runtime for .Net 4.0 (64-bit)

SAP is notoriously bad at making these downloads available... or in an easily accessible location so hopefully this link still works by the time you read this answer.

< original link no longer active >

http://scn.sap.com/docs/DOC-7824 Updated Link 2/6/13:

https://wiki.scn.sap.com/wiki/display/BOBJ/Crystal+Reports%2C+Developer+for+Visual+Studio+Downloads - "Updated 10/31/2017"

http://www.crystalreports.com/crvs/confirm/ - "Updated 10/31/2017"

How to write data to a text file without overwriting the current data

First of all check if the filename already exists, If yes then create a file and close it at the same time then append your text using AppendAllText. For more info check the code below.


string FILE_NAME = "Log" + System.DateTime.Now.Ticks.ToString() + "." + "txt"; 
string str_Path = HostingEnvironment.ApplicationPhysicalPath + ("Log") + "\\" +FILE_NAME;


 if (!File.Exists(str_Path))
 {
     File.Create(str_Path).Close();
    File.AppendAllText(str_Path, jsonStream + Environment.NewLine);

 }
 else if (File.Exists(str_Path))
 {

     File.AppendAllText(str_Path, jsonStream + Environment.NewLine);

 }

Can scrapy be used to scrape dynamic content from websites that are using AJAX?

yes, Scrapy can scrap dynamic websites, website that are rendered through javaScript.

There are Two approaches to scrapy these kind of websites.

First,

you can use splash to render Javascript code and then parse the rendered HTML. you can find the doc and project here Scrapy splash, git

Second,

As everyone is stating, by monitoring the network calls, yes, you can find the api call that fetch the data and mock that call in your scrapy spider might help you to get desired data.

Adding a directory to PATH in Ubuntu

The file .bashrc is read when you start an interactive shell. This is the file that you should update. E.g:

export PATH=$PATH:/opt/ActiveTcl-8.5/bin

Restart the shell for the changes to take effect or source it, i.e.:

source .bashrc

How to read a file from jar in Java?

Ah, this is one of my favorite subjects. There are essentially two ways you can load a resource through the classpath:

Class.getResourceAsStream(resource)

and

ClassLoader.getResourceAsStream(resource)

(there are other ways which involve getting a URL for the resource in a similar fashion, then opening a connection to it, but these are the two direct ways).

The first method actually delegates to the second, after mangling the resource name. There are essentially two kinds of resource names: absolute (e.g. "/path/to/resource/resource") and relative (e.g. "resource"). Absolute paths start with "/".

Here's an example which should illustrate. Consider a class com.example.A. Consider two resources, one located at /com/example/nested, the other at /top, in the classpath. The following program shows nine possible ways to access the two resources:

package com.example;

public class A {

    public static void main(String args[]) {

        // Class.getResourceAsStream
        Object resource = A.class.getResourceAsStream("nested");
        System.out.println("1: A.class nested=" + resource);

        resource = A.class.getResourceAsStream("/com/example/nested");
        System.out.println("2: A.class /com/example/nested=" + resource);

        resource = A.class.getResourceAsStream("top");
        System.out.println("3: A.class top=" + resource);

        resource = A.class.getResourceAsStream("/top");
        System.out.println("4: A.class /top=" + resource);

        // ClassLoader.getResourceAsStream
        ClassLoader cl = A.class.getClassLoader();
        resource = cl.getResourceAsStream("nested");        
        System.out.println("5: cl nested=" + resource);

        resource = cl.getResourceAsStream("/com/example/nested");
        System.out.println("6: cl /com/example/nested=" + resource);
        resource = cl.getResourceAsStream("com/example/nested");
        System.out.println("7: cl com/example/nested=" + resource);

        resource = cl.getResourceAsStream("top");
        System.out.println("8: cl top=" + resource);

        resource = cl.getResourceAsStream("/top");
        System.out.println("9: cl /top=" + resource);
    }

}

The output from the program is:

1: A.class nested=java.io.BufferedInputStream@19821f
2: A.class /com/example/nested=java.io.BufferedInputStream@addbf1
3: A.class top=null
4: A.class /top=java.io.BufferedInputStream@42e816
5: cl nested=null
6: cl /com/example/nested=null
7: cl com/example/nested=java.io.BufferedInputStream@9304b1
8: cl top=java.io.BufferedInputStream@190d11
9: cl /top=null

Mostly things do what you'd expect. Case-3 fails because class relative resolving is with respect to the Class, so "top" means "/com/example/top", but "/top" means what it says.

Case-5 fails because classloader relative resolving is with respect to the classloader. But, unexpectedly Case-6 also fails: one might expect "/com/example/nested" to resolve properly. To access a nested resource through the classloader you need to use Case-7, i.e. the nested path is relative to the root of the classloader. Likewise Case-9 fails, but Case-8 passes.

Remember: for java.lang.Class, getResourceAsStream() does delegate to the classloader:

     public InputStream getResourceAsStream(String name) {
        name = resolveName(name);
        ClassLoader cl = getClassLoader0();
        if (cl==null) {
            // A system class.
            return ClassLoader.getSystemResourceAsStream(name);
        }
        return cl.getResourceAsStream(name);
    }

so it is the behavior of resolveName() that is important.

Finally, since it is the behavior of the classloader that loaded the class that essentially controls getResourceAsStream(), and the classloader is often a custom loader, then the resource-loading rules may be even more complex. e.g. for Web-Applications, load from WEB-INF/classes or WEB-INF/lib in the context of the web application, but not from other web-applications which are isolated. Also, well-behaved classloaders delegate to parents, so that duplicateed resources in the classpath may not be accessible using this mechanism.