Programs & Examples On #Gnu

This tag is for programming questions related to software and tools provided by the GNU ("GNU's Not Unix") project.

Passing additional variables from command line to make

The simplest way is:

make foo=bar target

Then in your makefile you can refer to $(foo). Note that this won't propagate to sub-makes automatically.

If you are using sub-makes, see this article: Communicating Variables to a Sub-make

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

You can also press = while less is open to just display (at the bottom of the screen) information about the current screen, including line numbers, with format:

myfile.txt lines 20530-20585/1816468 byte 1098945/116097872 1%  (press RETURN)

So here for example, the screen was currently showing lines 20530-20585, and the files has a total of 1816468 lines.

How do I syntax check a Bash script without running it?

sh  -n   script-name 

Run this. If there are any syntax errors in the script, then it returns the same error message. If there are no errors, then it comes out without giving any message. You can check immediately by using echo $?, which will return 0 confirming successful without any mistake.

It worked for me well. I ran on Linux OS, Bash Shell.

grep --ignore-case --only

If your grep -i does not work then try using tr command to convert the the output of your file to lower case and then pipe it into standard grep with whatever you are looking for. (it sounds complicated but the actual command which I have provided for you is not !).

Notice the tr command does not change the content of your original file, it just converts it just before it feeds it into grep.

1.here is how you can do this on a file

tr '[:upper:]' '[:lower:]' <your_file.txt|grep what_ever_you_are_searching_in_lower_case

2.or in your case if you are just echoing something

echo "ABC"|tr '[:upper:]' '[:lower:]' | grep abc

How do I apply a diff patch on Windows?

It appears that TortoiseSVN (TortoiseMerge) requires the line Index: foobar.py in the diff/patch file. This is what I needed to do to make a non-TortoiseSVN patch file work with TortoiseSVN's right-click Apply Patch command.

Before:

--- foobar.py.org   Sat May 08 16:00:56 2010
+++ foobar.py   Sat May 08 15:47:48 2010

After:

Index: foobar.py
===================================================================
--- foobar.py
+++ foobar.py   (working copy)

Or if you know the specific revision your contributor was working from:

Index: foobar.py
===================================================================
--- foobar.py   (revision 1157)
+++ foobar.py   (working copy)

grep regex whitespace behavior

This looks like a behavior difference in the handling of \s between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).

Note:

GNU grep 2.5.4
echo "foo bar" | grep "\s"
   (doesn't match)

whereas

GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar

Probably less trouble (as \s is not documented):

Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar

My advice is to avoid using \s ... use [ \t]* or [[:space:]] or something like it instead.

GnuPG: "decryption failed: secret key not available" error from gpg on Windows

You need to import not only your secret key, but also the corresponding public key, or you'll get this error.

Compiling a C++ program with gcc

gcc can actually compile c++ code just fine. The errors you received are linker errors, not compiler errors.

Odds are that if you change the compilation line to be this:

gcc info.C -lstdc++

which makes it link to the standard c++ library, then it will work just fine.

However, you should just make your life easier and use g++.


EDIT:

Rup says it best in his comment to another answer:

[...] gcc will select the correct back-end compiler based on file extension (i.e. will compile a .c as C and a .cc as C++) and links binaries against just the standard C and GCC helper libraries by default regardless of input languages; g++ will also select the correct back-end based on extension except that I think it compiles all C source as C++ instead (i.e. it compiles both .c and .cc as C++) and it includes libstdc++ in its link step regardless of input languages.

How to Export Private / Secret ASC Key to Decrypt GPG Files

See the treatment by Dark Otter

https://montemazuma.wordpress.com/2010/03/01/moving-a-gpg-key-privately/

If the site is down use reference the archive.org backup:

https://web.archive.org/web/20170518155052/https://montemazuma.wordpress.com/2010/03/01/moving-a-gpg-key-privately/

which includes a reasonably secure way to transfer keys. You could put that recommendation into shell-scripts shown below for repeated use.

First get the KEYID you want from the list shown by

$ gpg -K

From the resulting list note the KEYID (the 8 hexadecimals following sec) you need for transfer.

Then envoke the tested shell scipts "export_private_key" on the first account and generate your pubkey.gpg + keys.asc. Subsequently invoke on the second account "import_private_key". Here is their content shown with cat (copy & paste content):

$ cat export_private_key 
gpg -K
echo "select private key"
read KEYID
gpg --output pubkey.gpg --export $KEYID
echo REMEMBER THE COMING PASS-PHRASE
gpg --output - --export-secret-key $KEYID | \
   cat pubkey.gpg - | \
   gpg --armor --output keys.asc --symmetric --cipher-algo AES256
ls -l pubkey.gpg keys.asc
####################  E X P O R T _ P R I V A T E _ K E Y  #####################

Now tranfer by some means the "pubkey.gpg" (if needed) and the private "keys.asc" to the second account and envoke the below-shown program.

$ cat import_private_key 
gpg --no-use-agent --output - keys.asc | gpg --import
###################  I M P O R T _ P R I V A T E _ K E Y  ######################

In Otter's spirit "And that, should be, that".

gcc-arm-linux-gnueabi command not found

Its a bit counter-intuitive. The toolchain is called gcc-arm-linux-gnueabi. To invoke the tools execute the following: arm-linux-gnueabi-xxx

where xxx is gcc or ar or ld, etc

Comparing strings, c++

.compare() returns an integer, which is a measure of the difference between the two strings.

  • A return value of 0 indicates that the two strings compare as equal.
  • A positive value means that the compared string is longer, or the first non-matching character is greater.
  • A negative value means that the compared string is shorter, or the first non-matching character is lower.

operator== simply returns a boolean, indicating whether the strings are equal or not.

If you don't need the extra detail, you may as well just use ==.

Use Async/Await with Axios in React.js

In my experience over the past few months, I've realized that the best way to achieve this is:

class App extends React.Component{
  constructor(){
   super();
   this.state = {
    serverResponse: ''
   }
  }
  componentDidMount(){
     this.getData();
  }
  async getData(){
   const res = await axios.get('url-to-get-the-data');
   const { data } = await res;
   this.setState({serverResponse: data})
 }
 render(){
  return(
     <div>
       {this.state.serverResponse}
     </div>
  );
 }
}

If you are trying to make post request on events such as click, then call getData() function on the event and replace the content of it like so:

async getData(username, password){
 const res = await axios.post('url-to-post-the-data', {
   username,
   password
 });
 ...
}

Furthermore, if you are making any request when the component is about to load then simply replace async getData() with async componentDidMount() and change the render function like so:

render(){
 return (
  <div>{this.state.serverResponse}</div>
 )
}

fcntl substitute on Windows

The substitute of fcntl on windows are win32api calls. The usage is completely different. It is not some switch you can just flip.

In other words, porting a fcntl-heavy-user module to windows is not trivial. It requires you to analyze what exactly each fcntl call does and then find the equivalent win32api code, if any.

There's also the possibility that some code using fcntl has no windows equivalent, which would require you to change the module api and maybe the structure/paradigm of the program using the module you're porting.

If you provide more details about the fcntl calls people can find windows equivalents.

PHP - check if variable is undefined

You can use -

$isTouch = isset($variable);

It will return true if the $variable is defined. if the variable is not defined it will return false.

Note : Returns TRUE if var exists and has value other than NULL, FALSE otherwise.

If you want to check for false, 0 etc You can then use empty() -

$isTouch = empty($variable);

empty() works for -

  • "" (an empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a float)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • $var; (a variable declared, but without a value)

AngularJS sorting by property

It's pretty easy, just do it like this

$scope.props = [{order:"1"},{order:"5"},{order:"2"}]

ng-repeat="prop in props | orderBy:'order'"

Run/install/debug Android applications over Wi-Fi?

android Wireless Debugging (MAC)

step 1: go to sdk folder (common path "/Users/macname/Library/Android/sdk/platform-tools") open cmd here run "adb devices" output - List of devices attached

if adb command not found in cmd type ./adb --help OS X / macOS: typically ~/.profile or ~/.bash_profile Add the following line there and replace the path with the one where you installed platform-tools:

step 2: $ export PATH="/Users/macname/Library/Android/sdk/platform-tools":$PATH

step 3: $ adb devices List of devices attached ZH99FF7FTY device

step 4: $ adb tcpip 5555 restarting in TCP mode port: 5555

step 5: $ adb connect 10.124.32.18:5555 connected to 10.124.32.18:5555

Next Time repeat step 4 and 5 to reconnect Or if Device reboot and not connect follow step again BEST OF LUCK

java how to use classes in other package?

You have to provide the full path that you want to import.

import com.my.stuff.main.Main;
import com.my.stuff.second.*;

So, in your main class, you'd have:

package com.my.stuff.main

import com.my.stuff.second.Second;   // THIS IS THE IMPORTANT LINE FOR YOUR QUESTION

class Main {
   public static void main(String[] args) {
      Second second = new Second();
      second.x();  
   }
}

EDIT: adding example in response to Shawn D's comment

There is another alternative, as Shawn D points out, where you can specify the full package name of the object that you want to use. This is very useful in two locations. First, if you're using the class exactly once:

class Main {
    void function() {
        int x = my.package.heirarchy.Foo.aStaticMethod();

        another.package.heirarchy.Baz b = new another.package.heirarchy.Bax();
    }
}

Alternatively, this is useful when you want to differentiate between two classes with the same short name:

class Main {
    void function() {
        java.util.Date utilDate = ...;
        java.sql.Date sqlDate = ...;
    }
}

Setting default value for TypeScript object passed as argument

Here is something to try, using interface and destructuring with default values. Please note that "lastName" is optional.

interface IName {
  firstName: string
  lastName?: string
}

function sayName(params: IName) {
  const { firstName, lastName = "Smith" } = params
  const fullName = `${firstName} ${lastName}`

  console.log("FullName-> ", fullName)
}

sayName({ firstName: "Bob" })

Change the current directory from a Bash script

Basically we use cd.. to come back from every directory. I thought to make it more easy by giving the number of directories with which you need to come back at a time. You can implement this using a separate script file using the alias command . For example:

code.sh

#!/bin/sh
 _backfunc(){
 if [ "$1" -eq 1 ]; then
  cd ..
 elif [ "$1" -eq 2 ]; then
  cd ../..
 elif [ "$1" -eq 3 ]; then
  cd ../../..
 elif [ "$1" -eq 4 ]; then
  cd ../../../..
 elif ["$1" -eq 10]; then
  cd /home/arun/Documents/work
 fi
 }
alias back='_backfunc'   

After using source code.sh in the current shell you can use :

$back 2 

to come two steps back from the current directory. Explained in detail over here. It is also explained over there how to put the code in ~/.bashrc so that every new shell opened will automatically have this new alias command. You can add new command to go to specific directories by modifying the code by adding more if conditions and different arguments. You can also pull the code from git over here.

jQuery selector for the label of a checkbox

Another solution could be:

$("#comedyclubs").next()

VBA Macro to compare all cells of two Excel files

Do NOT loop through all cells!! There is a lot of overhead in communications between worksheets and VBA, for both reading and writing. Looping through all cells will be agonizingly slow. I'm talking hours.

Instead, load an entire sheet at once into a Variant array. In Excel 2003, this takes about 2 seconds (and 250 MB of RAM). Then you can loop through it in no time at all.

In Excel 2007 and later, sheets are about 1000 times larger (1048576 rows × 16384 columns = 17 billion cells, compared to 65536 rows × 256 columns = 17 million in Excel 2003). You will run into an "Out of memory" error if you try to load the whole sheet into a Variant; on my machine I can only load 32 million cells at once. So you have to limit yourself to the range you know has actual data in it, or load the sheet bit by bit, e.g. 30 columns at a time.

Option Explicit

Sub test()

    Dim varSheetA As Variant
    Dim varSheetB As Variant
    Dim strRangeToCheck As String
    Dim iRow As Long
    Dim iCol As Long

    strRangeToCheck = "A1:IV65536"
    ' If you know the data will only be in a smaller range, reduce the size of the ranges above.
    Debug.Print Now
    varSheetA = Worksheets("Sheet1").Range(strRangeToCheck)
    varSheetB = Worksheets("Sheet2").Range(strRangeToCheck) ' or whatever your other sheet is.
    Debug.Print Now

    For iRow = LBound(varSheetA, 1) To UBound(varSheetA, 1)
        For iCol = LBound(varSheetA, 2) To UBound(varSheetA, 2)
            If varSheetA(iRow, iCol) = varSheetB(iRow, iCol) Then
                ' Cells are identical.
                ' Do nothing.
            Else
                ' Cells are different.
                ' Code goes here for whatever it is you want to do.
            End If
        Next iCol
    Next iRow

End Sub

To compare to a sheet in a different workbook, open that workbook and get the sheet as follows:

Set wbkA = Workbooks.Open(filename:="C:\MyBook.xls")
Set varSheetA = wbkA.Worksheets("Sheet1") ' or whatever sheet you need

How to install crontab on Centos

As seen in Install crontab on CentOS, the crontab package in CentOS is vixie-cron. Hence, do install it with:

yum install vixie-cron

And then start it with:

service crond start

To make it persistent, so that it starts on boot, use:

chkconfig crond on

On CentOS 7 you need to use cronie:

yum install cronie

On CentOS 6 you can install vixie-cron, but the real package is cronie:

yum install vixie-cron

and

yum install cronie

In both cases you get the same output:

.../...
==================================================================
 Package         Arch       Version         Repository      Size
==================================================================
Installing:
 cronie          x86_64     1.4.4-12.el6    base             73 k
Installing for dependencies:
 cronie-anacron  x86_64     1.4.4-12.el6    base             30 k
 crontabs        noarch     1.10-33.el6     base             10 k
 exim            x86_64     4.72-6.el6      epel            1.2 M

Transaction Summary
==================================================================
Install       4 Package(s)

How to pass a PHP variable using the URL

In your link.php your echo statement must be like this:

echo '<a href="pass.php?link=' . $a . '>Link 1</a>';
echo '<a href="pass.php?link=' . $b . '">Link 2</a>';

Then in your pass.php you cannot use $a because it was not initialized with your intended string value.

You can directly compare it to a string like this:

if($_GET['link'] == 'Link1')

Another way is to initialize the variable first to the same thing you did with link.php. And, a much better way is to include the $a and $b variables in a single PHP file, then include that in all pages where you are going to use those variables as Tim Cooper mention on his post. You can also include this in a session.

How to format date with hours, minutes and seconds when using jQuery UI Datepicker?

This worked fine for me:

        $('#myelement').datetimepicker({
            dateFormat: "yy-mm-dd",
            timeFormat:  "hh:mm:ss"
        });

Convert array to JSON string in swift

How to convert array to json String in swift 2.3

var yourString : String = ""
do
{
    if let postData : NSData = try NSJSONSerialization.dataWithJSONObject(yourArray, options: NSJSONWritingOptions.PrettyPrinted)
    {
        yourString = NSString(data: postData, encoding: NSUTF8StringEncoding)! as String
    }
}
catch
{
    print(error)
}

And now you can use yourSting as JSON string..

Scanner is skipping nextLine() after using next() or nextFoo()?

I guess I'm pretty late to the party..

As previously stated, calling input.nextLine() after getting your int value will solve your problem. The reason why your code didn't work was because there was nothing else to store from your input (where you inputted the int) into string1. I'll just shed a little more light to the entire topic.

Consider nextLine() as the odd one out among the nextFoo() methods in the Scanner class. Let's take a quick example.. Let's say we have two lines of code like the ones below:

int firstNumber = input.nextInt();
int secondNumber = input.nextInt();

If we input the value below (as a single line of input)

54 234

The value of our firstNumber and secondNumber variable become 54 and 234 respectively. The reason why this works this way is because a new line feed (i.e \n) IS NOT automatically generated when the nextInt() method takes in the values. It simply takes the "next int" and moves on. This is the same for the rest of the nextFoo() methods except nextLine().

nextLine() generates a new line feed immediately after taking a value; this is what @RohitJain means by saying the new line feed is "consumed".

Lastly, the next() method simply takes the nearest String without generating a new line; this makes this the preferential method for taking separate Strings within the same single line.

I hope this helps.. Merry coding!

Get a UTC timestamp

As wizzard pointed out, the correct method is,

new Date().getTime();

or under Javascript 1.5, just

Date.now();

From the documentation,

The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00 UTC.

If you wanted to make a time stamp without milliseconds you can use,

Math.floor(Date.now() / 1000);

I wanted to make this an answer so the correct method is more visible.

You can compare ExpExc's and Narendra Yadala's results to the method above at http://jsfiddle.net/JamesFM/bxEJd/, and verify with http://www.unixtimestamp.com/ or by running date +%s on a Unix terminal.

How to correctly set Http Request Header in Angular 2

The simpler and current approach for adding header to a single request is:

// Step 1

const yourHeader: HttpHeaders = new HttpHeaders({
    Authorization: 'Bearer JWT-token'
});

// POST request

this.http.post(url, body, { headers: yourHeader });

// GET request

this.http.get(url, { headers: yourHeader });

TypeError: 'NoneType' object is not iterable in Python

Just continue the loop when you get None Exception,

example:

   a = None
   if a is None:
       continue
   else:
       print("do something")

This can be any iterable coming from DB or an excel file.

Git - Ignore files during merge

You could start by using git merge --no-commit, and then edit the merge however you like i.e. by unstaging config.xml or any other file, then commit. I suspect you'd want to automate it further after that using hooks, but I think it'd be worth going through manually at least once.

Multiple conditions with CASE statements

Another way based on amadan:

    SELECT * FROM [Purchasing].[Vendor] WHERE  

      ( (@url IS null OR @url = '' OR @url = 'ALL') and   PurchasingWebServiceURL LIKE '%')
    or

       ( @url = 'blank' and  PurchasingWebServiceURL = '')
    or
        (@url = 'fail' and  PurchasingWebServiceURL NOT LIKE '%treyresearch%')
    or( (@url not in ('fail','blank','','ALL') and @url is not null and 
          PurchasingWebServiceUrl Like '%'+@ur+'%') 
END

Difference between Fact table and Dimension table?

  1. The fact table mainly consists of business facts and foreign keys that refer to primary keys in the dimension tables. A dimension table consists mainly of descriptive attributes that are textual fields.
  2. A dimension table contains a surrogate key, natural key, and a set of attributes. On the contrary, a fact table contains a foreign key, measurements, and degenerated dimensions.
  3. Dimension tables provide descriptive or contextual information for the measurement of a fact table. On the other hand, fact tables provide the measurements of an enterprise.
  4. When comparing the size of the two tables, a fact table is bigger than a dimensional table. In a comparison table, more dimensions are presented than the fact tables. In a fact table, less numbers of facts are observed.
  5. The dimension table has to be loaded first. While loading the fact tables, one should have to look at the dimension table. This is because the fact table has measures, facts, and foreign keys that are the primary keys in the dimension table.

Read more: Dimension Table and Fact Table | Difference Between | Dimension Table vs Fact Table http://www.differencebetween.net/technology/hardware-technology/dimension-table-and-fact-table/#ixzz3SBp8kPzo

CodeIgniter Disallowed Key Characters

The problem is you are using characters not included in the standard Regex. Use this:

!preg_match("/^[a-z0-9\x{4e00}-\x{9fa5}\:\;\.\,\?\!\@\#\$%\^\*\"\~\'+=\\\ &_\/\.\[\]-\}\{]+$/iu", $str)

As per the comments (and personal experience) you should not modify they Input.php file — rather, you should create/use your own MY_Input.php as follows:

<?php

class MY_Input extends CI_Input {

    /**
     * Clean Keys
     *
     * This is a helper function. To prevent malicious users
     * from trying to exploit keys we make sure that keys are
     * only named with alpha-numeric text and a few other items.
     * 
     * Extended to allow: 
     *      - '.' (dot), 
     *      - '[' (open bracket),
     *      - ']' (close bracket)
     * 
     * @access  private
     * @param   string
     * @return  string
     */
    function _clean_input_keys($str) {
        // UPDATE: Now includes comprehensive Regex that can process escaped JSON
        if (!preg_match("/^[a-z0-9\:\;\.\,\?\!\@\#\$%\^\*\"\~\'+=\\\ &_\/\.\[\]-\}\{]+$/iu", $str)) {
            /**
             * Check for Development enviroment - Non-descriptive 
             * error so show me the string that caused the problem 
             */
            if (getenv('ENVIRONMENT') && getenv('ENVIRONMENT') == 'DEVELOPMENT') {
                var_dump($str);
            }
            exit('Disallowed Key Characters.');
        }

        // Clean UTF-8 if supported
        if (UTF8_ENABLED === TRUE) {
            $str = $this->uni->clean_string($str);
        }

        return $str;
    }

}

// /?/> /* Should never close php file - if you have a space after code, it can mess your life up */

++Chinese Character Support

// NOTE: \x{4e00}-\x{9fa5} = allow chinese characters
// NOTE: 'i' — case insensitive
// NOTE: 'u' — UTF-8 mode
if (!preg_match("/^[a-z0-9\x{4e00}-\x{9fa5}\:\;\.\,\?\!\@\#\$%\^\*\"\~\'+=\\\ &_\/\.\[\]-\}\{]+$/iu", $str) { ... }

// NOTE: When Chinese characters are provided in a URL, they are not 'really' there; the browser/OS
//   handles the copy/paste -> unicode conversion, eg:
//        ???  -->  xn--4gqsa60b   
//   'punycode' converts these codes according to RFC 3492 and RFC 5891.
//   https://github.com/bestiejs/punycode.js ---  $ bower install punycode

Input Type image submit form value?

An input type="image" only defines that image as the submit button and not as an input that can carry over a value to the server.

SQL Server 2008 Connection Error "No process is on the other end of the pipe"

Adding "user instance=False" to connection string solved the problem for me.

<connectionStrings>
  <add name="NorthwindEntities" connectionString="metadata=res://*/Models.Northwind.csdl|res://*/Models.Northwind.ssdl|res://*/Models.Northwind.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.\SQLEXPRESS2008R2;attachdbfilename=|DataDirectory|\Northwind.mdf;integrated security=True;user instance=False;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
</connectionStrings>

Plotting categorical data with pandas and matplotlib

You might find useful mosaic plot from statsmodels. Which can also give statistical highlighting for the variances.

from statsmodels.graphics.mosaicplot import mosaic
plt.rcParams['font.size'] = 16.0
mosaic(df, ['direction', 'colour']);

enter image description here

But beware of the 0 sized cell - they will cause problems with labels.

See this answer for details

Class constructor type in typescript?

Like that:

class Zoo {
    AnimalClass: typeof Animal;

    constructor(AnimalClass: typeof Animal ) {
        this.AnimalClass = AnimalClass
        let Hector = new AnimalClass();
    }
}

Or just:

class Zoo {
    constructor(public AnimalClass: typeof Animal ) {
        let Hector = new AnimalClass();
    }
}

typeof Class is the type of the class constructor. It's preferable to the custom constructor type declaration because it processes static class members properly.

Here's the relevant part of TypeScript docs. Search for the typeof. As a part of a TypeScript type annotation, it means "give me the type of the symbol called Animal" which is the type of the class constructor function in our case.

How to allow only a number (digits and decimal point) to be typed in an input?

Extending Adam Thomas answer you can easily make this directive more generic by adding input argument with custom regexp:

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

app.controller('MainCtrl', function($scope) {
});

app.directive('validInput', function() {
  return {
    require: '?ngModel',
    scope: {
      "inputPattern": '@'
    },
    link: function(scope, element, attrs, ngModelCtrl) {

      var regexp = null;

      if (scope.inputPattern !== undefined) {
        regexp = new RegExp(scope.inputPattern, "g");
      }

      if(!ngModelCtrl) {
        return;
      }

      ngModelCtrl.$parsers.push(function(val) {
        if (regexp) {
          var clean = val.replace(regexp, '');
          if (val !== clean) {
            ngModelCtrl.$setViewValue(clean);
            ngModelCtrl.$render();
          }
          return clean;
        }
        else {
          return val;
        }

      });

      element.bind('keypress', function(event) {
        if(event.keyCode === 32) {
          event.preventDefault();
        }
      });
    }
}});

HTML

<input type="text" ng-model="employee.age" valid-input  
       input-pattern="[^0-9]+" placeholder="Enter an age" />
</label>

Live on CodePen

Open URL in Java to get the content

String url_open ="http://javadl.sun.com/webapps/download/AutoDL?BundleId=76860";
java.awt.Desktop.getDesktop().browse(java.net.URI.create(url_open));

How to query first 10 rows and next time query other 10 rows from table

LIMIT limit OFFSET offset will work.

But you need a stable ORDER BY clause, or the values may be ordered differently for the next call (after any write on the table for instance).

SELECT *
FROM   msgtable
WHERE  cdate = '2012-07-18'
ORDER  BY msgtable_id  -- or whatever is stable 
LIMIT  10
OFFSET 50;  -- to skip to page 6

Use standard-conforming date style (ISO 8601 in my example), which works irregardless of your locale settings.

Paging will still shift if involved rows are inserted or deleted or changed in relevant columns. It has to.

To avoid that shift or for better performance with big tables use smarter paging strategies:

sub and gsub function?

That won't work if the string contains more than one match... try this:

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo "  $0) }'

or better (if the echo isn't a placeholder for something else):

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'

In your case you want to make a copy of the value before changing it:

echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'

Remove empty space before cells in UITableView

check for

if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
    [tableView setSeparatorInset:UIEdgeInsetsZero];
}
  • mention tableview delegate function cellForRowAtIndexPath:
  • it can handled both ios 6 and 7.

How to initialize static variables

In PHP 7.0.1, I was able to define this:

public static $kIdsByActions = array(
  MyClass1::kAction => 0,
  MyClass2::kAction => 1
);

And then use it like this:

MyClass::$kIdsByActions[$this->mAction];

mvn command not found in OSX Mavrerick

steps to install maven :

  1. download the maven file from http://maven.apache.org/download.cgi
  2. $tar xvf apache-maven-3.5.4-bin.tar.gz
  3. copy the apache folder to desired place $cp -R apache-maven-3.5.4 /Users/locals
  4. go to apache directory $cd /Users/locals/apache-maven-3.5.4/
  5. create .bash_profile $vim ~/.bash_profile
  6. write these two command : export M2_HOME=/Users/manisha/apache-maven-3.5.4 export PATH=$PATH:$M2_HOME/bin 7 save and quit the vim :wq!
  7. restart the terminal and type mvn -version

How does Access-Control-Allow-Origin header work?

The Access-Control-Allow-Origin response header indicates whether the response can be shared with requesting code from the given origin.

Header type Response       header
Forbidden header name      no

A response that tells the browser to allow code from any origin to access a resource will include the following:

Access-Control-Allow-Origin: *

For more info, visit here....

The activity must be exported or contain an intent-filter

Double check your manifest, your first activity should have tag

    <intent-filter>
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

inside of activity tag.

If that doesn't work, look for target build, which located in the left of run button (green-colored play button), it should be targeting "app" folder, not a particular activity. if it doesn't targeting "app", just click it and choose "app" from drop down list.

Hope it helps!

Node.js check if path is file or directory

The following should tell you. From the docs:

fs.lstatSync(path_string).isDirectory() 

Objects returned from fs.stat() and fs.lstat() are of this type.

stats.isFile()
stats.isDirectory()
stats.isBlockDevice()
stats.isCharacterDevice()
stats.isSymbolicLink() (only valid with fs.lstat())
stats.isFIFO()
stats.isSocket()

NOTE:

The above solution will throw an Error if; for ex, the file or directory doesn't exist.

If you want a true or false approach, try fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory(); as mentioned by Joseph in the comments below.

Delete many rows from a table using id in Mysql

The best way is to use IN statement :

DELETE from tablename WHERE id IN (1,2,3,...,254);

You can also use BETWEEN if you have consecutive IDs :

DELETE from tablename WHERE id BETWEEN 1 AND 254;

You can of course limit for some IDs using other WHERE clause :

DELETE from tablename WHERE id BETWEEN 1 AND 254 AND id<>10;

Deleting objects from an ArrayList in Java

You could iterate backwards and remove as you go through the ArrayList. This has the advantage of subsequent elements not needing to shift and is easier to program than moving forwards.

Alter table to modify default value of column

ALTER TABLE *table_name*
MODIFY *column_name* DEFAULT *value*;

worked in Oracle

e.g:

ALTER TABLE MY_TABLE
MODIFY MY_COLUMN DEFAULT 1;

Can I use Objective-C blocks as properties?

You can follow the format below and can use the testingObjectiveCBlock property in the class.

typedef void (^testingObjectiveCBlock)(NSString *errorMsg);

@interface MyClass : NSObject
@property (nonatomic, strong) testingObjectiveCBlock testingObjectiveCBlock;
@end

For more info have a look here

Can you call Directory.GetFiles() with multiple filters?

in .NET 2.0 (no Linq):

public static List<string> GetFilez(string path, System.IO.SearchOption opt,  params string[] patterns)
{
    List<string> filez = new List<string>();
    foreach (string pattern in patterns)
    {
        filez.AddRange(
            System.IO.Directory.GetFiles(path, pattern, opt)
        );
    }


    // filez.Sort(); // Optional
    return filez; // Optional: .ToArray()
}

Then use it:

foreach (string fn in GetFilez(path
                             , System.IO.SearchOption.AllDirectories
                             , "*.xml", "*.xml.rels", "*.rels"))
{}

JPA Native Query select and cast object

You might want to try one of the following ways:

  • Using the method createNativeQuery(sqlString, resultClass)

    Native queries can also be defined dynamically using the EntityManager.createNativeQuery() API.

    String sql = "SELECT USER.* FROM USER_ AS USER WHERE ID = ?";
    
    Query query = em.createNativeQuery(sql, User.class);
    query.setParameter(1, id);
    User user = (User) query.getSingleResult();
    
  • Using the annotation @NamedNativeQuery

    Native queries are defined through the @NamedNativeQuery and @NamedNativeQueries annotations, or <named-native-query> XML element.

    @NamedNativeQuery(
        name="complexQuery",
        query="SELECT USER.* FROM USER_ AS USER WHERE ID = ?",
        resultClass=User.class
    )
    public class User { ... }
    
    Query query = em.createNamedQuery("complexQuery", User.class);
    query.setParameter(1, id);
    User user = (User) query.getSingleResult();
    

You can read more in the excellent open book Java Persistence (available in PDF).

-------
NOTE: With regard to use of getSingleResult(), see Why you should never use getSingleResult() in JPA.

How to use Oracle's LISTAGG function with a unique filter?

select group_id, 
       listagg(name, ',') within group (order by name) as names
       over (partition by group_id)   
from demotable
group by group_id 

Notepad++ cached files location

I noticed it myself, and found the files inside the backup folder. You can check where it is using Menu:Settings -> Preferences -> Backup. Note : My NPP installation is portable, and on Windows, so YMMV.

Execute a shell script in current shell with sudo permission

I think you are confused about the difference between sourcing and executing a script.

Executing a script means creating a new process, and running the program. The program can be a shell script, or any other type of program. As it is a sub process, any environmental variables changed in the program will not affect the shell.

Sourcing a script can only be used with a bash script (if you are running bash). It effectively types the commands in as if you did them. This is useful as it lets a script change environmental variables in the shell.


Running a script is simple, you just type in the path to the script. . is the current directory. So ./script.sh will execute the file script.sh in the current directory. If the command is a single file (eg script.sh), it will check all the folders in the PATH variable to find the script. Note that the current directory isn't in PATH, so you can't execute a file script.sh in the current directory by running script.sh, you need to run ./script.sh (unless the current directory is in the PATH, eg you can run ls while in the /bin dir).

Sourcing a script doesn't use the PATH, and just searches for the path. Note that source isn't a program - otherwise it wouldn't be able to change environmental variables in the current shell. It is actually a bash built in command. Search /bin and /usr/bin - you won't find a source program there. So to source a file script.sh in the current directory, you just use source script.sh.


How does sudo interact with this? Well sudo takes a program, and executes it as root. Eg sudo ./script.sh executes script.sh in a sub process but running as root.

What does sudo source ./script.sh do however? Remember source isn't a program (rather a shell builtin)? Sudo expects a program name though, so it searches for a program named source. It doesn't find one, and so fails. It isn't possible to source a file running as root, without creating a new subprocess, as you cannot change the runner of a program (in this case, bash) after it has started.

I'm not sure what you actually wanted, but hopefully this will clear it up for you.


Here is a concrete example. Make the file script.sh in your current directory with the contents:

#!/bin/bash    
export NEW_VAR="hello"
whoami
echo "Some text"

Make it executable with chmod +x script.sh.

Now observe what happens with bash:

> ./script.sh
david
Some text
> echo $NEW_VAR

> sudo ./script.sh
root
Some text
> echo $NEW_VAR

> source script.sh
david
Some text
> echo $NEW_VAR
hello
> sudo source script.sh
sudo: source: command not found

Swipe to Delete and the "More" button (like in Mail app on iOS 7)

I have created a new library to implement swippable buttons which supports a variety of transitions and expandable buttons like iOS 8 mail app.

https://github.com/MortimerGoro/MGSwipeTableCell

This library is compatible with all the different ways to create a UITableViewCell and its tested on iOS 5, iOS 6, iOS 7 and iOS 8.

Here a sample of some transitions:

Border transition:

Border transition

Clip transition

Clip transition

3D Transition:

enter image description here

A Windows equivalent of the Unix tail command

I've used Tail For Windows. Certainly not as elegant as using

tail
but then, you're using Windows. ;)

How to grant permission to users for a directory using command line in Windows?

This is what worked for me:

  1. Manually open the folder for which the access is denied.

  2. Select the Executable/application file in that folder.

  3. Right-click on it and go to Properties -> Compatibility

  4. Now see the Privilege Level and check it for Run As Administrator

  5. Click on Change Settings for all users.

The problem is solved now.

Validating a Textbox field for only numeric input.

You may try the TryParse method which allows you to parse a string into an integer and return a boolean result indicating the success or failure of the operation.

int distance;
if (int.TryParse(txtEvDistance.Text, out distance))
{
    // it's a valid integer => you could use the distance variable here
}

How to round an average to 2 decimal places in PostgreSQL?

Error:function round(double precision, integer) does not exist

Solution: You need to addtype cast then it will work

Ex: round(extract(second from job_end_time_t)::integer,0)

How to write a stored procedure using phpmyadmin and how to use it through php?

I guess no one mentioned this so I will write it here. In phpMyAdmin 4.x, there is "Add Routine" link under "Routines" tab at the top row. This link opens a popup dialog where you can write your Stored procedure without worrying about delimiter or template.

enter image description here

Add Routine

enter image description here

Note that for simple test stored procedure, you may want to drop the default parameter which is already given or you can simply set it with a value.

Can comments be used in JSON?

JSON does not support comments natively, but you can make your own decoder or at least preprocessor to strip out comments, that's perfectly fine (as long as you just ignore comments and don't use them to guide how your application should process the JSON data).

JSON does not have comments. A JSON encoder MUST NOT output comments. A JSON decoder MAY accept and ignore comments.

Comments should never be used to transmit anything meaningful. That is what JSON is for.

Cf: Douglas Crockford, author of JSON spec.

Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clause

Yes, that is supported.

Check the documentation provided here for the supported keywords inside method names.

You can just define the method in the repository interface without using the @Query annotation and writing your custom query. In your case it would be as followed:

List<Inventory> findByIdIn(List<Long> ids);

I assume that you have the Inventory entity and the InventoryRepository interface. The code in your case should look like this:

The Entity

@Entity
public class Inventory implements Serializable {

  private static final long serialVersionUID = 1L;

  private Long id;

  // other fields
  // getters/setters

}

The Repository

@Repository
@Transactional
public interface InventoryRepository extends PagingAndSortingRepository<Inventory, Long> {

  List<Inventory> findByIdIn(List<Long> ids);

}

Change the Theme in Jupyter Notebook?

After I changed the theme it behaved strangely. The font size was small, cannot see the toolbar and I really didn't like the new look.

For those who want to restore the original theme, you can do it as follows:

jt -r

You need to restart Jupyter the first time you do it and later refresh is enough to enable the new theme.

or directly from inside the notebook

!jt -r

How to get the pure text without HTML element using JavaScript?

This works for me compiled based on what was said here with a more modern standard. This works best for multiple looks up.

let element = document.querySelectorAll('.myClass')
  element.forEach(item => {
    console.log(item.innerHTML = item.innerText || item.textContent)
  })

How to run batch file from network share without "UNC path are not supported" message?

Basically, you can't run it from a UNC path without seeing that message.

What I usually do is just put a CLS at the top of the script so I don't have to see that message. Then, specify the full path to files in the network share that you need to use.

How to remove html special chars?

A plain vanilla strings way to do it without engaging the preg regex engine:

function remEntities($str) {
  if(substr_count($str, '&') && substr_count($str, ';')) {
    // Find amper
    $amp_pos = strpos($str, '&');
    //Find the ;
    $semi_pos = strpos($str, ';');
    // Only if the ; is after the &
    if($semi_pos > $amp_pos) {
      //is a HTML entity, try to remove
      $tmp = substr($str, 0, $amp_pos);
      $tmp = $tmp. substr($str, $semi_pos + 1, strlen($str));
      $str = $tmp;
      //Has another entity in it?
      if(substr_count($str, '&') && substr_count($str, ';'))
        $str = remEntities($tmp);
    }
  }
  return $str;
}

How do I debug a stand-alone VBScript script?

Click the mse7.exe installed along with Office typically at \Program Files\Microsoft Office\OFFICE11.

This will open up the debugger, open the file and then run the debugger in the GUI mode.

Python requests library how to pass Authorization header with single token

This worked for me:

r = requests.get('http://127.0.0.1:8000/api/ray/musics/', headers={'Authorization': 'Token 22ec0cc4207ebead1f51dea06ff149342082b190'})

My code uses user generated token.

How to get the first non-null value in Java?

Object coalesce(Object... objects)
{
    for(Object o : object)
        if(o != null)
            return o;
    return null;
}

How can I get column names from a table in Oracle?

The answer is here: http://php.net/manual/en/function.mysql-list-fields.php I'd use the following code in your case:

$result = mysql_query("SHOW COLUMNS FROM sometable");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
$fields = array();
if (mysql_num_rows($result) > 0) {
    while ($row = mysql_fetch_assoc($result)) {
        $fields[] = $row['Field'];
    }
}

Get Windows version in a batch file

@echo off
for /f "tokens=2 delims=:" %%a in ('systeminfo ^| find "OS Name"') do set OS_Name=%%a
for /f "tokens=* delims= " %%a in ("%OS_Name%") do set OS_Name=%%a
for /f "tokens=3 delims= " %%a in ("%OS_Name%") do set OS_Name=%%a
if "%os_name%"=="XP" set version=XP
if "%os_name%"=="7" set version=7

This will grab the OS name as "7" or "XP"

Then you can use this in a variable to do certain commands based on the version of windows.

Xcode 6.1 Missing required architecture X86_64 in file

I run into exactly the same problem and was following this tutorial https://github.com/jverkoey/iOS-Framework#faq

The way that I made this work is after putting into the scripts into your Aggregate's Build Phase, before you compile, make sure you compile it using an iphone simulator (I used iPhone6) instead of IOS Device.

which will give me 2 slices: armv7 and x86_64, then drag and drop it into new project is working fine for me.

How to increase the Java stack size?

Hmm... it works for me and with far less than 999MB of stack:

> java -Xss4m Test
0

(Windows JDK 7, build 17.0-b05 client VM, and Linux JDK 6 - same version information as you posted)

package R does not exist

Never, ever try to write the R class yourself!

Have you imported the right R class in your files?

Doing

import android.R;

instead of

import com.example.R;

seems to be the problem for a lot of people. After cleaning and building, my classes sometimes import the wrong one.

Access-Control-Allow-Origin: * in tomcat

I had to restart the browser after changing the ip address (laptop wireless DHCP) which was my "cross-host" I was referring to in my web app, which resolved the issue.

Also make sure all the cors headers being added by your browser/host are accepted/allowed by including then in the cors.allowed.headers

How do I give text or an image a transparent background using CSS?

Here is a jQuery plugin that will handle everything for you, Transify (Transify - a jQuery plugin to easily apply transparency / opacity to an element’s background).

I was running into this problem every now and then, so I decided to write something that would make life a lot easier. The script is less than 2 KB and it only requires one line of code to get it to work, and it will also handle animating the opacity of the background if you like.

Check if enum exists in Java

I don't think there's a built-in way to do it without catching exceptions. You could instead use something like this:

public static MyEnum asMyEnum(String str) {
    for (MyEnum me : MyEnum.values()) {
        if (me.name().equalsIgnoreCase(str))
            return me;
    }
    return null;
}

Edit: As Jon Skeet notes, values() works by cloning a private backing array every time it is called. If performance is critical, you may want to call values() only once, cache the array, and iterate through that.

Also, if your enum has a huge number of values, Jon Skeet's map alternative is likely to perform better than any array iteration.

CMD (command prompt) can't go to the desktop

You need to use the change directory command 'cd' to change directory

cd C:\Users\MyName\Desktop

you can use cd \d to change the drive as well.

link for additional resources http://ss64.com/nt/cd.html

How to perform an SQLite query within an Android application?

Alternatively, db.rawQuery(sql, selectionArgs) exists.

Cursor c = db.rawQuery(select, null);

How to check if a variable is both null and /or undefined in JavaScript

A variable cannot be both null and undefined at the same time. However, the direct answer to your question is:

if (variable != null)

One =, not two.

There are two special clauses in the "abstract equality comparison algorithm" in the JavaScript spec devoted to the case of one operand being null and the other being undefined, and the result is true for == and false for !=. Thus if the value of the variable is undefined, it's not != null, and if it's not null, it's obviously not != null.

Now, the case of an identifier not being defined at all, either as a var or let, as a function parameter, or as a property of the global context is different. A reference to such an identifier is treated as an error at runtime. You could attempt a reference and catch the error:

var isDefined = false;
try {
  (variable);
  isDefined = true;
}
catch (x) {}

I would personally consider that a questionable practice however. For global symbols that may or may be there based on the presence or absence of some other library, or some similar situation, you can test for a window property (in browser JavaScript):

var isJqueryAvailable = window.jQuery != null;

or

var isJqueryAvailable = "jQuery" in window;

C++ int to byte array

Using std::vector<unsigned char>:

#include <vector>
using namespace std;

vector<unsigned char> intToBytes(int paramInt)
{
     vector<unsigned char> arrayOfByte(4);
     for (int i = 0; i < 4; i++)
         arrayOfByte[3 - i] = (paramInt >> (i * 8));
     return arrayOfByte;
}

How to say no to all "do you want to overwrite" prompts in a batch file copy?

You can make a text file with a single long line of "n" then run your command and put < nc.txt after it. I did this to copy over 145,000 instances where "No overwrite" was what I wanted and it worked fine this way.

Or you can just hold the n key down with something, but that takes longer than using the < to pipe it in.

symfony 2 twig limit the length of the text and put three dots

It is better to use an HTML character

{{ entity.text[:50] }}&#8230;

Show all current locks from get_lock

I found following way which can be used if you KNOW name of lock

select IS_USED_LOCK('lockname');

however i not found any info about how to list all names.

Customize list item bullets using CSS

Depending on the level of IE support needed, you could also use the :before selector with the bullet style set as the content property.

li {  
  list-style-type: none;
  font-size: small;
}

li:before {
  content: '\2022';
  font-size: x-large;
}

You may have to look up the HTML ASCII for the bullet style you want and use a converter for CSS Hex value.

Google Play app description formatting

<br> seems to be the best and only way that currently works on the app version to create a new line break. I have tried it successfully in a review, as well as unsuccessfully tried all other Unicode/HTML newline-related characters that the Wikipedia page for newlines would tell me. I used <br> with | immediately on either side, using no closing tag, and it magically created a single line break without revealing the source or screwing anything up.

TLDR: <br> lets you successfully utilize single line breaks in Google Play app -- unlike everything else I tried (a lot).

P.S. I have no clue how to make the thing show source instead of being used as source. !^( Now I do, and I know it works on both the desktop and mobile sites. !!

Additionally, upon searching for how to make it show the source, I stumbled upon this. <del></del>

How do I run a Python program in the Command Prompt in Windows 7?

You need to edit the environment variable named PATH, and add ;c:\python27 to the end of that. The semicolon separates one pathname from another (you will already have several things in your PATH).

Alternately, you can just type

c:\python27\python

at the command prompt without having to modify any environment variables at all.

Sharing link on WhatsApp from mobile website (not application) for Android

The above answers are bit outdated. Although those method work, but by using below method, you can share any text to a predefined number. The below method works for android, WhatsApp web, IOS etc.

You just need to use this format:

<a href="https://api.whatsapp.com/send?phone=whatsappphonenumber&text=urlencodedtext"></a>

UPDATE-- Use this from now(Nov-2018)

<a href="https://wa.me/whatsappphonenumber/?text=urlencodedtext"></a>

Use: https://wa.me/15551234567

Don't use: https://wa.me/+001-(555)1234567

To create your own link with a pre-filled message that will automatically appear in the text field of a chat, use https://wa.me/whatsappphonenumber/?text=urlencodedtext where whatsappphonenumber is a full phone number in international format and URL-encodedtext is the URL-encoded pre-filled message.

Example:https://wa.me/15551234567?text=I'm%20interested%20in%20your%20car%20for%20sale

To create a link with just a pre-filled message, use https://wa.me/?text=urlencodedtext

Example:https://wa.me/?text=I'm%20inquiring%20about%20the%20apartment%20listing

After clicking on the link, you will be shown a list of contacts you can send your message to.

For more information, see https://www.whatsapp.com/faq/en/general/26000030

File loading by getClass().getResource()

getClass().getResource() uses the class loader to load the resource. This means that the resource must be in the classpath to be loaded.

When doing it with Eclipse, everything you put in the source folder is "compiled" by Eclipse:

  • .java files are compiled into .class files that go the the bin directory (by default)
  • other files are copied to the bin directory (respecting the package/folder hirearchy)

When launching the program with Eclipse, the bin directory is thus in the classpath, and since it contains the Test.properties file, this file can be loaded by the class loader, using getResource() or getResourceAsStream().

If it doesn't work from the command line, it's thus because the file is not in the classpath.

Note that you should NOT do

FileInputStream inputStream = new FileInputStream(new File(getClass().getResource(url).toURI()));

to load a resource. Because that can work only if the file is loaded from the file system. If you package your app into a jar file, or if you load the classes over a network, it won't work. To get an InputStream, just use

getClass().getResourceAsStream("Test.properties")

And finally, as the documentation indicates,

Foo.class.getResourceAsStream("Test.properties")

will load a Test.properties file located in the same package as the class Foo.

Foo.class.getResourceAsStream("/com/foo/bar/Test.properties")

will load a Test.properties file located in the package com.foo.bar.

How do you get the logical xor of two variables in Python?

As Zach explained, you can use:

xor = bool(a) ^ bool(b)

Personally, I favor a slightly different dialect:

xor = bool(a) + bool(b) == 1

This dialect is inspired from a logical diagramming language I learned in school where "OR" was denoted by a box containing =1 (greater than or equal to 1) and "XOR" was denoted by a box containing =1.

This has the advantage of correctly implementing exclusive or on multiple operands.

  • "1 = a ^ b ^ c..." means the number of true operands is odd. This operator is "parity".
  • "1 = a + b + c..." means exactly one operand is true. This is "exclusive or", meaning "one to the exclusion of the others".

Task.Run with Parameter(s)?

private void RunAsync()
{
    string param = "Hi";
    Task.Run(() => MethodWithParameter(param));
}

private void MethodWithParameter(string param)
{
    //Do stuff
}

Edit

Due to popular demand I must note that the Task launched will run in parallel with the calling thread. Assuming the default TaskScheduler this will use the .NET ThreadPool. Anyways, this means you need to account for whatever parameter(s) being passed to the Task as potentially being accessed by multiple threads at once, making them shared state. This includes accessing them on the calling thread.

In my above code that case is made entirely moot. Strings are immutable. That's why I used them as an example. But say you're not using a String...

One solution is to use async and await. This, by default, will capture the SynchronizationContext of the calling thread and will create a continuation for the rest of the method after the call to await and attach it to the created Task. If this method is running on the WinForms GUI thread it will be of type WindowsFormsSynchronizationContext.

The continuation will run after being posted back to the captured SynchronizationContext - again only by default. So you'll be back on the thread you started with after the await call. You can change this in a variety of ways, notably using ConfigureAwait. In short, the rest of that method will not continue until after the Task has completed on another thread. But the calling thread will continue to run in parallel, just not the rest of the method.

This waiting to complete running the rest of the method may or may not be desirable. If nothing in that method later accesses the parameters passed to the Task you may not want to use await at all.

Or maybe you use those parameters much later on in the method. No reason to await immediately as you could continue safely doing work. Remember, you can store the Task returned in a variable and await on it later - even in the same method. For instance, once you need to access the passed parameters safely after doing a bunch some other work. Again, you do not need to await on the Task right when you run it.

Anyways, a simple way to make this thread-safe with respect to the parameters passed to Task.Run is to do this:

You must first decorate RunAsync with async:

private async void RunAsync()

Important Note

Preferably the method marked async should not return void, as the linked documentation mentions. The common exception to this is event handlers such as button clicks and such. They must return void. Otherwise I always try to return a Task or Task<TResult> when using async. It's good practice for a quite a few reasons.

Now you can await running the Task like below. You cannot use await without async.

await Task.Run(() => MethodWithParameter(param));
//Code here and below in the same method will not run until AFTER the above task has completed in one fashion or another

So, in general, if you await the task you can avoid treating passed in parameters as a potentially shared resource with all the pitfalls of modifying something from multiple threads at once. Also, beware of closures. I won't cover those in depth but the linked article does a great job of it.

Side Note

A bit off topic, but be careful using any type of "blocking" on the WinForms GUI thread due to it being marked with [STAThread]. Using await won't block at all, but I do sometimes see it used in conjunction with some sort of blocking.

"Block" is in quotes because you technically cannot block the WinForms GUI thread. Yes, if you use lock on the WinForms GUI thread it will still pump messages, despite you thinking it's "blocked". It's not.

This can cause bizarre issues in very rare cases. One of the reasons you never want to use a lock when painting, for example. But that's a fringe and complex case; however I've seen it cause crazy issues. So I noted it for completeness sake.

How to check task status in Celery?

Every Task object has a .request property, which contains it AsyncRequest object. Accordingly, the following line gives the state of a Task task:

task.AsyncResult(task.request.id).state

How do you log all events fired by an element in jQuery?

$('body').on("click mousedown mouseup focus blur keydown change mouseup click dblclick mousemove mouseover mouseout mousewheel keydown keyup keypress textInput touchstart touchmove touchend touchcancel resize scroll zoom focus blur select change submit reset",function(e){
     console.log(e);
}); 

Neither user 10102 nor current process has android.permission.READ_PHONE_STATE

Are you running Android M? If so, this is because it's not enough to declare permissions in the manifest. For some permissions, you have to explicitly ask user in the runtime: http://developer.android.com/training/permissions/requesting.html

What is the difference between Cygwin and MinGW?

Cygwin is is a Unix-like environment and command-line interface for Microsoft Windows.

Mingw is a native software port of the GNU Compiler Collection (GCC) to Microsoft Windows, along with a set of freely distributable import libraries and header files for the Windows API. MinGW allows developers to create native Microsoft Windows applications.

You can run binaries generated with mingw without the cygwin environment, provided that all necessary libraries (DLLs) are present.

Creating dummy variables in pandas for python

The following code returns dataframe with the 'Category' column replaced by categorical columns:

df_with_dummies = pd.get_dummies(df, prefix='Category_', columns=['Category'])

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html

What are major differences between C# and Java?

Generics:

With Java generics, you don't actually get any of the execution efficiency that you get with .NET because when you compile a generic class in Java, the compiler takes away the type parameter and substitutes Object everywhere. For instance if you have a Foo<T> class the java compiler generates Byte Code as if it was Foo<Object>. This means casting and also boxing/unboxing will have to be done in the "background".

I've been playing with Java/C# for a while now and, in my opinion, the major difference at the language level are, as you pointed, delegates.

Time complexity of accessing a Python dict

To answer your specific questions:

Q1:
"Am I correct that python dicts suffer from linear access times with such inputs?"

A1: If you mean that average lookup time is O(N) where N is the number of entries in the dict, then it is highly likely that you are wrong. If you are correct, the Python community would very much like to know under what circumstances you are correct, so that the problem can be mitigated or at least warned about. Neither "sample" code nor "simplified" code are useful. Please show actual code and data that reproduce the problem. The code should be instrumented with things like number of dict items and number of dict accesses for each P where P is the number of points in the key (2 <= P <= 5)

Q2:
"As far as I know, sets have guaranteed logarithmic access times. How can I simulate dicts using sets(or something similar) in Python?"

A2: Sets have guaranteed logarithmic access times in what context? There is no such guarantee for Python implementations. Recent CPython versions in fact use a cut-down dict implementation (keys only, no values), so the expectation is average O(1) behaviour. How can you simulate dicts with sets or something similar in any language? Short answer: with extreme difficulty, if you want any functionality beyond dict.has_key(key).

Git - Won't add files?

In my case the issue was enabled SafeCrLf option. I am on windows with tortoise git. After disabling the option adding the files was not an issue anymore.

Regex: match everything but specific pattern

Not a regexp expert, but I think you could use a negative lookahead from the start, e.g. ^(?!foo).*$ shouldn't match anything starting with foo.

CakePHP 3.0 installation: intl extension missing from system

OS X Homebrew (May 2015):

The intl extension has been removed from the main php5x formulas, so you no longer compile with the --enable-intl flag.

If you can't find the new package:

$ brew install php56-intl
Error: No available formula for php56-intl

Follow these instructions: https://github.com/Homebrew/homebrew-php/issues/1701

$ brew install php56-intl
==> Installing php56-intl from homebrew/homebrew-php

Add or change a value of JSON key with jquery or javascript

It seems if your key is saved in a variable. data.key = value won't work.

You should use data[key] = value

Example:

data = {key1:'v1', key2:'v2'};

var mykey = 'key1'; 
data.mykey = 'newv1';
data[mykey] = 'newV2';

console.log(data);

Result:

{
  "key1": "newV2",
  "key2": "v2",
  "mykey": "newv1"
}

asynchronous vs non-blocking

In many circumstances they are different names for the same thing, but in some contexts they are quite different. So it depends. Terminology is not applied in a totally consistent way across the whole software industry.

For example in the classic sockets API, a non-blocking socket is one that simply returns immediately with a special "would block" error message, whereas a blocking socket would have blocked. You have to use a separate function such as select or poll to find out when is a good time to retry.

But asynchronous sockets (as supported by Windows sockets), or the asynchronous IO pattern used in .NET, are more convenient. You call a method to start an operation, and the framework calls you back when it's done. Even here, there are basic differences. Asynchronous Win32 sockets "marshal" their results onto a specific GUI thread by passing Window messages, whereas .NET asynchronous IO is free-threaded (you don't know what thread your callback will be called on).

So they don't always mean the same thing. To distil the socket example, we could say:

  • Blocking and synchronous mean the same thing: you call the API, it hangs up the thread until it has some kind of answer and returns it to you.
  • Non-blocking means that if an answer can't be returned rapidly, the API returns immediately with an error and does nothing else. So there must be some related way to query whether the API is ready to be called (that is, to simulate a wait in an efficient way, to avoid manual polling in a tight loop).
  • Asynchronous means that the API always returns immediately, having started a "background" effort to fulfil your request, so there must be some related way to obtain the result.

What's the difference between import java.util.*; and import java.util.Date; ?

Your program should work exactly the same with either import java.util.*; or import java.util.Date;. There has to be something else you did in between.

Read whole ASCII file into C++ std::string

You may not find this in any book or site but I found out that it works pretty well:

ifstream ifs ("filename.txt");
string s;
getline (ifs, s, (char) ifs.eof());

ConnectionTimeout versus SocketTimeout

A connection timeout occurs only upon starting the TCP connection. This usually happens if the remote machine does not answer. This means that the server has been shut down, you used the wrong IP/DNS name, wrong port or the network connection to the server is down.

A socket timeout is dedicated to monitor the continuous incoming data flow. If the data flow is interrupted for the specified timeout the connection is regarded as stalled/broken. Of course this only works with connections where data is received all the time.

By setting socket timeout to 1 this would require that every millisecond new data is received (assuming that you read the data block wise and the block is large enough)!

If only the incoming stream stalls for more than a millisecond you are running into a timeout.

How to use Git?

Using Git for version control

Visual studio code have Integrated Git Support.

  • Steps to use git.

Install Git : https://git-scm.com/downloads

1) Initialize your repository

Navigate to directory where you want to initialize Git

Use git init command This will create a empty .git repository

2) Stage the changes

Staging is process of making Git to track our newly added files. For example add a file and type git status. You will find the status that untracked file. So to stage the changes use git add filename. If now type git status, you will find that new file added for tracking.

You can also unstage files. Use git reset

3) Commit Changes

Commiting is the process of recording your changes to repository. To commit the statges changes, you need to add a comment that explains the changes you made since your previous commit.

Use git commit -m message string

We can also commit the multiple files of same type using command git add '*.txt'. This command will commit all files with txt extension.

4) Follow changes

The aim of using version control is to keep all versions of each and every file in our project, Compare the the current version with last commit and keep the log of all changes.

Use git log to see the log of all changes.

Visual studio code’s integrated git support help us to compare the code by double clicking on the file OR Use git diff HEAD

You can also undo file changes at the last commit. Use git checkout -- file_name

5) Create remote repositories

Till now we have created a local repository. But in order to push it to remote server. We need to add a remote repository in server.

Use git remote add origin server_git_url

Then push it to server repository

Use git push -u origin master

Let assume some time has passed. We have invited other people to our project who have pulled our changes, made their own commits, and pushed them.

So to get the changes from our team members, we need to pull the repository.

Use git pull origin master

6) Create Branches

Lets think that you are working on a feature or a bug. Better you can create a copy of your code(Branch) and make separate commits to. When you have done, merge this branch back to their master branch.

Use git branch branch_name

Now you have two local branches i.e master and XXX(new branch). You can switch branches using git checkout master OR git checkout new_branch_name

Commiting branch changes using git commit -m message

Switch back to master using git checkout master

Now we need to merge changes from new branch into our master Use git merge branch_name

Good! You just accomplished your bugfix Or feature development and merge. Now you don’t need the new branch anymore. So delete it using git branch -d branch_name

Now we are in the last step to push everything to remote repository using git push

Hope this will help you

How can I check what version/edition of Visual Studio is installed programmatically?

For anyone stumbling on this question, here is the answer if you are doing C++: You can check in your cpp code for vs version like the example bellow which links against a library based on vs version being 2015 or higher:

#if (_MSC_VER > 1800)
#pragma comment (lib, "legacy_stdio_definitions.lib")
#endif

This is done at link time and no extra run-time cost.

Call child method from parent

If you are doing this simply because you want the Child to provide a re-usable trait to its parents, then you might consider doing that using render-props instead.

That technique actually turns the structure upside down. The Child now wraps the parent, so I have renamed it to AlertTrait below. I kept the name Parent for continuity, although it is not really a parent now.

// Use it like this:

  <AlertTrait renderComponent={Parent}/>


class AlertTrait extends Component {
  // You will need to bind this function, if it uses 'this'
  doAlert() {
    alert('clicked');
  }
  render() {
    return this.props.renderComponent({ doAlert: this.doAlert });
  }
}

class Parent extends Component {
  render() {
    return (
      <button onClick={this.props.doAlert}>Click</button>
    );
  }
}

In this case, the AlertTrait provides one or more traits which it passes down as props to whatever component it was given in its renderComponent prop.

The Parent receives doAlert as a prop, and can call it when needed.

(For clarity, I called the prop renderComponent in the above example. But in the React docs linked above, they just call it render.)

The Trait component can render stuff surrounding the Parent, in its render function, but it does not render anything inside the parent. Actually it could render things inside the Parent, if it passed another prop (e.g. renderChild) to the parent, which the parent could then use during its render method.

This is somewhat different from what the OP asked for, but some people might end up here (like we did) because they wanted to create a reusable trait, and thought that a child component was a good way to do that.

WebSockets protocol vs HTTP

A regular REST API uses HTTP as the underlying protocol for communication, which follows the request and response paradigm, meaning the communication involves the client requesting some data or resource from a server, and the server responding back to that client. However, HTTP is a stateless protocol, so every request-response cycle will end up having to repeat the header and metadata information. This incurs additional latency in case of frequently repeated request-response cycles.

http

With WebSockets, although the communication still starts off as an initial HTTP handshake, it is further upgraded to follow the WebSockets protocol (i.e. if both the server and the client are compliant with the protocol as not all entities support the WebSockets protocol).

Now with WebSockets, it is possible to establish a full-duplex and persistent connection between the client and a server. This means that unlike a request and a response, the connection stays open for as long as the application is running (i.e. it’s persistent), and since it is full-duplex, two-way simultaneous communication is possible i.e now the server is capable of initiating communication and 'push' some data to the client when new data (that the client is interested in) becomes available.

websockets

The WebSockets protocol is stateful and allows you to implement the Publish-Subscribe (or Pub/Sub) messaging pattern which is the primary concept used in the real-time technologies where you are able to get new updates in the form of server push without the client having to request (refresh the page) repeatedly. Examples of such applications are Uber car's location tracking, Push Notifications, Stock market prices updating in real-time, chat, multiplayer games, live online collaboration tools, etc.

You can check out a deep dive article on Websockets which explains the history of this protocol, how it came into being, what it’s used for and how you can implement it yourself.

Here's a video from a presentation I did about WebSockets and how they are different from using the regular REST APIs: Standardisation and leveraging the exponential rise in data streaming

How to search for rows containing a substring?

Well, you can always try WHERE textcolumn LIKE "%SUBSTRING%" - but this is guaranteed to be pretty slow, as your query can't do an index match because you are looking for characters on the left side.

It depends on the field type - a textarea usually won't be saved as VARCHAR, but rather as (a kind of) TEXT field, so you can use the MATCH AGAINST operator.

To get the columns that don't match, simply put a NOT in front of the like: WHERE textcolumn NOT LIKE "%SUBSTRING%".

Whether the search is case-sensitive or not depends on how you stock the data, especially what COLLATION you use. By default, the search will be case-insensitive.

Updated answer to reflect question update:

I say that doing a WHERE field LIKE "%value%" is slower than WHERE field LIKE "value%" if the column field has an index, but this is still considerably faster than getting all values and having your application filter. Both scenario's:

1/ If you do SELECT field FROM table WHERE field LIKE "%value%", MySQL will scan the entire table, and only send the fields containing "value".

2/ If you do SELECT field FROM table and then have your application (in your case PHP) filter only the rows with "value" in it, MySQL will also scan the entire table, but send all the fields to PHP, which then has to do additional work. This is much slower than case #1.

Solution: Please do use the WHERE clause, and use EXPLAIN to see the performance.

How to change color of the back arrow in the new material theme?

Another solution that might work for you is to not declare your toolbar as the app's action bar ( by setActionBar or setSupportActionBar ) and set the back icon in your onActivityCreated using the code mentioned in another answer on this page

final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
upArrow.setColorFilter(getResources().getColor(R.color.grey), PorterDuff.Mode.SRC_ATOP);
toolbar.setNavigationIcon(upArrow);

Now, you will not get the onOptionItemSelected callback when you press the back button. However, you can register for that using setNavigationOnClickListener. This is what i do:

toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        getActivity().onBackPressed(); //or whatever you used to do on your onOptionItemSelected's android.R.id.home callback
    }
});

I'm not sure if it will work if you work with menu items.

Batch file to delete files older than N days

forfiles /p "v:" /s /m *.* /d -3 /c "cmd /c del @path"

You should do /d -3 (3 days earlier) This works fine for me. So all the complicated batches could be in the trash bin. Also forfiles don't support UNC paths, so make a network connection to a specific drive.

What is the best open-source java charting library? (other than jfreechart)

There is JChart which is all open source. I'm not sure exactly what you are graphing and how you are graphing it (servlets, swing, etc) so I would say just look at a couple different ones and see which works for you.

http://sourceforge.net/projects/jchart/

I've also used JGraph but I've only used their commercial version. They do offer an open source version however:

http://www.jgraph.com/jgraph.html

500 internal server error, how to debug

You can turn on your PHP errors with error_reporting:

error_reporting(E_ALL);
ini_set('display_errors', 'on');

Edit: It's possible that even after putting this, errors still don't show up. This can be caused if there is a fatal error in the script. From PHP Runtime Configuration:

Although display_errors may be set at runtime (with ini_set()), it won't have any affect if the script has fatal errors. This is because the desired runtime action does not get executed.

You should set display_errors = 1 in your php.ini file and restart the server.

How would you do a "not in" query with LINQ?

Example using List of int for simplicity.

List<int> list1 = new List<int>();
// fill data
List<int> list2 = new List<int>();
// fill data

var results = from i in list1
              where !list2.Contains(i)
              select i;

foreach (var result in results)
    Console.WriteLine(result.ToString());

Python: maximum recursion depth exceeded while calling a Python object

Python don't have a great support for recursion because of it's lack of TRE (Tail Recursion Elimination).

This means that each call to your recursive function will create a function call stack and because there is a limit of stack depth (by default is 1000) that you can check out by sys.getrecursionlimit (of course you can change it using sys.setrecursionlimit but it's not recommended) your program will end up by crashing when it hits this limit.

As other answer has already give you a much nicer way for how to solve this in your case (which is to replace recursion by simple loop) there is another solution if you still want to use recursion which is to use one of the many recipes of implementing TRE in python like this one.

N.B: My answer is meant to give you more insight on why you get the error, and I'm not advising you to use the TRE as i already explained because in your case a loop will be much better and easy to read.

Kendo grid date column not formatting

Try formatting the date in the kendo grid as:

columns.Bound(x => x.LastUpdateDate).ClientTemplate("#= kendo.toString(LastUpdateDate, \"MM/dd/yyyy hh:mm tt\") #");

Array.sort() doesn't sort numbers correctly

a.sort(function(a,b){return a - b})

These can be confusing.... check this link out.

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).

Barcode scanner for mobile phone for Website in form

There's a JS QrCode scanner, that works on mobile sites with a camera:

https://github.com/LazarSoft/jsqrcode

I have worked with it for one of my project and it works pretty good !

Setting log level of message at runtime in slf4j

The method I use is to import the ch.qos.logback modules and then type-cast the slf4j Logger instance to a ch.qos.logback.classic.Logger. This instance includes a setLevel() method.

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;

Logger levelSet = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);

// Now you can set the desired logging-level
levelSet.setLevel( Level.OFF );

To find out the possible Logging-levels, you can explode the ch.qos.logback class to see all the possible values for Level:

prompt$ javap -cp logback-classic-1.2.3.jar ch.qos.logback.classic.Level

The results are the following:

{
   // ...skipping
   public static final ch.qos.logback.classic.Level OFF;
   public static final ch.qos.logback.classic.Level ERROR;
   public static final ch.qos.logback.classic.Level WARN;
   public static final ch.qos.logback.classic.Level INFO;
   public static final ch.qos.logback.classic.Level DEBUG;
   public static final ch.qos.logback.classic.Level TRACE;
   public static final ch.qos.logback.classic.Level ALL;
}

AngularJS : Clear $watch

scope.$watch returns a function that you can call and that will unregister the watch.

Something like:

var unbindWatch = $scope.$watch("myvariable", function() {
    //...
});

setTimeout(function() {
    unbindWatch();
}, 1000);

Get screenshot on Windows with Python?

You can use the ImageGrab module. ImageGrab works on Windows and macOS, and you need PIL (Pillow) to use it. Here is a little example:

from PIL import ImageGrab
snapshot = ImageGrab.grab()
save_path = "C:\\Users\\YourUser\\Desktop\\MySnapshot.jpg"
snapshot.save(save_path)

Session variables not working php

I had similar issue and with the cookie domain:

    ini_set('session.cookie_domain', '.domain.com');

the domain was setup wrong so all sessions were ignored because the user cookie was never set right hope this will help someone.

How to declare a structure in a header that is to be used by multiple files in c?

a.h:

#ifndef A_H
#define A_H

struct a { 
    int i;
    struct b {
        int j;
    }
};

#endif

there you go, now you just need to include a.h to the files where you want to use this structure.

Getting input values from text box

you have multiple elements with the same id. That is a big no-no. Make sure your inputs have unique ids.

<td id="pass"><label>Password</label></td>
<tr>
   <td colspan="2"><input class="textBox" id="pass" type="text" maxlength="30" required/></td>
</tr>

see, both the td and the input share the id value pass.

How do I combine two dataframes?

There's another solution for the case that you are working with big data and need to concatenate multiple datasets. concat can get performance-intensive, so if you don't want to create a new df each time, you can instead use a list comprehension:

frames = [ process_file(f) for f in dataset_files ]
result = pd.append(frames)

(as pointed out here in the docs at the bottom of the section):

Note: It is worth noting however, that concat (and therefore append) makes a full copy of the data, and that constantly reusing this function can create a significant performance hit. If you need to use the operation over several datasets, use a list comprehension.

Function ereg_replace() is deprecated - How to clear this bug?

IIRC they suggest using the preg_ functions instead (in this case, preg_replace).

How do I vertically center an H1 in a div?

I've had success putting text within span tags and then setting vertical-align: middle on that span. Don't know how cross-browser compliant this is though, I've only tested it in webkit browsers.

What do pty and tty mean?

A tty is a terminal (it stands for teletype - the original terminals used a line printer for output and a keyboard for input!). A terminal is a basically just a user interface device that uses text for input and output.

A pty is a pseudo-terminal - it's a software implementation that appears to the attached program like a terminal, but instead of communicating directly with a "real" terminal, it transfers the input and output to another program.

For example, when you ssh in to a machine and run ls, the ls command is sending its output to a pseudo-terminal, the other side of which is attached to the SSH daemon.

How to get the browser language using JavaScript

Try this script to get your browser language

_x000D_
_x000D_
<script type="text/javascript">_x000D_
var userLang = navigator.language || navigator.userLanguage; _x000D_
alert ("The language is: " + userLang);_x000D_
</script>
_x000D_
_x000D_
_x000D_

Cheers

Generic type conversion FROM string

lubos hasko's method fails for nullables. The method below will work for nullables. I didn't come up with it, though. I found it via Google: http://web.archive.org/web/20101214042641/http://dogaoztuzun.com/post/C-Generic-Type-Conversion.aspx Credit to "Tuna Toksoz"

Usage first:

TConverter.ChangeType<T>(StringValue);  

The class is below.

public static class TConverter
{
    public static T ChangeType<T>(object value)
    {
        return (T)ChangeType(typeof(T), value);
    }

    public static object ChangeType(Type t, object value)
    {
        TypeConverter tc = TypeDescriptor.GetConverter(t);
        return tc.ConvertFrom(value);
    }

    public static void RegisterTypeConverter<T, TC>() where TC : TypeConverter
    {

        TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC)));
    }
}

Can dplyr join on multiple columns or composite key?

Updating to use tibble()

You can pass a named vector of length greater than 1 to the by argument of left_join():

library(dplyr)

d1 <- tibble(
  x = letters[1:3],
  y = LETTERS[1:3],
  a = rnorm(3)
  )

d2 <- tibble(
  x2 = letters[3:1],
  y2 = LETTERS[3:1],
  b = rnorm(3)
  )

left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))

Why use static_cast<int>(x) instead of (int)x?

C Style casts are easy to miss in a block of code. C++ style casts are not only better practice; they offer a much greater degree of flexibility.

reinterpret_cast allows integral to pointer type conversions, however can be unsafe if misused.

static_cast offers good conversion for numeric types e.g. from as enums to ints or ints to floats or any data types you are confident of type. It does not perform any run time checks.

dynamic_cast on the other hand will perform these checks flagging any ambiguous assignments or conversions. It only works on pointers and references and incurs an overhead.

There are a couple of others but these are the main ones you will come across.

Error: Could not find or load main class in intelliJ IDE

I meet same problem and solved it by:

  • Closing all IDEA windows
  • Delete C:/Userz/xx/.IdeaIC2019.3 folder
  • Reopen IDEA

JavaScript post request like a form submit

FormObject is an option. But FormObject is not supported by most browsers now.

Parsing JSON giving "unexpected token o" error

cur_ques_details is already a JS object, you don't need to parse it

Artificially create a connection timeout error

How about a software solution:

Install SSH server on the application server. Then, use socket tunnel to create a link between your local port and the remote port on the application server. You can use ssh client tools to do so. Have your client application connect to your mapped local port instead. Then, you can break the socket tunnel at will to simulate the connection timeout.

SQL Server replace, remove all after certain character

UPDATE MyTable
   SET MyText = SUBSTRING(MyText, 1, CHARINDEX(';', MyText) - 1)
 WHERE CHARINDEX(';', MyText) > 0 

How to execute my SQL query in CodeIgniter

 return $this->db->select('(CASE 
            enter code hereWHEN orderdetails.ProductID = 0   THEN dealmaster.deal_name
            WHEN orderdetails.DealID = 0 THEN products.name
            END) as product_name')

HTML Script tag: type or language (or omit both)?

HTML4/XHTML1 requires

<script type="...">...</script>

HTML5 faces the fact that there is only one scripting language on the web, and allows

<script>...</script>

The latter works in any browser that supports scripting (NN2+).

What is a elegant way in Ruby to tell if a variable is a Hash or an Array?

First of all, the best answer for the literal question is

Hash === @some_var

But the question really should have been answered by showing how to do duck-typing here. That depends a bit on what kind of duck you need.

@some_var.respond_to?(:each_pair)

or

@some_var.respond_to?(:has_key?)

or even

@some_var.respond_to?(:to_hash)

may be right depending on the application.

How can I programmatically invoke an onclick() event from a anchor tag while keeping the ‘this’ reference in the onclick function?

To trigger an event you basically just call the event handler for that element. Slight change from your code.

var a = document.getElementById("element");
var evnt = a["onclick"];

if (typeof(evnt) == "function") {
    evnt.call(a);
}

Changing button text onclick

This is simple way to change Submit to loading state   

 <button id="custSub" type="submit" class="button left tiny" data-text-swap="Processing.. &nbsp;">Submit &nbsp;<i class="fa fa-angle-double-right"></i></button>


    <script>
    jQuery(document).ready(function ($) {

        $("button").on("click", function() {
          var el = $(this);
          if (el.html() == el.data("text-swap")) {
            el.html(el.data("text-original"));
          } else {
            el.data("text-original", el.html());
            el.html(el.data("text-swap"));
          }
          setTimeout(function () {
                el.html(el.data("text-original"));
           }, 500);
        });

    });
    </script>

How to Call VBA Function from Excel Cells?

The issue you have encountered is that UDFs cannot modify the Excel environment, they can only return a value to the calling cell.

There are several alternatives

  1. For the sample given you don't actually need VBA. This formula will work
    ='C:\Users\UserName\Desktop\[TestSample.xlsx]Sheet1'!$B$2

  2. Use a rather messy work around: See this answer

  3. You can use ExecuteExcel4Macro or OLEDB

Python float to int conversion

2.51 * 100 = 250.999999999997

The int() function simply truncates the number at the decimal point, giving 250. Use

int(round(2.51*100)) 

to get 251 as an integer. In general, floating point numbers cannot be represented exactly. One should therefore be careful of round-off errors. As mentioned, this is not a Python-specific problem. It's a recurring problem in all computer languages.

how do I create an array in jquery?

your question makes no sense. you are asking how to turn a hash into an array. You cant.

you can make a list of values, or make a list of keys, and neither of these have anything to do with jquery, this is pure javascript

Extract file name from path, no matter what the os/path format

In your example you will also need to strip slash from right the right side to return c:

>>> import os
>>> path = 'a/b/c/'
>>> path = path.rstrip(os.sep) # strip the slash from the right side
>>> os.path.basename(path)
'c'

Second level:

>>> os.path.filename(os.path.dirname(path))
'b'

update: I think lazyr has provided the right answer. My code will not work with windows-like paths on unix systems and vice versus with unix-like paths on windows system.

What is the difference between And and AndAlso in VB.NET?

AndAlso is much like And, except it works like && in C#, C++, etc.

The difference is that if the first clause (the one before AndAlso) is true, the second clause is never evaluated - the compound logical expression is "short circuited".

This is sometimes very useful, e.g. in an expression such as:

If Not IsNull(myObj) AndAlso myObj.SomeProperty = 3 Then
   ...
End If

Using the old And in the above expression would throw a NullReferenceException if myObj were null.

How to change Elasticsearch max memory size

In ElasticSearch >= 5 the documentation has changed, which means none of the above answers worked for me.

I tried changing ES_HEAP_SIZE in /etc/default/elasticsearch and in /etc/init.d/elasticsearch, but when I ran ps aux | grep elasticsearch the output still showed:

I had to make these changes in:

/etc/elasticsearch/jvm.options

# Xms represents the initial size of total heap space
# Xmx represents the maximum size of total heap space

-Xms1g 
-Xmx1g 
# the settings shipped with ES 5 were: -Xms2g
# the settings shipped with ES 5 were: -Xmx2g

Can I use return value of INSERT...RETURNING in another INSERT?

You can use the lastval() function:

Return value most recently obtained with nextval for any sequence

So something like this:

INSERT INTO Table1 (name) VALUES ('a_title');
INSERT INTO Table2 (val)  VALUES (lastval());

This will work fine as long as no one calls nextval() on any other sequence (in the current session) between your INSERTs.

As Denis noted below and I warned about above, using lastval() can get you into trouble if another sequence is accessed using nextval() between your INSERTs. This could happen if there was an INSERT trigger on Table1 that manually called nextval() on a sequence or, more likely, did an INSERT on a table with a SERIAL or BIGSERIAL primary key. If you want to be really paranoid (a good thing, they really are you to get you after all), then you could use currval() but you'd need to know the name of the relevant sequence:

INSERT INTO Table1 (name) VALUES ('a_title');
INSERT INTO Table2 (val)  VALUES (currval('Table1_id_seq'::regclass));

The automatically generated sequence is usually named t_c_seq where t is the table name and c is the column name but you can always find out by going into psql and saying:

=> \d table_name;

and then looking at the default value for the column in question, for example:

id | integer | not null default nextval('people_id_seq'::regclass)

FYI: lastval() is, more or less, the PostgreSQL version of MySQL's LAST_INSERT_ID. I only mention this because a lot of people are more familiar with MySQL than PostgreSQL so linking lastval() to something familiar might clarify things.

Server returned HTTP response code: 401 for URL: https

401 means "Unauthorized", so there must be something with your credentials.

I think that java URL does not support the syntax you are showing. You could use an Authenticator instead.

Authenticator.setDefault(new Authenticator() {

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {          
        return new PasswordAuthentication(login, password.toCharArray());
    }
});

and then simply invoking the regular url, without the credentials.

The other option is to provide the credentials in a Header:

String loginPassword = login+ ":" + password;
String encoded = new sun.misc.BASE64Encoder().encode (loginPassword.getBytes());
URLConnection conn = url.openConnection();
conn.setRequestProperty ("Authorization", "Basic " + encoded);

PS: It is not recommended to use that Base64Encoder but this is only to show a quick solution. If you want to keep that solution, look for a library that does. There are plenty.

SyntaxError: import declarations may only appear at top level of a module

I got this on Firefox (FF58). I fixed this with:

  1. It is still experimental on Firefox (from v54): You have to set to true the variable dom.moduleScripts.enabled in about:config

Source: Import page on mozilla (See Browser compatibility)

  1. Add type="module" to your script tag where you import the js file

<script type="module" src="appthatimports.js"></script>

  1. Import files have to be prefixed (./, /, ../ or http:// before)

import * from "./mylib.js"

For more examples, this blog post is good.

Load More Posts Ajax Button in WordPress

If I'm not using any category then how can I use this code? Actually, I want to use this code for custom post type.

Get an array of list element contents in jQuery

var arr = new Array();

$('li').each(function() { 
  arr.push(this.innerHTML); 
})

How to send data with angularjs $http.delete() request?

My suggestion:

$http({
    method: 'DELETE',
    url: '/roles/' + roleid,
    data: {
        user: userId
    },
    headers: {
        'Content-type': 'application/json;charset=utf-8'
    }
})
.then(function(response) {
    console.log(response.data);
}, function(rejection) {
    console.log(rejection.data);
});

Why is Node.js single threaded?

Node.js was created explicitly as an experiment in async processing. The theory was that doing async processing on a single thread could provide more performance and scalability under typical web loads than the typical thread-based implementation.

And you know what? In my opinion that theory's been borne out. A node.js app that isn't doing CPU intensive stuff can run thousands more concurrent connections than Apache or IIS or other thread-based servers.

The single threaded, async nature does make things complicated. But do you honestly think it's more complicated than threading? One race condition can ruin your entire month! Or empty out your thread pool due to some setting somewhere and watch your response time slow to a crawl! Not to mention deadlocks, priority inversions, and all the other gyrations that go with multithreading.

In the end, I don't think it's universally better or worse; it's different, and sometimes it's better and sometimes it's not. Use the right tool for the job.

How to get the groups of a user in Active Directory? (c#, asp.net)

First of all, GetAuthorizationGroups() is a great function but unfortunately has 2 disadvantages:

  1. Performance is poor, especially in big company's with many users and groups. It fetches a lot more data then you actually need and does a server call for each loop iteration in the result
  2. It contains bugs which can cause your application to stop working 'some day' when groups and users are evolving. Microsoft recognized the issue and is related with some SID's. The error you'll get is "An error occurred while enumerating the groups"

Therefore, I've wrote a small function to replace GetAuthorizationGroups() with better performance and error-safe. It does only 1 LDAP call with a query using indexed fields. It can be easily extended if you need more properties than only the group names ("cn" property).

// Usage: GetAdGroupsForUser2("domain\user") or GetAdGroupsForUser2("user","domain")
public static List<string> GetAdGroupsForUser2(string userName, string domainName = null)
{
    var result = new List<string>();

    if (userName.Contains('\\') || userName.Contains('/'))
    {
        domainName = userName.Split(new char[] { '\\', '/' })[0];
        userName = userName.Split(new char[] { '\\', '/' })[1];
    }

    using (PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, domainName))
        using (UserPrincipal user = UserPrincipal.FindByIdentity(domainContext, userName))
            using (var searcher = new DirectorySearcher(new DirectoryEntry("LDAP://" + domainContext.Name)))
            {
                searcher.Filter = String.Format("(&(objectCategory=group)(member={0}))", user.DistinguishedName);
                searcher.SearchScope = SearchScope.Subtree;
                searcher.PropertiesToLoad.Add("cn");

                foreach (SearchResult entry in searcher.FindAll())
                    if (entry.Properties.Contains("cn"))
                        result.Add(entry.Properties["cn"][0].ToString());
            }

    return result;
}

How do I set bold and italic on UILabel of iPhone/iPad?

You can set any font style, family, size for the label, by clicking on letter "T" in Font field.

Label font settings

How do I get the Back Button to work with an AngularJS ui-router state machine?

If you are looking for the simplest "back" button, then you could set up a directive like so:

    .directive('back', function factory($window) {
      return {
        restrict   : 'E',
        replace    : true,
        transclude : true,
        templateUrl: 'wherever your template is located',
        link: function (scope, element, attrs) {
          scope.navBack = function() {
            $window.history.back();
          };
        }
      };
    });

Keep in mind this is a fairly unintelligent "back" button because it is using the browser's history. If you include it on your landing page, it will send a user back to any url they came from prior to landing on yours.

concatenate two database columns into one resultset column

Just Cast Column As Varchar(Size)

If both Column are numeric then use code below.

Example:

Select (Cast(Col1 as Varchar(20)) + '-' + Cast(Col2 as Varchar(20))) As Col3 from Table

What will be the size of col3 it will be 40 or something else

Is there a way to pass optional parameters to a function?

You can specify a default value for the optional argument with something that would never passed to the function and check it with the is operator:

class _NO_DEFAULT:
    def __repr__(self):return "<no default>"
_NO_DEFAULT = _NO_DEFAULT()

def func(optional= _NO_DEFAULT):
    if optional is _NO_DEFAULT:
        print("the optional argument was not passed")
    else:
        print("the optional argument was:",optional)

then as long as you do not do func(_NO_DEFAULT) you can be accurately detect whether the argument was passed or not, and unlike the accepted answer you don't have to worry about side effects of ** notation:

# these two work the same as using **
func()
func(optional=1)

# the optional argument can be positional or keyword unlike using **
func(1) 

#this correctly raises an error where as it would need to be explicitly checked when using **
func(invalid_arg=7)

Using G++ to compile multiple .cpp and .h files

list all the other cpp files after main.cpp.

ie

g++ main.cpp other.cpp etc.cpp

and so on.

Or you can compile them all individually. You then link all the resulting ".o" files together.

How do I make a placeholder for a 'select' box?

You could set the first option's color to gray, set it's display to none, set the select's color to gray, and add an input event listener to it that sets it's color to black.

_x000D_
_x000D_
select > option:not(:first-of-type) {
  color: black;
}
_x000D_
<select style='color:gray' oninput='style.color="black"'>
  <option style='display:none'>
    Choose an option
  </option>
  <option>
    1
  </option>
  <option>
    2
  </option>
  <option>
    3
  </option>
</select>
_x000D_
_x000D_
_x000D_

Using the customElement API:

_x000D_
_x000D_
class placeholderSelect extends HTMLElement {
  connectedCallback() {
    this.outerHTML = `<select style='color:gray' oninput='style.color="black"'>
  <option style='display:none'>
    ${this.getAttribute('data-placeholder')}
  </option>
  ${this.innerHTML}
</select>`

    Array.from(this.children).forEach(function(el, i) {
      if (i !== 0) {
        el.style.color = 'black'
      }
    })
  }
}

customElements.define('placeholder-select', placeholderSelect)
_x000D_
<placeholder-select data-placeholder='Choose an option'>
  <option>
    1
  </option>
  <option>
    2
  </option>
  <option>
    3
  </option>
</placeholder-select>
_x000D_
_x000D_
_x000D_

Sending commands and strings to Terminal.app with Applescript

You don't need to "tell" Terminal to do anything. AppleScript can do shell scripts directly.

set theDir to "~/Desktop/"
do shell script "touch " & theDir &"SomeFile.txt"

or whatever ...

Illegal mix of collations MySQL Error

My user account did not have the permissions to alter the database and table, as suggested in this solution.

If, like me, you don't care about the character collation (you are using the '=' operator), you can apply the reverse fix. Run this before your SELECT:

SET collation_connection = 'latin1_swedish_ci';

Restricting JTextField input to Integers

When you type integer numbers to JtextField1 after key release it will go to inside try , for any other character it will throw NumberFormatException. If you set empty string to jTextField1 inside the catch so the user cannot type any other keys except positive numbers because JTextField1 will be cleared for each bad attempt.

 //Fields 
int x;
JTextField jTextField1;

 //Gui Code Here

private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {                                        
    try {
        x = Integer.parseInt(jTextField1.getText());
    } catch (NumberFormatException nfe) {
        jTextField1.setText("");
    }
}   

How to print table using Javascript?

My fellows,

In January 2019 I used a code made before:

 <script type="text/javascript">   
    function imprimir() {
        var divToPrint=document.getElementById("ConsutaBPM");
        newWin= window.open("");
        newWin.document.write(divToPrint.outerHTML);
        newWin.print();
        newWin.close();
    }
</script>

To undestand: ConsutaBPM is a DIV which contains inside phrases and tables. I wanted to print ALL, titles, table, and others. The problem was when TRIED to print the TABLE...

The table mas be defined with BORDER and CELLPADDING:

<table border='1' cellpadding='1' id='Tablbpm1' >

It worked fine!!!

Proper way to assert type of variable in Python

You might want to try this example for version 2.6 of Python.

def my_print(text, begin, end):
    "Print text in UPPER between 'begin' and 'end' in lower."
    for obj in (text, begin, end):
        assert isinstance(obj, str), 'Argument of wrong type!'
    print begin.lower() + text.upper() + end.lower()

However, have you considered letting the function fail naturally instead?

How can I get session id in php and show it?

session_start();    
echo session_id();

How can I get Git to follow symlinks?

Conversion from symlinks could be useful. Link in a Git folder instead of a symlink by a script.

php: loop through json array

First you have to decode your json :

$array = json_decode($the_json_code);

Then after the json decoded you have to do the foreach

foreach ($array as $key => $jsons) { // This will search in the 2 jsons
     foreach($jsons as $key => $value) {
         echo $value; // This will show jsut the value f each key like "var1" will print 9
                       // And then goes print 16,16,8 ...
    }
}

If you want something specific just ask for a key like this. Put this between the last foreach.

if($key == 'var1'){
 echo $value;
}

Hash function for a string

Hash functions for algorithmic use have usually 2 goals, first they have to be fast, second they have to evenly distibute the values across the possible numbers. The hash function also required to give the all same number for the same input value.

if your values are strings, here are some examples for bad hash functions:

  1. string[0] - the ASCII characters a-Z are way more often then others
  2. string.lengh() - the most probable value is 1

Good hash functions tries to use every bit of the input while keeping the calculation time minimal. If you only need some hash code, try to multiply the bytes with prime numbers, and sum them.

Swap two items in List<T>

Check the answer from Marc from C#: Good/best implementation of Swap method.

public static void Swap<T>(IList<T> list, int indexA, int indexB)
{
    T tmp = list[indexA];
    list[indexA] = list[indexB];
    list[indexB] = tmp;
}

which can be linq-i-fied like

public static IList<T> Swap<T>(this IList<T> list, int indexA, int indexB)
{
    T tmp = list[indexA];
    list[indexA] = list[indexB];
    list[indexB] = tmp;
    return list;
}

var lst = new List<int>() { 8, 3, 2, 4 };
lst = lst.Swap(1, 2);

ApiNotActivatedMapError for simple html page using google-places-api

I had the same error. To fix the error:

  1. Open the console menu Gallery Menu and select API Manager.
  2. On the left, click Credentials and then click New Credentials.
  3. Click Create Credentials.
  4. Click API KEY.
  5. Click Navigator Key (there are more options; It depends on when consumed).

You must use this new API Navigator Key, generated by the system.

How to convert an NSString into an NSNumber

You can use -[NSString integerValue], -[NSString floatValue], etc. However, the correct (locale-sensitive, etc.) way to do this is to use -[NSNumberFormatter numberFromString:] which will give you an NSNumber converted from the appropriate locale and given the settings of the NSNumberFormatter (including whether it will allow floating point values).

HTTP Ajax Request via HTTPS Page

Make a bypass API in server.js. This works for me.

app.post('/by-pass-api',function(req, response){
  const url = req.body.url;
  console.log("calling url", url);
  request.get(
    url,
    (error, res, body) => {
      if (error) {
        console.error(error)
        return response.status(200).json({'content': "error"}) 
}
        return response.status(200).json(JSON.parse(body))
        },
      )
    })

And call it using axios or fetch like this:

const options = {
     method: 'POST',
     headers: {'content-type': 'application/json'},
     url:`http://localhost:3000/by-pass-api`, // your environment 
     data: { url },  // your https request here
    };

Run certain code every n seconds

You can start a separate thread whose sole duty is to count for 5 seconds, update the file, repeat. You wouldn't want this separate thread to interfere with your main thread.

Add newly created specific folder to .gitignore in Git

For this there are two cases

Case 1: File already added to git repo.

Case 2: File newly created and its status still showing as untracked file when using

git status

If you have case 1:

STEP 1: Then run

git rm --cached filename 

to remove it from git repo cache

if it is a directory then use

git rm -r --cached  directory_name

STEP 2: If Case 1 is over then create new file named .gitignore in your git repo

STEP 3: Use following to tell git to ignore / assume file is unchanged

git update-index --assume-unchanged path/to/file.txt

STEP 4: Now, check status using git status open .gitignore in your editor nano, vim, geany etc... any one, add the path of the file / folder to ignore. If it is a folder then user folder_name/* to ignore all file.

If you still do not understand read the article git ignore file link.

How to get thread id of a pthread in linux c program?

This single line gives you pid , each threadid and spid.

 printf("before calling pthread_create getpid: %d getpthread_self: %lu tid:%lu\n",getpid(), pthread_self(), syscall(SYS_gettid));

jQuery find() method not working in AngularJS directive

You can do it like this:

 var myApp = angular.module('myApp', [])
  .controller('Ctrl', ['$scope', function($scope) {
     $scope.aaa = 3432
 }])
 .directive('test', function () {
    return {
       link: function (scope, elm, attr) {
           var look = elm.children('#findme').addClass("addedclass");
           console.log(look);
        }
   };
});

<div ng-app="myApp" ng-controller="Ctrl">
   <div test>TEST Div
      <div id="findme">{{aaa}}</div>
   </div>
</div>

http://jsfiddle.net/FZGKA/133/

Install tkinter for Python

It is not very easy to install Tkinter locally to use with system-provided Python. You may build it from sources, but this is usually not the best idea with a binary package-based distro you're apparently running.

It's safer to apt-get install python-tk on your machine(s). (Works on Debian-derived distributions like for Ubuntu; refer to your package manager and package list on other distributions.)

HTML - how can I show tooltip ONLY when ellipsis is activated

Here's a Vanilla JavaScript solution:

_x000D_
_x000D_
(function init() {_x000D_
_x000D_
  var cells = document.getElementsByClassName("cell");_x000D_
_x000D_
  for(let index = 0; index < cells.length; ++index) {_x000D_
    let cell = cells.item(index);_x000D_
    cell.addEventListener('mouseenter', setTitleIfNecessary, false);_x000D_
  }_x000D_
_x000D_
  function setTitleIfNecessary() {_x000D_
    if(this.offsetWidth < this.scrollWidth) {_x000D_
      this.setAttribute('title', this.innerHTML);_x000D_
    }_x000D_
  }_x000D_
_x000D_
})();
_x000D_
.cell {_x000D_
  white-space: nowrap;_x000D_
  overflow: hidden;_x000D_
  text-overflow: ellipsis;_x000D_
  border: 1px;_x000D_
  border-style: solid;_x000D_
  width: 120px; _x000D_
}
_x000D_
<div class="cell">hello world!</div>_x000D_
<div class="cell">hello mars! kind regards, world</div>
_x000D_
_x000D_
_x000D_

JQuery Calculate Day Difference in 2 date textboxes

Number of days calculation between two dates.

    $(document).ready(function () {
        $('.submit').on('click', function () {
            var startDate = $('.start-date').val();
            var endDate = $('.end-date').val();

            var start = new Date(startDate);
            var end = new Date(endDate);

            var diffDate = (end - start) / (1000 * 60 * 60 * 24);
            var days = Math.round(diffDate);
        });
    });

How to do scanf for single char in C

The only code that worked for me is:

scanf(" %c",&c);

I was having the same problem, and only with single characters. After an hour of random testing I can not report an issue yet. One would think that C would have by now a bullet-proof function to retrieve single characters from the keyboard, and not an array of possible hackarounds... Just saying...

ssh: connect to host github.com port 22: Connection timed out

The answer above gave me the information needed to resolve this issue. In my case the url was incorrectly starting with ssh:///

To check the url in your git config is correct, open the git config file :-

git config --local -e

Check the url entry. It should NOT have ssh:/// at the start.

Incorrect entry:

 url = ssh:///[email protected]:username/repo.git

Correct entry:

 url = [email protected]:username/repo.git

If your url is correct, then the next step would be to try the answer above that suggests changing protocol to http.

How to remove constraints from my MySQL table?

Mysql has a special syntax for dropping foreign key constraints:

ALTER TABLE tbl_magazine_issue
  DROP FOREIGN KEY FK_tbl_magazine_issue_mst_users

How to recover just deleted rows in mysql?

There is another solution, if you have binary logs active on your server you can use mysqlbinlog

generate a sql file with it

mysqlbinlog binary_log_file > query_log.sql

then search for your missing rows. If you don't have it active, no other solution. Make backups next time.

How SQL query result insert in temp table?

Suppose your existing reporting query is

Select EmployeeId,EmployeeName 
from Employee 
Where EmployeeId>101 order by EmployeeName

and you have to save this data into temparory table then you query goes to

Select EmployeeId,EmployeeName 
into #MyTempTable 
from Employee 
Where EmployeeId>101 order by EmployeeName  

php exec() is not executing the command

You might also try giving the full path to the binary you're trying to run. That solved my problem when trying to use ImageMagick.

Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

Simply download javax.servlet.jsp.jstl.jar and add to your build path and WEB-INF/lib if you simply developing dynamic web application.

When you develop dynamic web application using maven then add javax.servlet.jsp.jstl dependency in pom file.

Thanks

nirmalrajsanjeev

Put search icon near textbox using bootstrap

Adding a class with a width of 90% to your input element and adding the following input-icon class to your span would achieve what you want I think.

.input { width: 90%; }
.input-icon {
    display: inline-block;
    height: 22px;
    width: 22px;
    line-height: 22px;
    text-align: center;
    color: #000;
    font-size: 12px;
    font-weight: bold;
    margin-left: 4px;
}

EDIT Per dan's suggestion, it would not be wise to use .input as the class name, some more specific would be advised. I was simply using .input as a generic placeholder for your css

Twitter Bootstrap 3 Sticky Footer

Using flexbox is the easiest way I have found, from the guys of CSS-tricks. This is true sticky-footer, it works when the content is < 100% of the page and > 100% of the page:

<body>
  <div class="content">
  content
</div>
<footer></footer>
</body>

And CSS:

html {
  height: 100%;
}
body {
  min-height: 100%;
  display: flex;
  flex-direction: column;
}
.content {
  flex: 1;
}

Note that this is bootstrap-agnostic, so it works with bootstrap and without it.

How to get data out of a Node.js http get request

This is my solution, although for sure you can use a lot of modules that give you the object as a promise or similar. Anyway, you were missing another callback

function getData(callbackData){
  var http = require('http');
  var str = '';

  var options = {
        host: 'www.random.org',
        path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
  };

  callback = function(response) {

        response.on('data', function (chunk) {
              str += chunk;
        });

        response.on('end', function () {
              console.log(str);
          callbackData(str);
        });

        //return str;
  }

  var req = http.request(options, callback).end();

  // These just return undefined and empty
  console.log(req.data);
  console.log(str);
}

somewhere else

getData(function(data){
// YOUR CODE HERE!!!
})

Calling a function of a module by using its name (a string)

locals()["myfunction"]()

or

globals()["myfunction"]()

locals returns a dictionary with a current local symbol table. globals returns a dictionary with global symbol table.

Android dependency has different version for the compile and runtime

Replace a hard coded version to + example:

implementation 'com.google.android.gms:play-services-base:+'
implementation 'com.google.android.gms:play-services-maps:+'

Send form data using ajax

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

Manually map column names with class properties

Kaleb Pederson's solution worked for me. I updated the ColumnAttributeTypeMapper to allow a custom attribute (had requirement for two different mappings on same domain object) and updated properties to allow private setters in cases where a field needed to be derived and the types differed.

public class ColumnAttributeTypeMapper<T,A> : FallbackTypeMapper where A : ColumnAttribute
{
    public ColumnAttributeTypeMapper()
        : base(new SqlMapper.ITypeMap[]
            {
                new CustomPropertyTypeMap(
                   typeof(T),
                   (type, columnName) =>
                       type.GetProperties( BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance).FirstOrDefault(prop =>
                           prop.GetCustomAttributes(true)
                               .OfType<A>()
                               .Any(attr => attr.Name == columnName)
                           )
                   ),
                new DefaultTypeMap(typeof(T))
            })
    {
        //
    }
}

Allow anything through CORS Policy

I've your same requirements on a public API for which I used rails-api.

I've also set header in a before filter. It looks like this:

headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
headers['Access-Control-Request-Method'] = '*'
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'

It seems you missed the Access-Control-Request-Method header.

What does the regex \S mean in JavaScript?

\s matches whitespace (spaces, tabs and new lines). \S is negated \s.

SELECT DISTINCT on one column

The simplest solution would be to use a subquery for finding the minimum ID matching your query. In the subquery you use GROUP BY instead of DISTINCT:

SELECT * FROM [TestData] WHERE [ID] IN (
   SELECT MIN([ID]) FROM [TestData]
   WHERE [SKU] LIKE 'FOO-%'
   GROUP BY [PRODUCT]
)

SQL Server PRINT SELECT (Print a select query result)?

If you want to print multiple rows, you can iterate through the result by using a cursor. e.g. print all names from sys.database_principals

DECLARE @name nvarchar(128)

DECLARE cur CURSOR FOR
SELECT name FROM sys.database_principals

OPEN cur

FETCH NEXT FROM cur INTO @name;
WHILE @@FETCH_STATUS = 0
BEGIN   
PRINT @name
FETCH NEXT FROM cur INTO @name;
END

CLOSE cur;
DEALLOCATE cur;

How do I see the commit differences between branches in git?

You can easily do that with

git log master..branch-X

That will show you commits that branch-X has but master doesn't.

How can I do a case insensitive string comparison?

This is not the best practice in .NET framework (4 & +) to check equality

String.Compare(x.Username, (string)drUser["Username"], 
                  StringComparison.OrdinalIgnoreCase) == 0

Use the following instead

String.Equals(x.Username, (string)drUser["Username"], 
                   StringComparison.OrdinalIgnoreCase) 

MSDN recommends:

  • Use an overload of the String.Equals method to test whether two strings are equal.
  • Use the String.Compare and String.CompareTo methods to sort strings, not to check for equality.

Sorting a Dictionary in place with respect to keys

Take a look at SortedDictionary, there's even a constructor overload so you can pass in your own IComparable for the comparisons.