Programs & Examples On #Dynamic jasper

DynamicJasper (DJ) is an open source free library that hides the complexity of Jasper Reports.

Font is not available to the JVM with Jasper Reports

I faced the issue with my web application based on Spring 3 and deployed on Weblogic 10.3 on Oracle Linux 6. The solution mentioned at the link did not work for me.

I had to take the following steps - 1. Copy the Arial*.ttf font files to JROCKIT_JAVA_HOME/jre/lib/fonts directory 2. Make entries of the fonts in fontconfig.properties.src 3. Restart the cluster from Weblogic console

filename.Arial=Arial.ttf
filename.Arial_Bold=Arial_Bold.ttf
filename.Arial_Italic=Arial_Italic.ttf
filename.Arial_Bold_Italic=Arial_Bold_Italic.ttf

Why should you use strncpy instead of strcpy?

The strncpy() function was designed with a very particular problem in mind: manipulating strings stored in the manner of original UNIX directory entries. These used a fixed sized array, and a nul-terminator was only used if the filename was shorter than the array.

That's what's behind the two oddities of strncpy():

  • It doesn't put a nul-terminator on the destination if it is completely filled; and
  • It always completely fills the destination, with nuls if necessary.

For a "safer strcpy()", you are better off using strncat() like so:

if (dest_size > 0)
{
    dest[0] = '\0';
    strncat(dest, source, dest_size - 1);
}

That will always nul-terminate the result, and won't copy more than necessary.

Passing JavaScript array to PHP through jQuery $.ajax

I should be like this:

$.post(submitAddress, { 'yourArrayName' : javaScriptArrayToSubmitToServer },
  function(response, status, xhr) {
    alert("POST returned: \n" + response + "\n\n");
  })

Kill Attached Screen in Linux

Suppose your screen id has a pattern. Then you can use the following code to kill all the attached screen at once.

result=$(screen -ls | grep 'pattern_of_screen_id' -o)
for i in $result; 
do      
    `screen -X -S $i quit`;
done

Convert string to float?

Try this:

String yourVal = "20.5";
float a = (Float.valueOf(yourVal)).floatValue(); 
System.out.println(a);

Append values to a set in Python

You can also use the | operator to concatenate two sets (union in set theory):

>>> my_set = {1}
>>> my_set = my_set | {2}
>>> my_set
{1, 2}

Or a shorter form using |=:

>>> my_set = {1}
>>> my_set |= {2}
>>> my_set
{1, 2}

Note: In versions prior to Python 2.7, use set([...]) instead of {...}.

Replacing Spaces with Underscores

As of others have explained how to do it using str_replace, you can also use regex to achieve this.

$name = preg_replace('/\s+/', '_', $name);

Best practice to validate null and empty collection in Java

Personally, I prefer to use empty collections instead of null and have the algorithms work in a way that for the algorithm it does not matter if the collection is empty or not.

Create Directory When Writing To File In Node.js

If you don't want to use any additional package, you can call the following function before creating your file:

var path = require('path'),
    fs = require('fs');

function ensureDirectoryExistence(filePath) {
  var dirname = path.dirname(filePath);
  if (fs.existsSync(dirname)) {
    return true;
  }
  ensureDirectoryExistence(dirname);
  fs.mkdirSync(dirname);
}

Check if an apt-get package is installed and then install it if it's not on Linux

To check if packagename was installed, type:

dpkg -s <packagename>

You can also use dpkg-query that has a neater output for your purpose, and accepts wild cards, too.

dpkg-query -l <packagename>

To find what package owns the command, try:

dpkg -S `which <command>`

For further details, see article Find out if package is installed in Linux and dpkg cheat sheet.

Master Page Weirdness - "Content controls have to be top-level controls in a content page or a nested master page that references a master page."

Better late than never i suppose... you get the option to set the MASTERPAGE only of you are developing a WEB SITE (FILE>NEW>WEBSITE)... but not when you create an ASP.NET project (FILE>NEW>PROJECT) - there you have to set the Masterpage using the properties of the newly created webform and it's up to you to modify the ASPX source to make it master page compliant (ie, removing the stock HTML, etc...)

Limit Get-ChildItem recursion depth

Use this to limit the depth to 2:

Get-ChildItem \*\*\*,\*\*,\*

The way it works is that it returns the children at each depth 2,1 and 0.


Explanation:

This command

Get-ChildItem \*\*\*

returns all items with a depth of two subfolders. Adding \* adds an additional subfolder to search in.

In line with the OP question, to limit a recursive search using get-childitem you are required to specify all the depths that can be searched.

How to use PHP's password_hash to hash and verify passwords

I’ve built a function I use all the time for password validation and to create passwords, e.g. to store them in a MySQL database. It uses a randomly generated salt which is way more secure than using a static salt.

function secure_password($user_pwd, $multi) {

/*
    secure_password ( string $user_pwd, boolean/string $multi ) 

    *** Description: 
        This function verifies a password against a (database-) stored password's hash or
        returns $hash for a given password if $multi is set to either true or false

    *** Examples:
        // To check a password against its hash
        if(secure_password($user_password, $row['user_password'])) {
            login_function();
        } 
        // To create a password-hash
        $my_password = 'uber_sEcUrE_pass';
        $hash = secure_password($my_password, true);
        echo $hash;
*/

// Set options for encryption and build unique random hash
$crypt_options = ['cost' => 11, 'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM)];
$hash = password_hash($user_pwd, PASSWORD_BCRYPT, $crypt_options);

// If $multi is not boolean check password and return validation state true/false
if($multi!==true && $multi!==false) {
    if (password_verify($user_pwd, $table_pwd = $multi)) {
        return true; // valid password
    } else {
        return false; // invalid password
    }
// If $multi is boolean return $hash
} else return $hash;

}

Is __init__.py not required for packages in Python 3.3+

I would say that one should omit the __init__.py only if one wants to have the implicit namespace package. If you don't know what it means, you probably don't want it and therefore you should continue to use the __init__.py even in Python 3.

Unable to read data from the transport connection : An existing connection was forcibly closed by the remote host

According to "Hans Vonn" replies.

Adding the following line before making the call resolved the issue:

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

After adding Security protocol and working fine but I have to add before every API call which is not healthy. I just upgrade .net framework version at least 4.6 and working as expected do not require to adding before every API call.

Android ListView with Checkbox and all clickable

Set the listview adapter to "simple_list_item_multiple_choice"

ArrayAdapter<String> adapter;

List<String> values; // put values in this

//Put in listview
adapter = new ArrayAdapter<UserProfile>(
this,
android.R.layout.simple_list_item_multiple_choice, 
values);
setListAdapter(adapter);    

How to make a HTML list appear horizontally instead of vertically using CSS only?

You will have to use something like below

_x000D_
_x000D_
#menu ul{_x000D_
  list-style: none;_x000D_
}_x000D_
#menu li{_x000D_
  display: inline;_x000D_
}_x000D_
 
_x000D_
<div id="menu">_x000D_
  <ul>_x000D_
    <li>First menu item</li>_x000D_
    <li>Second menu item</li>_x000D_
    <li>Third menu item</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' with pdo

For me it was missing MySQL PDO, I recompiled my PHP with the --with-pdo-mysql option, installed it and restarted apache and it was all working

Script Tag - async & defer

This image explains normal script tag, async and defer

enter image description here

  • Async scripts are executed as soon as the script is loaded, so it doesn't guarantee the order of execution (a script you included at the end may execute before the first script file )

  • Defer scripts guarantees the order of execution in which they appear in the page.

Ref this link : http://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html

How to update the constant height constraint of a UIView programmatically?

To update a layout constraint you only need to update the constant property and call layoutIfNeeded after.

myConstraint.constant = newValue
myView.layoutIfNeeded()

How to pass integer from one Activity to another?

It's simple. On the sender side, use Intent.putExtra:

Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("intVariableName", intValue);
startActivity(myIntent);

On the receiver side, use Intent.getIntExtra:

 Intent mIntent = getIntent();
 int intValue = mIntent.getIntExtra("intVariableName", 0);

How to convert strings into integers in Python?

Try this.

x = "1"

x is a string because it has quotes around it, but it has a number in it.

x = int(x)

Since x has the number 1 in it, I can turn it in to a integer.

To see if a string is a number, you can do this.

def is_number(var):
    try:
        if var == int(var):
            return True
    except Exception:
        return False

x = "1"

y = "test"

x_test = is_number(x)

print(x_test)

It should print to IDLE True because x is a number.

y_test = is_number(y)

print(y_test)

It should print to IDLE False because y in not a number.

Generate a random date between two other dates

To chip in a pandas-based solution I use:

import pandas as pd
import numpy as np

def random_date(start, end, position=None):
    start, end = pd.Timestamp(start), pd.Timestamp(end)
    delta = (end - start).total_seconds()
    if position is None:
        offset = np.random.uniform(0., delta)
    else:
        offset = position * delta
    offset = pd.offsets.Second(offset)
    t = start + offset
    return t

I like it, because of the nice pd.Timestamp features that allow me to throw different stuff and formats at it. Consider the following few examples...

Your signature.

>>> random_date(start="1/1/2008 1:30 PM", end="1/1/2009 4:50 AM", position=0.34)
Timestamp('2008-05-04 21:06:48', tz=None)

Random position.

>>> random_date(start="1/1/2008 1:30 PM", end="1/1/2009 4:50 AM")
Timestamp('2008-10-21 05:30:10', tz=None)

Different format.

>>> random_date('2008-01-01 13:30', '2009-01-01 4:50')
Timestamp('2008-11-18 17:20:19', tz=None)

Passing pandas/datetime objects directly.

>>> random_date(pd.datetime.now(), pd.datetime.now() + pd.offsets.Hour(3))
Timestamp('2014-03-06 14:51:16.035965', tz=None)

Loop code for each file in a directory

scandir:

$files = scandir('folder/');
foreach($files as $file) {
  //do your work here
}

or glob may be even better for your needs:

$files = glob('folder/*.{jpg,png,gif}', GLOB_BRACE);
foreach($files as $file) {
  //do your work here
}

Error: Selection does not contain a main type

The entry point for Java programs is the method:

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

If you do not have this, your program will not run.

ASP.NET MVC3 Razor - Html.ActionLink style

Reviving an old question because it seems to appear at the top of search results.

I wanted to retain transition effects while still being able to style the actionlink so I came up with this solution.

  1. I wrapped the action link with a div that would contain the parent style:
<div class="parent-style-one">
      @Html.ActionLink("Homepage", "Home", "Home")
</div>
  1. Next I create the CSS for the div, this will be the parent css and will be inherited by the child elements such as the action link.
  .parent-style-one {
     /* your styles here */
  }
  1. Because all an action link is, is an element when broken down as html so you just need to target that element in your css selection:
  .parent-style-one a {
     text-decoration: none;
  }
  1. For transition effects I did this:
  .parent-style-one a:hover {
        text-decoration: underline;
        -webkit-transition-duration: 1.1s; /* Safari */
        transition-duration: 1.1s;         
  }

This way I only target the child elements of the div in this case the action link and still be able to apply transition effects.

How do I use $rootScope in Angular to store variables?

i find no reason to do this $scope.value = $rootScope.test;

$scope is already prototype inheritance from $rootScope.

Please see this example

var app = angular.module('app',[]).run(function($rootScope){
$rootScope.userName = "Rezaul Hasan";
});

now you can bind this scope variable in anywhere in app tag.

Counting number of lines, words, and characters in a text file

while(in.hasNextLine())  {
        lines++;
        String line = in.nextLine();
        for(int i=0;i<line.length();i++)
        {
            if(line.charAt(i)!=' ' && line.charAt(i)!='\n')
        chars ++;
        }
        words += new StringTokenizer(line, " ,;:.").countTokens();
    }

Permission denied (publickey). fatal: The remote end hung up unexpectedly while pushing back to git repository

Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/

How do I vertically align text in a paragraph?

If the answers that involve tables or setting line-height don't work for you, you can experiment with wrapping the p element in a div and style its positioning relative to the height of the parent div.

_x000D_
_x000D_
.parent-div{_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background-color: blue;_x000D_
}_x000D_
_x000D_
.text-div{_x000D_
  position: relative;_x000D_
  top: 50%;_x000D_
  transform: translateY(-50%);_x000D_
}_x000D_
_x000D_
p.event_desc{_x000D_
  font: bold 12px "Helvetica Neue", Helvetica, Arial, sans-serif;_x000D_
  color: white;_x000D_
  text-align: center;_x000D_
}
_x000D_
<div class="parent-div">_x000D_
  <div class="text-div">_x000D_
   <p class="event_desc">_x000D_
    MY TEXT_x000D_
   </p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Javascript AES encryption

Judging from my own experience, asmcrypto.js provides the fastest AES implementation in JavaScript (especially in Firefox since it can fully leverage asm.js there).

From the readme:

Chrome/31.0
SHA256: 51 MiB/s (9 times faster than SJCL and CryptoJS)
AES-CBC: 47 MiB/s (13 times faster than CryptoJS and 20 times faster than SJCL)

Firefox/26.0
SHA256: 144 MiB/s (5 times faster than CryptoJS and 20 times faster than SJCL)
AES-CBC: 81 MiB/s (3 times faster than CryptoJS and 8 times faster than SJCL)

Edit: The Web Cryptography API is now implemented in most browsers and should be used as the primary solution if you care about performance. Be aware that IE11 implemented an earlier draft version of the standard which did not use promises.

Some examples can be found here:

Is it possible to set a timeout for an SQL query on Microsoft SQL server?

I might suggest 2 things.

1) If your query takes a lot of time because it´s using several tables that might involve locks, a quite fast solution is to run your queries with the "NoLock" hint.

Simply add Select * from YourTable WITH (NOLOCK) in all your table references an that will prevent your query to block for concurrent transactions.

2) if you want to be sure that all of your queries runs in (let´s say) less than 5 seconds, then you could add what @talha proposed, that worked sweet for me

Just add at the top of your execution

SET LOCK_TIMEOUT 5000;   --5 seconds.

And that will cause that your query takes less than 5 or fail. Then you should catch the exception and rollback if needed.

Hope it helps.

Generate your own Error code in swift 3

You can create enums to deal with errors :)

enum RikhError: Error {
    case unknownError
    case connectionError
    case invalidCredentials
    case invalidRequest
    case notFound
    case invalidResponse
    case serverError
    case serverUnavailable
    case timeOut
    case unsuppotedURL
 }

and then create a method inside enum to receive the http response code and return the corresponding error in return :)

static func checkErrorCode(_ errorCode: Int) -> RikhError {
        switch errorCode {
        case 400:
            return .invalidRequest
        case 401:
            return .invalidCredentials
        case 404:
            return .notFound
        //bla bla bla
        default:
            return .unknownError
        }
    }

Finally update your failure block to accept single parameter of type RikhError :)

I have a detailed tutorial on how to restructure traditional Objective - C based Object Oriented network model to modern Protocol Oriented model using Swift3 here https://learnwithmehere.blogspot.in Have a look :)

Hope it helps :)

Get random item from array

If you don't mind picking the same item again at some other time:

$items[rand(0, count($items) - 1)];

How to call a javaScript Function in jsp on page load without using <body onload="disableView()">

Either use window.onload this way

<script>
    window.onload = function() {
        // ...
    }
</script>

or alternatively

<script>
    window.onload = functionName;
</script>

(yes, without the parentheses)


Or just put the script at the very bottom of page, right before </body>. At that point, all HTML DOM elements are ready to be accessed by document functions.

<body>
    ...

    <script>
        functionName();
    </script>
</body>

How to upgrade Python version to 3.7?

On ubuntu you can add this PPA Repository and use it to install python 3.7: https://launchpad.net/~jonathonf/+archive/ubuntu/python-3.7

Or a different PPA that provides several Python versions is Deadsnakes: https://launchpad.net/~deadsnakes/+archive/ubuntu/ppa

See also here: https://askubuntu.com/questions/865554/how-do-i-install-python-3-6-using-apt-get (I know it says 3.6 in the url, but the deadsnakes ppa also contains 3.7 so you can use it for 3.7 just the same)

If you want "official" you'd have to install it from the sources from the site, get the code (which you already downloaded) and do this:

tar -xf Python-3.7.0.tar.xz
cd Python-3.7.0
./configure
make
sudo make install        <-- sudo is required.

This might take a while

Window.open and pass parameters by post method

I created a function to generate a form, based on url, target and an object as the POST/GET data and submit method. It supports nested and mixed types within that object, so it can fully replicate any structure you feed it: PHP automatically parses it and returns it as a nested array. However, there is a single restriction: the brackets [ and ] must not be part of any key in the object (like {"this [key] is problematic" : "hello world"}). If someone knows how to escape it properly, please do tell!

Without further ado, here is the source:

_x000D_
_x000D_
function getForm(url, target, values, method) {_x000D_
  function grabValues(x) {_x000D_
    var path = [];_x000D_
    var depth = 0;_x000D_
    var results = [];_x000D_
_x000D_
    function iterate(x) {_x000D_
      switch (typeof x) {_x000D_
        case 'function':_x000D_
        case 'undefined':_x000D_
        case 'null':_x000D_
          break;_x000D_
        case 'object':_x000D_
          if (Array.isArray(x))_x000D_
            for (var i = 0; i < x.length; i++) {_x000D_
              path[depth++] = i;_x000D_
              iterate(x[i]);_x000D_
            }_x000D_
          else_x000D_
            for (var i in x) {_x000D_
              path[depth++] = i;_x000D_
              iterate(x[i]);_x000D_
            }_x000D_
          break;_x000D_
        default:_x000D_
          results.push({_x000D_
            path: path.slice(0),_x000D_
            value: x_x000D_
          })_x000D_
          break;_x000D_
      }_x000D_
      path.splice(--depth);_x000D_
    }_x000D_
    iterate(x);_x000D_
    return results;_x000D_
  }_x000D_
  var form = document.createElement("form");_x000D_
  form.method = method;_x000D_
  form.action = url;_x000D_
  form.target = target;_x000D_
_x000D_
  var values = grabValues(values);_x000D_
_x000D_
  for (var j = 0; j < values.length; j++) {_x000D_
    var input = document.createElement("input");_x000D_
    input.type = "hidden";_x000D_
    input.value = values[j].value;_x000D_
    input.name = values[j].path[0];_x000D_
    for (var k = 1; k < values[j].path.length; k++) {_x000D_
      input.name += "[" + values[j].path[k] + "]";_x000D_
    }_x000D_
    form.appendChild(input);_x000D_
  }_x000D_
  return form;_x000D_
}
_x000D_
_x000D_
_x000D_

Usage example:

_x000D_
_x000D_
document.body.onclick = function() {_x000D_
  var obj = {_x000D_
    "a": [1, 2, [3, 4]],_x000D_
    "b": "a",_x000D_
    "c": {_x000D_
      "x": [1],_x000D_
      "y": [2, 3],_x000D_
      "z": [{_x000D_
        "a": "Hello",_x000D_
        "b": "World"_x000D_
      }, {_x000D_
        "a": "Hallo",_x000D_
        "b": "Welt"_x000D_
      }]_x000D_
    }_x000D_
  };_x000D_
_x000D_
  var form = getForm("http://example.com", "_blank", obj, "post");_x000D_
_x000D_
  document.body.appendChild(form);_x000D_
  form.submit();_x000D_
  form.parentNode.removeChild(form);_x000D_
}
_x000D_
_x000D_
_x000D_

Retrieve column values of the selected row of a multicolumn Access listbox

Just a little addition. If you've only selected 1 row then the code below will select the value of a column (index of 4, but 5th column) for the selected row:

me.lstIssues.Column(4)

This saves having to use the ItemsSelected property.

Kristian

What underlies this JavaScript idiom: var self = this?

function Person(firstname, lastname) {
  this.firstname = firstname;

  this.lastname = lastname;
  this.getfullname = function () {
    return `${this.firstname}   ${this.lastname}`;
  };

  let that = this;
  this.sayHi = function() {
    console.log(`i am this , ${this.firstname}`);
    console.log(`i am that , ${that.firstname}`);
  };
}

let thisss = new Person('thatbetty', 'thatzhao');

let thatt = {firstname: 'thisbetty', lastname: 'thiszhao'};

thisss.sayHi.call(thatt);

In Oracle SQL: How do you insert the current date + time into a table?

It only seems to because that is what it is printing out. But actually, you shouldn't write the logic this way. This is equivalent:

insert into errortable (dateupdated, table1id)
    values (sysdate, 1083);

It seems silly to convert the system date to a string just to convert it back to a date.

If you want to see the full date, then you can do:

select TO_CHAR(dateupdated, 'YYYY-MM-DD HH24:MI:SS'), table1id
from errortable;

YAML: Do I need quotes for strings in YAML?

After a brief review of the YAML cookbook cited in the question and some testing, here's my interpretation:

  • In general, you don't need quotes.
  • Use quotes to force a string, e.g. if your key or value is 10 but you want it to return a String and not a Fixnum, write '10' or "10".
  • Use quotes if your value includes special characters, (e.g. :, {, }, [, ], ,, &, *, #, ?, |, -, <, >, =, !, %, @, \).
  • Single quotes let you put almost any character in your string, and won't try to parse escape codes. '\n' would be returned as the string \n.
  • Double quotes parse escape codes. "\n" would be returned as a line feed character.
  • The exclamation mark introduces a method, e.g. !ruby/sym to return a Ruby symbol.

Seems to me that the best approach would be to not use quotes unless you have to, and then to use single quotes unless you specifically want to process escape codes.

Update

"Yes" and "No" should be enclosed in quotes (single or double) or else they will be interpreted as TrueClass and FalseClass values:

en:
  yesno:
    'yes': 'Yes'
    'no': 'No'

Refreshing Web Page By WebDriver When Waiting For Specific Condition

5 different ways to refresh a webpage using Selenium Webdriver

There is no special extra coding. I have just used the existing functions in different ways to get it work. Here they are :

  1. Using sendKeys.Keys method

    driver.get("https://accounts.google.com/SignUp");
    driver.findElement(By.id("firstname-placeholder")).sendKeys(Keys.F5);
    
  2. Using navigate.refresh() method

    driver.get("https://accounts.google.com/SignUp");  
    driver.navigate().refresh();
    
  3. Using navigate.to() method

    driver.get("https://accounts.google.com/SignUp");  
    driver.navigate().to(driver.getCurrentUrl());
    
  4. Using get() method

    driver.get("https://accounts.google.com/SignUp");  
    driver.get(driver.getCurrentUrl());
    
  5. Using sendKeys() method

    driver.get("https://accounts.google.com/SignUp"); 
    driver.findElement(By.id("firstname-placeholder")).sendKeys("\uE035");
    

Calculating distance between two geographic locations

I wanted to implement myself this, i ended up reading the Wikipedia page on Great-circle distance formula, because no code was readable enough for me to use as basis.

C# example

    /// <summary>
    /// Calculates the distance between two locations using the Great Circle Distance algorithm
    /// <see cref="https://en.wikipedia.org/wiki/Great-circle_distance"/>
    /// </summary>
    /// <param name="first"></param>
    /// <param name="second"></param>
    /// <returns></returns>
    private static double DistanceBetween(GeoLocation first, GeoLocation second)
    {
        double longitudeDifferenceInRadians = Math.Abs(ToRadians(first.Longitude) - ToRadians(second.Longitude));

        double centralAngleBetweenLocationsInRadians = Math.Acos(
            Math.Sin(ToRadians(first.Latitude)) * Math.Sin(ToRadians(second.Latitude)) +
            Math.Cos(ToRadians(first.Latitude)) * Math.Cos(ToRadians(second.Latitude)) *
            Math.Cos(longitudeDifferenceInRadians));

        const double earthRadiusInMeters = 6357 * 1000;

        return earthRadiusInMeters * centralAngleBetweenLocationsInRadians;
    }

    private static double ToRadians(double degrees)
    {
        return degrees * Math.PI / 180;
    }

RegEx to parse or validate Base64 data

From the RFC 4648:

Base encoding of data is used in many situations to store or transfer data in environments that, perhaps for legacy reasons, are restricted to US-ASCII data.

So it depends on the purpose of usage of the encoded data if the data should be considered as dangerous.

But if you’re just looking for a regular expression to match Base64 encoded words, you can use the following:

^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$

jQuery 'input' event

oninput event is very useful to track input fields changes.

However it is not supported in IE version < 9. But older IE versions has its own proprietary event onpropertychange that does the same as oninput.

So you can use it this way:

$(':input').on('input propertychange');

To have a full crossbrowser support.

Since the propertychange can be triggered for ANY property change, for example, the disabled property is changed, then you want to do include this:

$(':input').on('propertychange input', function (e) {
    var valueChanged = false;

    if (e.type=='propertychange') {
        valueChanged = e.originalEvent.propertyName=='value';
    } else {
        valueChanged = true;
    }
    if (valueChanged) {
        /* Code goes here */
    }
});

c# dictionary How to add multiple values for single key?

Dictionary<string, List<string>> dictionary = new Dictionary<string,List<string>>();

foreach(string key in keys) {
    if(!dictionary.ContainsKey(key)) {
        //add
        dictionary.Add(key, new List<string>());
    }
    dictionary[key].Add("theString");
}

If the key doesn't exist, a new List is added (inside if). Else the key exists, so just add a new value to the List under that key.

PHP list of specific files in a directory

I use this code:

<?php

{
//foreach (glob("images/*.jpg") as $large) 
foreach (glob("*.xml") as $filename) { 

//echo "$filename\n";
//echo str_replace("","","$filename\n");

echo str_replace("","","<a href='$filename'>$filename</a>\n");

}
}


?>

How to use mysql JOIN without ON condition?

MySQL documentation covers this topic.

Here is a synopsis. When using join or inner join, the on condition is optional. This is different from the ANSI standard and different from almost any other database. The effect is a cross join. Similarly, you can use an on clause with cross join, which also differs from standard SQL.

A cross join creates a Cartesian product -- that is, every possible combination of 1 row from the first table and 1 row from the second. The cross join for a table with three rows ('a', 'b', and 'c') and a table with four rows (say 1, 2, 3, 4) would have 12 rows.

In practice, if you want to do a cross join, then use cross join:

from A cross join B

is much better than:

from A, B

and:

from A join B -- with no on clause

The on clause is required for a right or left outer join, so the discussion is not relevant for them.

If you need to understand the different types of joins, then you need to do some studying on relational databases. Stackoverflow is not an appropriate place for that level of discussion.

SQL: Combine Select count(*) from multiple tables

select 
  (select count(*) from foo) as foo
, (select count(*) from bar) as bar
, ...

Error message "No exports were found that match the constraint contract name"

I am using Visual Studio 2012. After installing the Visual Studio 2013 web express, when I want to run or open any project in Visual Studio 2012 it shows me the following error:

"no exports were found that match the constraint contract name".

I also tried the above solution for clearing the ComponentModelCache, but I did not find the folder. I solves my problem just by: Repair Visual Studio 2012

For the Express versions of the software, the folder you need is in a slightly different place(s): For Express 2012 for Web it is C:\Users\XXXXXXXX\AppData\Local\Microsoft\VWDExpress - not in the Visual Studio folder.

Locate Git installation folder on Mac OS X

If you have fresh installation / update of Xcode, it is possible that your git binary can't be executed (I had mine under /usr/bin/git). To fix this problem just run the Xcode and "Accept" license conditions and try again, it should work.

How to insert date values into table

You can also use the "timestamp" data type where it just needs "dd-mm-yyyy"

Like:

insert into emp values('12-12-2012');

considering there is just one column in the table... You can adjust the insertion values according to your table.

How to open a second activity on click of button in android app

You can move to desired activity on button click. just add
android:onClick="timerApp"this line.

xml:

 <Button
        android:id="@+id/timer_app"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="timerApp"
        android:text="Click To run Timer Activity" />

In your main activity just add this method:

 public void timerApp(View view){
        Intent intent= new Intent(MainActivity.this,TimerActivity.class);
        startActivity(intent);
    }

OR in onCreate() method add below code

Button btn =findViewById(R.id.timer_app);//Don't need to type casting in android studio 3

btn.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Intent intent = new Intent(MainActivity.this, TimerActivity.class);
        startActivity(intent);       
    }  
});

What port is used by Java RMI connection?

Depends how you implement the RMI, you can set the registry port (registry is a "unique point of services"). If you don't set a explicit port, the registry will assume the port 1099 by default. In some cases, you have a firewall, and the firewall don't allow your rmi-client to see the stubs and objects behind the registry, because this things are running in randomically port, a different port that the registry use, and this port is blocked by firewall - of course. If you use RmiServiceExporter to configure your RmiServer, you can use the method rmiServiceExporter.setServicePort(port) to fixed the rmi port, and open this port in the firewall.

Edit: I resolve this issue with this post: http://www.mscharhag.com/java/java-rmi-things-to-remember

How do I use DrawerLayout to display over the ActionBar/Toolbar and under the status bar?

This is the most simple, and it worked for me:

In the values-21:

<resources>
    <style name="AppTheme" parent="AppTheme.Base">
        ...
        <item name="android:windowTranslucentStatus">true</item>
    </style>
    <dimen name="topMargin">25dp</dimen>
</resources>

In the values:

<resources>
    <dimen name="topMargin">0dp</dimen>
</resources>

And set to your toolbar

android:layout_marginTop="@dimen/topMargin"

error C4996: 'scanf': This function or variable may be unsafe in c programming

It sounds like it's just a compiler warning.

Usage of scanf_s prevents possible buffer overflow.
See: http://code.wikia.com/wiki/Scanf_s

Good explanation as to why scanf can be dangerous: Disadvantages of scanf

So as suggested, you can try replacing scanf with scanf_s or disable the compiler warning.

Get list of a class' instance methods

$ irb --simple-prompt

class TestClass
  def method1
  end

  def method2
  end

  def method3
  end
end

tc_list = TestClass.instance_methods(false)
#[:method1, :method2, :method3]
puts tc_list
#method1
#method2
#method3

Center align "span" text inside a div

If you know the width of the span you could just stuff in a left margin.

Try this:

.center { text-align: center}
div.center span { display: table; }

Add the "center: class to your .

If you want some spans centered, but not others, replace the "div.center span" in your style sheet to a class (e.g "center-span") and add that class to the span.

Get dates from a week number in T-SQL

How about a function that jumps to the week before that week number and then steps through the next few days until the week number changes (max 7 steps), returning the new date?

CREATE FUNCTION dbo.fnGetDateFromWeekNo
(@weekNo int , @yearNo  int)
RETURNS smalldatetime
AS
BEGIN 

DECLARE @tmpDate smalldatetime


set @tmpdate= cast(cast (@yearNo as varchar) + '-01-01' as smalldatetime)
-- jump forward x-1 weeks to save counting through the whole year 
set @tmpdate=dateadd(wk,@weekno-1,@tmpdate)

-- make sure weekno is not out of range
if @WeekNo <= datepart(wk,cast(cast (@yearNo as varchar) + '-12-31' as smalldatetime))
BEGIN
    WHILE (datepart(wk,@tmpdate)<@WeekNo)
    BEGIN
        set @tmpdate=dateadd(dd,1,@tmpdate)
    END
END
ELSE
BEGIN
    -- invalid weeknumber given
    set @tmpdate=null
END


RETURN @tmpDate

END

How to declare and display a variable in Oracle

If using sqlplus you can define a variable thus:

define <varname>=<varvalue>

And you can display the value by:

define <varname>

And then use it in a query as, for example:

select *
from tab1
where col1 = '&varname';

Keeping session alive with Curl and PHP

Yup, often called a 'cookie jar' Google should provide many examples:

http://devzone.zend.com/16/php-101-part-10-a-session-in-the-cookie-jar/

http://curl.haxx.se/libcurl/php/examples/cookiejar.html <- good example IMHO

Copying that last one here so it does not go away...

Login to on one page and then get another page passing all cookies from the first page along Written by Mitchell

<?php
/*
This script is an example of using curl in php to log into on one page and 
then get another page passing all cookies from the first page along with you.
If this script was a bit more advanced it might trick the server into 
thinking its netscape and even pass a fake referer, yo look like it surfed 
from a local page.
*/

$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"http://www.myterminal.com/checkpwd.asp");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "UserID=username&password=passwd");

ob_start();      // prevent any output
curl_exec ($ch); // execute the curl command
ob_end_clean();  // stop preventing output

curl_close ($ch);
unset($ch);

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"http://www.myterminal.com/list.asp");

$buf2 = curl_exec ($ch);

curl_close ($ch);

echo "<PRE>".htmlentities($buf2);
?>  

How to create a sticky left sidebar menu using bootstrap 3?

You can also try to use a Polyfill like Fixed-Sticky. Especially when you are using Bootstrap4 the affix component is no longer included:

Dropped the Affix jQuery plugin. We recommend using a position: sticky polyfill instead.

How to use forEach in vueJs?

You can also use .map() as:

var list=[];

response.data.message.map(function(value, key) {
     list.push(value);
   });

Failed linking file resources

It is a xml error for some reason may be because of deleting a view or string in another view or may be for missing " or /> ..... etc

But here I am using a good technique to figure out where is the problem exactly :-

  • Go to every single xml file and minimize the root element if you find something like this so you got where is the error, fix it then repeat the process for all files.

  • If the file has an error you will see three dots with red color enter image description here
  • Fix the error here I removed this line because this array is not in the string file any more. enter image description here
  • Now you can see there is no error in this file any more if you still got the main error so you have to repeat this process again to all xml files until you solve the error enter image description here

I know it is not the solution of the main problem but it will make you find where is the error quickly and save you time.

Update

There is another way you can find out easily, as Bennik2000 write in comment, you can look at the right scrollbar for red lines, they also indicate errors.

Update

I found a very simple way to get where is the error exactly if it is in resource file or even java file.
1- Go to Project Window.
2- Open the file that has the error.
3- Click F2 to go to the nearest error appears (it will go to the correct line)

enter image description here

Is a Python dictionary an example of a hash table?

Yes. Internally it is implemented as open hashing based on a primitive polynomial over Z/2 (source).

Generate getters and setters in NetBeans

Position the cursor inside the class, then press ALT + Ins and select Getters and Setters from the contextual menu.

I just discovered why all ASP.Net websites are slow, and I am trying to work out what to do about it

Unless your application has specially needs, I think you have 2 approaches:

  1. Do not use session at all
  2. Use session as is and perform fine tuning as joel mentioned.

Session is not only thread-safe but also state-safe, in a way that you know that until the current request is completed, every session variable wont change from another active request. In order for this to happen you must ensure that session WILL BE LOCKED until the current request have completed.

You can create a session like behavior by many ways, but if it does not lock the current session, it wont be 'session'.

For the specific problems you mentioned I think you should check HttpContext.Current.Response.IsClientConnected. This can be useful to to prevent unnecessary executions and waits on the client, although it cannot solve this problem entirely, as this can be used only by a pooling way and not async.

Select all occurrences of selected word in VSCode

Ctrl + F2 works for me in Windows 10.

Ctrl + Shift + L starts performance logging

Javascript replace with reference to matched group?

You can use replace instead of gsub.

"hello _there_".replace(/_(.*?)_/g, "<div>\$1</div>")

Delegates in swift?

Simple Example:

protocol Work: class {
    func doSomething()
}

class Manager {
    weak var delegate: Work?
    func passAlong() {
        delegate?.doSomething()
    }
}

class Employee: Work {
    func doSomething() {
        print("Working on it")
    }
}

let manager = Manager()
let developer = Employee()
manager.delegate = developer
manager.passAlong() // PRINTS: Working on it

How to get value of a div using javascript

You can try this:

var theValue = document.getElementById("demo").getAttribute("value");

Best way to replace multiple characters in a string?

Replacing two characters

I timed all the methods in the current answers along with one extra.

With an input string of abc&def#ghi and replacing & -> \& and # -> \#, the fastest way was to chain together the replacements like this: text.replace('&', '\&').replace('#', '\#').

Timings for each function:

  • a) 1000000 loops, best of 3: 1.47 µs per loop
  • b) 1000000 loops, best of 3: 1.51 µs per loop
  • c) 100000 loops, best of 3: 12.3 µs per loop
  • d) 100000 loops, best of 3: 12 µs per loop
  • e) 100000 loops, best of 3: 3.27 µs per loop
  • f) 1000000 loops, best of 3: 0.817 µs per loop
  • g) 100000 loops, best of 3: 3.64 µs per loop
  • h) 1000000 loops, best of 3: 0.927 µs per loop
  • i) 1000000 loops, best of 3: 0.814 µs per loop

Here are the functions:

def a(text):
    chars = "&#"
    for c in chars:
        text = text.replace(c, "\\" + c)


def b(text):
    for ch in ['&','#']:
        if ch in text:
            text = text.replace(ch,"\\"+ch)


import re
def c(text):
    rx = re.compile('([&#])')
    text = rx.sub(r'\\\1', text)


RX = re.compile('([&#])')
def d(text):
    text = RX.sub(r'\\\1', text)


def mk_esc(esc_chars):
    return lambda s: ''.join(['\\' + c if c in esc_chars else c for c in s])
esc = mk_esc('&#')
def e(text):
    esc(text)


def f(text):
    text = text.replace('&', '\&').replace('#', '\#')


def g(text):
    replacements = {"&": "\&", "#": "\#"}
    text = "".join([replacements.get(c, c) for c in text])


def h(text):
    text = text.replace('&', r'\&')
    text = text.replace('#', r'\#')


def i(text):
    text = text.replace('&', r'\&').replace('#', r'\#')

Timed like this:

python -mtimeit -s"import time_functions" "time_functions.a('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.b('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.c('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.d('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.e('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.f('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.g('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.h('abc&def#ghi')"
python -mtimeit -s"import time_functions" "time_functions.i('abc&def#ghi')"

Replacing 17 characters

Here's similar code to do the same but with more characters to escape (\`*_{}>#+-.!$):

def a(text):
    chars = "\\`*_{}[]()>#+-.!$"
    for c in chars:
        text = text.replace(c, "\\" + c)


def b(text):
    for ch in ['\\','`','*','_','{','}','[',']','(',')','>','#','+','-','.','!','$','\'']:
        if ch in text:
            text = text.replace(ch,"\\"+ch)


import re
def c(text):
    rx = re.compile('([&#])')
    text = rx.sub(r'\\\1', text)


RX = re.compile('([\\`*_{}[]()>#+-.!$])')
def d(text):
    text = RX.sub(r'\\\1', text)


def mk_esc(esc_chars):
    return lambda s: ''.join(['\\' + c if c in esc_chars else c for c in s])
esc = mk_esc('\\`*_{}[]()>#+-.!$')
def e(text):
    esc(text)


def f(text):
    text = text.replace('\\', '\\\\').replace('`', '\`').replace('*', '\*').replace('_', '\_').replace('{', '\{').replace('}', '\}').replace('[', '\[').replace(']', '\]').replace('(', '\(').replace(')', '\)').replace('>', '\>').replace('#', '\#').replace('+', '\+').replace('-', '\-').replace('.', '\.').replace('!', '\!').replace('$', '\$')


def g(text):
    replacements = {
        "\\": "\\\\",
        "`": "\`",
        "*": "\*",
        "_": "\_",
        "{": "\{",
        "}": "\}",
        "[": "\[",
        "]": "\]",
        "(": "\(",
        ")": "\)",
        ">": "\>",
        "#": "\#",
        "+": "\+",
        "-": "\-",
        ".": "\.",
        "!": "\!",
        "$": "\$",
    }
    text = "".join([replacements.get(c, c) for c in text])


def h(text):
    text = text.replace('\\', r'\\')
    text = text.replace('`', r'\`')
    text = text.replace('*', r'\*')
    text = text.replace('_', r'\_')
    text = text.replace('{', r'\{')
    text = text.replace('}', r'\}')
    text = text.replace('[', r'\[')
    text = text.replace(']', r'\]')
    text = text.replace('(', r'\(')
    text = text.replace(')', r'\)')
    text = text.replace('>', r'\>')
    text = text.replace('#', r'\#')
    text = text.replace('+', r'\+')
    text = text.replace('-', r'\-')
    text = text.replace('.', r'\.')
    text = text.replace('!', r'\!')
    text = text.replace('$', r'\$')


def i(text):
    text = text.replace('\\', r'\\').replace('`', r'\`').replace('*', r'\*').replace('_', r'\_').replace('{', r'\{').replace('}', r'\}').replace('[', r'\[').replace(']', r'\]').replace('(', r'\(').replace(')', r'\)').replace('>', r'\>').replace('#', r'\#').replace('+', r'\+').replace('-', r'\-').replace('.', r'\.').replace('!', r'\!').replace('$', r'\$')

Here's the results for the same input string abc&def#ghi:

  • a) 100000 loops, best of 3: 6.72 µs per loop
  • b) 100000 loops, best of 3: 2.64 µs per loop
  • c) 100000 loops, best of 3: 11.9 µs per loop
  • d) 100000 loops, best of 3: 4.92 µs per loop
  • e) 100000 loops, best of 3: 2.96 µs per loop
  • f) 100000 loops, best of 3: 4.29 µs per loop
  • g) 100000 loops, best of 3: 4.68 µs per loop
  • h) 100000 loops, best of 3: 4.73 µs per loop
  • i) 100000 loops, best of 3: 4.24 µs per loop

And with a longer input string (## *Something* and [another] thing in a longer sentence with {more} things to replace$):

  • a) 100000 loops, best of 3: 7.59 µs per loop
  • b) 100000 loops, best of 3: 6.54 µs per loop
  • c) 100000 loops, best of 3: 16.9 µs per loop
  • d) 100000 loops, best of 3: 7.29 µs per loop
  • e) 100000 loops, best of 3: 12.2 µs per loop
  • f) 100000 loops, best of 3: 5.38 µs per loop
  • g) 10000 loops, best of 3: 21.7 µs per loop
  • h) 100000 loops, best of 3: 5.7 µs per loop
  • i) 100000 loops, best of 3: 5.13 µs per loop

Adding a couple of variants:

def ab(text):
    for ch in ['\\','`','*','_','{','}','[',']','(',')','>','#','+','-','.','!','$','\'']:
        text = text.replace(ch,"\\"+ch)


def ba(text):
    chars = "\\`*_{}[]()>#+-.!$"
    for c in chars:
        if c in text:
            text = text.replace(c, "\\" + c)

With the shorter input:

  • ab) 100000 loops, best of 3: 7.05 µs per loop
  • ba) 100000 loops, best of 3: 2.4 µs per loop

With the longer input:

  • ab) 100000 loops, best of 3: 7.71 µs per loop
  • ba) 100000 loops, best of 3: 6.08 µs per loop

So I'm going to use ba for readability and speed.

Addendum

Prompted by haccks in the comments, one difference between ab and ba is the if c in text: check. Let's test them against two more variants:

def ab_with_check(text):
    for ch in ['\\','`','*','_','{','}','[',']','(',')','>','#','+','-','.','!','$','\'']:
        if ch in text:
            text = text.replace(ch,"\\"+ch)

def ba_without_check(text):
    chars = "\\`*_{}[]()>#+-.!$"
    for c in chars:
        text = text.replace(c, "\\" + c)

Times in µs per loop on Python 2.7.14 and 3.6.3, and on a different machine from the earlier set, so cannot be compared directly.

?-------------------------------------------------------------?
¦ Py, input  ¦  ab  ¦ ab_with_check ¦  ba  ¦ ba_without_check ¦
¦------------+------+---------------+------+------------------¦
¦ Py2, short ¦ 8.81 ¦    4.22       ¦ 3.45 ¦    8.01          ¦
¦ Py3, short ¦ 5.54 ¦    1.34       ¦ 1.46 ¦    5.34          ¦
+------------+------+---------------+------+------------------¦
¦ Py2, long  ¦ 9.3  ¦    7.15       ¦ 6.85 ¦    8.55          ¦
¦ Py3, long  ¦ 7.43 ¦    4.38       ¦ 4.41 ¦    7.02          ¦
+-------------------------------------------------------------+

We can conclude that:

  • Those with the check are up to 4x faster than those without the check

  • ab_with_check is slightly in the lead on Python 3, but ba (with check) has a greater lead on Python 2

  • However, the biggest lesson here is Python 3 is up to 3x faster than Python 2! There's not a huge difference between the slowest on Python 3 and fastest on Python 2!

How should I log while using multiprocessing in Python?

I have a solution that's similar to ironhacker's except that I use logging.exception in some of my code and found that I needed to format the exception before passing it back over the Queue since tracebacks aren't pickle'able:

class QueueHandler(logging.Handler):
    def __init__(self, queue):
        logging.Handler.__init__(self)
        self.queue = queue
    def emit(self, record):
        if record.exc_info:
            # can't pass exc_info across processes so just format now
            record.exc_text = self.formatException(record.exc_info)
            record.exc_info = None
        self.queue.put(record)
    def formatException(self, ei):
        sio = cStringIO.StringIO()
        traceback.print_exception(ei[0], ei[1], ei[2], None, sio)
        s = sio.getvalue()
        sio.close()
        if s[-1] == "\n":
            s = s[:-1]
        return s

IIS7 URL Redirection from root to sub directory

I think, this could be done without IIS URL Rewrite module. <httpRedirect> supports wildcards, so you can configure it this way:

  <system.webServer>
    <httpRedirect enabled="true">
      <add wildcard="/" destination="/menu_1/MainScreen.aspx" />
    </httpRedirect>
  </system.webServer>

Note that you need to have the "HTTP Redirection" feature enabled on IIS - see HTTP Redirects

JSON.stringify output to div in pretty print way

Please use a <pre> tag

demo : http://jsfiddle.net/K83cK/

_x000D_
_x000D_
var data = {_x000D_
  "data": {_x000D_
    "x": "1",_x000D_
    "y": "1",_x000D_
    "url": "http://url.com"_x000D_
  },_x000D_
  "event": "start",_x000D_
  "show": 1,_x000D_
  "id": 50_x000D_
}_x000D_
_x000D_
_x000D_
document.getElementById("json").textContent = JSON.stringify(data, undefined, 2);
_x000D_
<pre id="json"></pre>
_x000D_
_x000D_
_x000D_

PHP mysql insert date format

As stated in Date and Time Literals:

MySQL recognizes DATE values in these formats:

  • As a string in either 'YYYY-MM-DD' or 'YY-MM-DD' format. A “relaxed” syntax is permitted: Any punctuation character may be used as the delimiter between date parts. For example, '2012-12-31', '2012/12/31', '2012^12^31', and '2012@12@31' are equivalent.

  • As a string with no delimiters in either 'YYYYMMDD' or 'YYMMDD' format, provided that the string makes sense as a date. For example, '20070523' and '070523' are interpreted as '2007-05-23', but '071332' is illegal (it has nonsensical month and day parts) and becomes '0000-00-00'.

  • As a number in either YYYYMMDD or YYMMDD format, provided that the number makes sense as a date. For example, 19830905 and 830905 are interpreted as '1983-09-05'.

Therefore, the string '08/25/2012' is not a valid MySQL date literal. You have four options (in some vague order of preference, without any further information of your requirements):

  1. Configure Datepicker to provide dates in a supported format using an altField together with its altFormat option:

    <input type="hidden" id="actualDate" name="actualDate"/>
    
    $( "selector" ).datepicker({
        altField : "#actualDate"
        altFormat: "yyyy-mm-dd"
    });
    

    Or, if you're happy for users to see the date in YYYY-MM-DD format, simply set the dateFormat option instead:

    $( "selector" ).datepicker({
        dateFormat: "yyyy-mm-dd"
    });
    
  2. Use MySQL's STR_TO_DATE() function to convert the string:

    INSERT INTO user_date VALUES ('', '$name', STR_TO_DATE('$date', '%m/%d/%Y'))
    
  3. Convert the string received from jQuery into something that PHP understands as a date, such as a DateTime object:

    $dt = \DateTime::createFromFormat('m/d/Y', $_POST['date']);
    

    and then either:

    • obtain a suitable formatted string:

      $date = $dt->format('Y-m-d');
      
    • obtain the UNIX timestamp:

      $timestamp = $dt->getTimestamp();
      

      which is then passed directly to MySQL's FROM_UNIXTIME() function:

      INSERT INTO user_date VALUES ('', '$name', FROM_UNIXTIME($timestamp))
      
  4. Manually manipulate the string into a valid literal:

    $parts = explode('/', $_POST['date']);
    $date  = "$parts[2]-$parts[0]-$parts[1]";
    

Warning

  1. Your code is vulnerable to SQL injection. You really should be using prepared statements, into which you pass your variables as parameters that do not get evaluated for SQL. If you don't know what I'm talking about, or how to fix it, read the story of Bobby Tables.

  2. Also, as stated in the introduction to the PHP manual chapter on the mysql_* functions:

    This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.

  3. You appear to be using either a DATETIME or TIMESTAMP column for holding a date value; I recommend you consider using MySQL's DATE type instead. As explained in The DATE, DATETIME, and TIMESTAMP Types:

    The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.

    The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59'.

    The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.

File tree view in Notepad++

If you want treeview like explorer, you can go with LightExplorer

Light Explorer in Notepad++

Download dll from here and paste it inside plugins folder in notepad++ installed directory. Restart notepad++ and then in menubar goto Plugins ->Light Explorer -> Light Explorer

How to limit the maximum files chosen when using multiple file input

if you want php you can count the array and just make an if statement like

if((int)count($_FILES['i_dont_know_whats_coming_next'] > 2)
      echo "error message";

eloquent laravel: How to get a row count from a ->get()

Its better to access the count with the laravels count method

$count = Model::where('status','=','1')->count();

or

$count = Model::count();

C++ cast to derived class

First of all - prerequisite for downcast is that object you are casting is of the type you are casting to. Casting with dynamic_cast will check this condition in runtime (provided that casted object has some virtual functions) and throw bad_cast or return NULL pointer on failure. Compile-time casts will not check anything and will just lead tu undefined behaviour if this prerequisite does not hold.
Now analyzing your code:

DerivedType m_derivedType = m_baseType;

Here there is no casting. You are creating a new object of type DerivedType and try to initialize it with value of m_baseType variable.

Next line is not much better:

DerivedType m_derivedType = (DerivedType)m_baseType;

Here you are creating a temporary of DerivedType type initialized with m_baseType value.

The last line

DerivedType * m_derivedType = (DerivedType*) & m_baseType;

should compile provided that BaseType is a direct or indirect public base class of DerivedType. It has two flaws anyway:

  1. You use deprecated C-style cast. The proper way for such casts is
    static_cast<DerivedType *>(&m_baseType)
  2. The actual type of casted object is not of DerivedType (as it was defined as BaseType m_baseType; so any use of m_derivedType pointer will result in undefined behaviour.

How to POST a FORM from HTML to ASPX page

You sure can.

The easiest way to see how you might do this is to browse to the aspx page you want to post to. Then save the source of that page as HTML. Change the action of the form on your new html page to point back to the aspx page you originally copied it from.

Add value tags to your form fields and put the data you want in there, then open the page and hit the submit button.

bundle install returns "Could not locate Gemfile"

You may also indicate the path to the gemfile in the same command e.g.

BUNDLE_GEMFILE="MyProject/Gemfile.ios" bundle install

jQuery set checkbox checked

$("#divParentClip").find("#subclip_checkbox")[0].checked=true;

Find will return array , so use [0] to get even if there is only one item

if you don't use find then

$("#subclip_checkbox").checked=true;

this worked fine in Mozilla Firefox for me

How to get the name of the current method from code

Call System.Reflection.MethodBase.GetCurrentMethod().Name from within the method.

What are the advantages of NumPy over regular Python lists?

NumPy's arrays are more compact than Python lists -- a list of lists as you describe, in Python, would take at least 20 MB or so, while a NumPy 3D array with single-precision floats in the cells would fit in 4 MB. Access in reading and writing items is also faster with NumPy.

Maybe you don't care that much for just a million cells, but you definitely would for a billion cells -- neither approach would fit in a 32-bit architecture, but with 64-bit builds NumPy would get away with 4 GB or so, Python alone would need at least about 12 GB (lots of pointers which double in size) -- a much costlier piece of hardware!

The difference is mostly due to "indirectness" -- a Python list is an array of pointers to Python objects, at least 4 bytes per pointer plus 16 bytes for even the smallest Python object (4 for type pointer, 4 for reference count, 4 for value -- and the memory allocators rounds up to 16). A NumPy array is an array of uniform values -- single-precision numbers takes 4 bytes each, double-precision ones, 8 bytes. Less flexible, but you pay substantially for the flexibility of standard Python lists!

PhpMyAdmin "Wrong permissions on configuration file, should not be world writable!"

you should change the owner of the server by chown command

from home you can run this command

sudo chown {userName} -R ../../opt

If it does not work yet, run this command

sudo chmod 777 -R ../../opt

It should work now.

Angular.js: set element height on page load

To avoid check on every digest cycle, we can change the height of the div when the window height gets changed.

http://jsfiddle.net/zbjLh/709/

<div ng-app="miniapp" resize>
  Testing
</div>

.

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

app.directive('resize', function ($window) {
    return function (scope, element) {
        var w = angular.element($window);
        var changeHeight = function() {element.css('height', (w.height() -20) + 'px' );};  
            w.bind('resize', function () {        
              changeHeight();   // when window size gets changed             
        });  
        changeHeight(); // when page loads          
    }
})

Convert string to Time

This gives you the needed results:

string time = "16:23:01";
var result = Convert.ToDateTime(time);
string test = result.ToString("hh:mm:ss tt", CultureInfo.CurrentCulture);
//This gives you "04:23:01 PM"  string

You could also use CultureInfo.CreateSpecificCulture("en-US") as not all cultures will display AM/PM.

Create aar file in Android Studio

just like user hcpl said but if you want to not worry about the version of the library you can do this:

dependencies {
    compile(name:'mylibrary', ext:'aar')
}

as its kind of annoying to have to update the version everytime. Also it makes the not worrying about the name space easier this way.

Execute an action when an item on the combobox is selected

The simple solution would be to use a ItemListener. When the state changes, you would simply check the currently selected item and set the text accordingly

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestComboBox06 {

    public static void main(String[] args) {
        new TestComboBox06();
    }

    public TestComboBox06() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    public class TestPane extends JPanel {

        private JComboBox cb;
        private JTextField field;

        public TestPane() {
            cb = new JComboBox(new String[]{"Item 1", "Item 2"});
            field = new JTextField(12);

            add(cb);
            add(field);

            cb.setSelectedItem(null);

            cb.addItemListener(new ItemListener() {
                @Override
                public void itemStateChanged(ItemEvent e) {
                    Object item = cb.getSelectedItem();
                    if ("Item 1".equals(item)) {
                        field.setText("20");
                    } else if ("Item 2".equals(item)) {
                        field.setText("30");
                    }
                }
            });
        }

    }

}

A better solution would be to create a custom object that represents the value to be displayed and the value associated with it...

Updated

Now I no longer have a 10 month chewing on my ankles, I updated the example to use a ListCellRenderer which is a more correct approach then been lazy and overriding toString

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestComboBox06 {

    public static void main(String[] args) {
        new TestComboBox06();
    }

    public TestComboBox06() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    public class TestPane extends JPanel {

        private JComboBox cb;
        private JTextField field;

        public TestPane() {
            cb = new JComboBox(new Item[]{
                new Item("Item 1", "20"), 
                new Item("Item 2", "30")});
            cb.setRenderer(new ItemCelLRenderer());
            field = new JTextField(12);

            add(cb);
            add(field);

            cb.setSelectedItem(null);

            cb.addItemListener(new ItemListener() {
                @Override
                public void itemStateChanged(ItemEvent e) {
                    Item item = (Item)cb.getSelectedItem();
                    field.setText(item.getValue());
                }
            });
        }

    }

    public class Item {
        private String value;
        private String text;

        public Item(String text, String value) {
            this.text = text;
            this.value = value;
        }

        public String getText() {
            return text;
        }

        public String getValue() {
            return value;
        }

    }

    public class ItemCelLRenderer extends DefaultListCellRenderer {

        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); //To change body of generated methods, choose Tools | Templates.
            if (value instanceof Item) {
                setText(((Item)value).getText());
            }
            return this;
        }

    }

}

Shell command to sum integers, one per line?

C (not simplified)

seq 1 10 | tcc -run <(cat << EOF
#include <stdio.h>
int main(int argc, char** argv) {
    int sum = 0;
    int i = 0;
    while(scanf("%d", &i) == 1) {
        sum = sum + i;
    }
    printf("%d\n", sum);
    return 0;
}
EOF)

pandas read_csv index_col=None not working with delimiters at the end of each line

Re: craigts's response, for anyone having trouble with using either False or None parameters for index_col, such as in cases where you're trying to get rid of a range index, you can instead use an integer to specify the column you want to use as the index. For example:

df = pd.read_csv('file.csv', index_col=0)

The above will set the first column as the index (and not add a range index in my "common case").

Update

Given the popularity of this answer, I thought i'd add some context/ a demo:

# Setting up the dummy data
In [1]: df = pd.DataFrame({"A":[1, 2, 3], "B":[4, 5, 6]})

In [2]: df
Out[2]:
   A  B
0  1  4
1  2  5
2  3  6

In [3]: df.to_csv('file.csv', index=None)
File[3]:
A  B
1  4
2  5
3  6

Reading without index_col or with None/False will all result in a range index:

In [4]: pd.read_csv('file.csv')
Out[4]:
   A  B
0  1  4
1  2  5
2  3  6

# Note that this is the default behavior, so the same as In [4]
In [5]: pd.read_csv('file.csv', index_col=None)
Out[5]:
   A  B
0  1  4
1  2  5
2  3  6

In [6]: pd.read_csv('file.csv', index_col=False)
Out[6]:
   A  B
0  1  4
1  2  5
2  3  6

However, if we specify that "A" (the 0th column) is actually the index, we can avoid the range index:

In [7]: pd.read_csv('file.csv', index_col=0)
Out[7]:
   B
A
1  4
2  5
3  6

How to remove carriage return and newline from a variable in shell script

yet another solution uses tr:

echo $testVar | tr -d '\r'
cat myscript | tr -d '\r'

the option -d stands for delete.

Check if an excel cell exists on another worksheet in a column - and return the contents of a different column

You can use following formulas.

For Excel 2007 or later:

=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")

For Excel 2003:

=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))

Note, that

  • I'm using List!A:C in VLOOKUP and returns value from column ? 3
  • I'm using 4th argument for VLOOKUP equals to FALSE, in that case VLOOKUP will only find an exact match, and the values in the first column of List!A:C do not need to be sorted (opposite to case when you're using TRUE).

GIT vs. Perforce- Two VCS will enter... one will leave

The command that sold me on git personally was bisect. I don't think that this feature is available in any other version control system as of now.

That being said, if people are used to a GUI client for source control they are not going to be impressed with git. Right now the only full-featured client is command-line.

How do you set a default value for a MySQL Datetime column?

IMPORTANT EDIT: It is now possible to achieve this with DATETIME fields since MySQL 5.6.5, take a look at the other post below...

Previous versions can't do that with DATETIME...

But you can do it with TIMESTAMP:

mysql> create table test (str varchar(32), ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
Query OK, 0 rows affected (0.00 sec)

mysql> desc test;
+-------+-------------+------+-----+-------------------+-------+
| Field | Type        | Null | Key | Default           | Extra |
+-------+-------------+------+-----+-------------------+-------+
| str   | varchar(32) | YES  |     | NULL              |       | 
| ts    | timestamp   | NO   |     | CURRENT_TIMESTAMP |       | 
+-------+-------------+------+-----+-------------------+-------+
2 rows in set (0.00 sec)

mysql> insert into test (str) values ("demo");
Query OK, 1 row affected (0.00 sec)

mysql> select * from test;
+------+---------------------+
| str  | ts                  |
+------+---------------------+
| demo | 2008-10-03 22:59:52 | 
+------+---------------------+
1 row in set (0.00 sec)

mysql>

CAVEAT: IF you define a column with CURRENT_TIMESTAMP ON as default, you will need to ALWAYS specify a value for this column or the value will automatically reset itself to "now()" on update. This means that if you do not want the value to change, your UPDATE statement must contain "[your column name] = [your column name]" (or some other value) or the value will become "now()". Weird, but true. I hope this helps. I am using 5.5.56-MariaDB

How can I turn a List of Lists into a List in Java 8?

The flatMap method on Stream can certainly flatten those lists for you, but it must create Stream objects for element, then a Stream for the result.

You don't need all those Stream objects. Here is the simple, concise code to perform the task.

// listOfLists is a List<List<Object>>.
List<Object> result = new ArrayList<>();
listOfLists.forEach(result::addAll);

Because a List is Iterable, this code calls the forEach method (Java 8 feature), which is inherited from Iterable.

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. Actions are performed in the order of iteration, if that order is specified.

And a List's Iterator returns items in sequential order.

For the Consumer, this code passes in a method reference (Java 8 feature) to the pre-Java 8 method List.addAll to add the inner list elements sequentially.

Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator (optional operation).

Android - Share on Facebook, Twitter, Mail, ecc

The ACTION_SEND will only give you options for sending using GMail, YahooMail... etc(Any application installed on your phone, that can perform ACTION_SEND). If you want to share on Facebook or Twitter you will need to place custom buttons for each and use their own SDK such as Facebook SDK or Twitter4J .

Creating a SOAP call using PHP with an XML body

First off, you have to specify you wish to use Document Literal style:

$client = new SoapClient(NULL, array(
    'location' => 'https://example.com/path/to/service',
    'uri' => 'http://example.com/wsdl',
    'trace' => 1,
    'use' => SOAP_LITERAL)
);

Then, you need to transform your data into a SoapVar; I've written a simple transform function:

function soapify(array $data)
{
        foreach ($data as &$value) {
                if (is_array($value)) {
                        $value = soapify($value);
                }
        }

        return new SoapVar($data, SOAP_ENC_OBJECT);
}

Then, you apply this transform function onto your data:

$data = soapify(array(
    'Acquirer' => array(
        'Id' => 'MyId',
        'UserId' => 'MyUserId',
        'Password' => 'MyPassword',
    ),
));

Finally, you call the service passing the Data parameter:

$method = 'Echo';

$result = $client->$method(new SoapParam($data, 'Data'));

Why Maven uses JDK 1.6 but my java -version is 1.7

I am late to this question, but I think the best way to handle JDK versions on MacOS is by using the script described at: http://www.jayway.com/2014/01/15/how-to-switch-jdk-version-on-mac-os-x-maverick/

Fatal error: [] operator not supported for strings

Solved!

$a['index'] = [];
$a['index'][] = 'another value';
$a['index'][] = 'another value';
$a['index'][] = 'another value';
$a['index'][] = 'another value';

Bootstrap: How to center align content inside column?

Want to center an image? Very easy, Bootstrap comes with two classes, .center-block and text-center.

Use the former in the case of your image being a BLOCK element, for example, adding img-responsive class to your img makes the img a block element. You should know this if you know how to navigate in the web console and see applied styles to an element.

Don't want to use a class? No problem, here is the CSS bootstrap uses. You can make a custom class or write a CSS rule for the element to match the Bootstrap class.

 // In case you're dealing with a block element apply this to the element itself 
.center-block {
   margin-left:auto;
   margin-right:auto;
   display:block;
}

// In case you're dealing with a inline element apply this to the parent 
.text-center {
   text-align:center
}

How can I get all sequences in an Oracle database?

You may not have permission to dba_sequences. So you can always just do:

select * from user_sequences;

How to compare two NSDates: Which is more recent?

You can compare two date by this method also

        switch ([currenttimestr  compare:endtimestr])
        {
            case NSOrderedAscending:

                // dateOne is earlier in time than dateTwo
                break;

            case NSOrderedSame:

                // The dates are the same
                break;
            case NSOrderedDescending:

                // dateOne is later in time than dateTwo


                break;

        }

Starting the week on Monday with isoWeekday()

For those who want isoWeek to be the default you can modify moment's behaviour as such:

const moment = require('moment');
const proto = Object.getPrototypeOf(moment());

const {startOf, endOf} = proto;
proto.startOf = function(period) {
  if (period === 'week') {
    period = 'isoWeek';
  }
  return startOf.call(this, period);
};
proto.endOf = function(period) {
  if (period === 'week') {
    period = 'isoWeek';
  }
  return endOf.call(this, period);
};

Now you can simply use someDate.startOf('week') without worrying you'll get sunday or having to think about whether to use isoweek or isoWeek etc.

Plus you can store this in a variable like const period = 'week' and use it safely in subtract() or add() operations, e.g. moment().subtract(1, period).startOf(period);. This won't work with period being isoWeek.

Event detect when css property changed using Jquery

For properties for which css transition will affect, can use transitionend event, example for z-index:

_x000D_
_x000D_
$(".observed-element").on("webkitTransitionEnd transitionend", function(e) {_x000D_
  console.log("end", e);_x000D_
  alert("z-index changed");_x000D_
});_x000D_
_x000D_
$(".changeButton").on("click", function() {_x000D_
  console.log("click");_x000D_
  document.querySelector(".observed-element").style.zIndex = (Math.random() * 1000) | 0;_x000D_
});
_x000D_
.observed-element {_x000D_
  transition: z-index 1ms;_x000D_
  -webkit-transition: z-index 1ms;_x000D_
}_x000D_
div {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  border: 1px solid;_x000D_
  position: absolute;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button class="changeButton">change z-index</button>_x000D_
<div class="observed-element"></div>
_x000D_
_x000D_
_x000D_

CSS opacity only to background color, not the text on it?

I had the same problem. I want a 100% transparent background color. Just use this code; it's worked great for me:

rgba(54, 25, 25, .00004);

You can see examples on the left side on this web page (the contact form area).

"Content is not allowed in prolog" when parsing perfectly valid XML on GAE

In my xml file, the header looked like this:

<?xml version="1.0" encoding="utf-16"? />

In a test file, I was reading the file bytes and decoding the data as UTF-8 (not realizing the header in this file was utf-16) to create a string.

byte[] data = Files.readAllBytes(Paths.get(path));
String dataString = new String(data, "UTF-8");

When I tried to deserialize this string into an object, I was seeing the same error:

javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,1]
Message: Content is not allowed in prolog.

When I updated the second line to

String dataString = new String(data, "UTF-16");

I was able to deserialize the object just fine. So as Romain had noted above, the encodings need to match.

How to set JAVA_HOME environment variable on Mac OS X 10.9?

I did it by putting

export JAVA_HOME=`/usr/libexec/java_home`

(backtics) in my .bashrc. See my comment on Adrian's answer.

Zipping a file in bash fails

Run dos2unix or similar utility on it to remove the carriage returns (^M).

This message indicates that your file has dos-style lineendings:

-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory 

Utilities like dos2unix will fix it:

 dos2unix <backup.bash >improved-backup.sh 

Or, if no such utility is installed, you can accomplish the same thing with translate:

tr -d "\015\032" <backup.bash >improved-backup.sh 

As for how those characters got there in the first place, @MadPhysicist had some good comments.

jQuery getJSON save result into variable

You can't get value when calling getJSON, only after response.

var myjson;
$.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
    myjson = json;
});

Missing include "bits/c++config.h" when cross compiling 64 bit program on 32 bit in Ubuntu

Adding this answer partially because it fixed my problem of the same issue and so I can bookmark this question myself.

I was able to fix it by doing the following:

sudo apt-get install gcc-multilib g++-multilib

If you've installed a version of gcc / g++ that doesn't ship by default (such as g++-4.8 on lucid) you'll want to match the version as well:

sudo apt-get install gcc-4.8-multilib g++-4.8-multilib

How to Join to first row

CROSS APPLY to the rescue:

SELECT Orders.OrderNumber, topline.Quantity, topline.Description
FROM Orders
cross apply
(
    select top 1 Description,Quantity
    from LineItems 
    where Orders.OrderID = LineItems.OrderID
)topline

You can also add the order by of your choice.

Center an item with position: relative

Alternatively, you may also use the CSS3 Flexible Box Model. It's a great way to create flexible layouts that can also be applied to center content like so:

#parent {
    -webkit-box-align:center;
    -webkit-box-pack:center;
    display:-webkit-box;
}

Python xticks in subplots

See the (quite) recent answer on the matplotlib repository, in which the following solution is suggested:

  • If you want to set the xticklabels:

    ax.set_xticks([1,4,5]) 
    ax.set_xticklabels([1,4,5], fontsize=12)
    
  • If you want to only increase the fontsize of the xticklabels, using the default values and locations (which is something I personally often need and find very handy):

    ax.tick_params(axis="x", labelsize=12) 
    
  • To do it all at once:

    plt.setp(ax.get_xticklabels(), fontsize=12, fontweight="bold", 
             horizontalalignment="left")`
    

Append date to filename in linux

You can use backticks.

$ echo myfilename-"`date +"%d-%m-%Y"`"

Yields:

myfilename-25-11-2009

React JS - Uncaught TypeError: this.props.data.map is not a function

It happens because the component is rendered before the async data arrived, you should control before to render.

I resolved it in this way:

render() {
    let partners = this.props && this.props.partners.length > 0 ?
        this.props.partners.map(p=>
            <li className = "partners" key={p.id}>
                <img src={p.img} alt={p.name}/> {p.name} </li>
        ) : <span></span>;

    return (
        <div>
            <ul>{partners}</ul>
        </div>
    );
}
  • Map can not resolve when the property is null/undefined, so I did a control first

this.props && this.props.partners.length > 0 ?

How can I display a tooltip on an HTML "option" tag?

Why use a dropdown at all? The only way the user will see your explanatory text is by blindly hovering over one of the options.

I think it would be preferable to use a radio button group, and next to each item, put a tooltip icon indicating additional information, as well as displaying it after selection (like you currently have it).

I realize this doesn't exactly solve your problem, but I don't see the point in struggling with an html element that's notorious for its inflexibility when you could just use one that's better suited in the first place.

How to get database structure in MySQL via query

SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='bodb' AND TABLE_NAME='abc';

works for getting all column names

Check if string doesn't contain another string

Or alternatively, you could use this:

WHERE CHARINDEX(N'Apples', someColumn) = 0

Not sure which one performs better - you gotta test it! :-)

Marc

UPDATE: the performance seems to be pretty much on a par with the other solution (WHERE someColumn NOT LIKE '%Apples%') - so it's really just a question of your personal preference.

How to measure height, width and distance of object using camera?

If you know the viewport angle of the camera, you can use the height in pixels to determine the angle from the top to bottom of the object. Then, using the distance and arctangent calculate the height:

height = arctan(angle) * distance

To find the viewport angle, point the camera at something which is of known height, and make it exactly fill the screen. For example, point it at a ruler, and make it just far enough away that you can only barely see the ends of the ruler. Measure the distance from the camera, and then your total viewport angle is

viewportAngle = tan(ruler_length / distance)

Then, suppose your camera is 480px tall (cheap webcam), and the view angle is 20°. If you have an object onscreen which is 240px tall, then its angle is 10°. If you know it's 2 feet away, you would say 2 feet * arctan(10°) = ~4.1 inches tall. (I think... it's 2am so this may be a little off)

CSS Outside Border

I think you've got your understanding of the two properties off a little. Border affects the outside edge of the element, making the element different in size. Outline will not change the size or position of the element (takes up no space) and goes outside the border. From your description you want to use the border property.

Look at the simple example below in your browser:

_x000D_
_x000D_
<div style="height: 100px; width: 100px; background: black; color: white; outline: thick solid #00ff00">SOME TEXT HERE</div>_x000D_
_x000D_
<div style="height: 100px; width: 100px; background: black; color: white; border-left: thick solid #00ff00">SOME TEXT HERE</div>
_x000D_
_x000D_
_x000D_

Notice how the border pushes the bottom div over, but the outline doesn't move the top div and the outline actually overlaps the bottom div.

You can read more about it here:
Border
Outline

how to redirect to external url from c# controller

Try this:

return Redirect("http://www.website.com");

Getting activity from context in android

If you like to call an activity method from within a custom layout class(non-Activity Class).You should create a delegate using interface.

It is untested and i coded it right . but i am conveying a way to achieve what you want.

First of all create and Interface

interface TaskCompleteListener<T> {
   public void onProfileClicked(T result);
}



public class ProfileView extends LinearLayout
{
    private TaskCompleteListener<String> callback;
    TextView profileTitleTextView;
    ImageView profileScreenImageButton;
    boolean isEmpty;
    ProfileData data;
    String name;

    public ProfileView(Context context, AttributeSet attrs, String name, final ProfileData profileData)
    {
        super(context, attrs);
        ......
        ......
    }
    public setCallBack( TaskCompleteListener<String> cb) 
    {
      this.callback = cb;
    }
    //Heres where things get complicated
    public void onClick(View v)
    {
        callback.onProfileClicked("Pass your result or any type");
    }
}

And implement this to any Activity.

and call it like

ProfileView pv = new ProfileView(actvitiyContext, null, temp, tempPd);
pv.setCallBack(new TaskCompleteListener
               {
                   public void onProfileClicked(String resultStringFromProfileView){}
               });

Lua - Current time in milliseconds

Kevlar is correct.

An alternative to a custom DLL is Lua Alien

Failed to decode downloaded font

I also had same problem but i have solved by adding 'Content-Type' : 'application/x-font-ttf' in response header for all .ttf files

make arrayList.toArray() return more specific types

A shorter version of converting List to Array of specific type (for example Long):

Long[] myArray = myList.toArray(Long[]::new);

Bootstrap: Position of dropdown menu relative to navbar item

This is the effect that we're trying to achieve:

A right-aligned menu

The classes that need to be applied changed with the release of Bootstrap 3.1.0 and again with the release of Bootstrap 4. If one of the below solutions doesn't seem to be working double check the version number of Bootstrap that you're importing and try a different one.

Bootstrap 3

Before v3.1.0

You can use the pull-right class to line the right hand side of the menu up with the caret:

<li class="dropdown">
  <a class="dropdown-toggle" href="#">Link</a>
  <ul class="dropdown-menu pull-right">
     <li>...</li>
  </ul>
</li>

Fiddle: http://jsfiddle.net/joeczucha/ewzafdju/

After v3.1.0

As of v3.1.0, we've deprecated .pull-right on dropdown menus. To right-align a menu, use .dropdown-menu-right. Right-aligned nav components in the navbar use a mixin version of this class to automatically align the menu. To override it, use .dropdown-menu-left.

You can use the dropdown-right class to line the right hand side of the menu up with the caret:

<li class="dropdown">
  <a class="dropdown-toggle" href="#">Link</a>
  <ul class="dropdown-menu dropdown-menu-right">
     <li>...</li>
  </ul>
</li>

Fiddle: http://jsfiddle.net/joeczucha/1nrLafxc/

Bootstrap 4

The class for Bootstrap 4 are the same as Bootstrap > 3.1.0, just watch out as the rest of the surrounding markup has changed a little:

<li class="nav-item dropdown">
  <a class="nav-link dropdown-toggle" href="#">
    Link
  </a>
  <div class="dropdown-menu dropdown-menu-right">
    <a class="dropdown-item" href="#">...</a>
  </div>
</li>

Fiddle: https://jsfiddle.net/joeczucha/f8h2tLoc/

Passing Parameters JavaFX FXML

Yes you can.
You need to add in the first controller:

YourController controller = loader.getController();     
controller.setclient(client);

Then in the second one declare a client, then at the bottom of your controller:

public void setclien(Client c) {
    this.client = c;
}

Cause of No suitable driver found for

If you look at your original connection string:

<property name="url" value="jdbc:hsqldb:hsql://localhost"/>

The Hypersonic docs suggest that you're missing an alias after localhost:

http://hsqldb.org/doc/guide/ch04.html

How to make IPython notebook matplotlib plot inline

I had the same problem when I was running the plotting commands in separate cells in Jupyter:

In [1]:  %matplotlib inline
         import matplotlib
         import matplotlib.pyplot as plt
         import numpy as np
In [2]:  x = np.array([1, 3, 4])
         y = np.array([1, 5, 3])
In [3]:  fig = plt.figure()
         <Figure size 432x288 with 0 Axes>                      #this might be the problem
In [4]:  ax = fig.add_subplot(1, 1, 1)
In [5]:  ax.scatter(x, y)
Out[5]:  <matplotlib.collections.PathCollection at 0x12341234>  # CAN'T SEE ANY PLOT :(
In [6]:  plt.show()                                             # STILL CAN'T SEE IT :(

The problem was solved by merging the plotting commands into a single cell:

In [1]:  %matplotlib inline
         import matplotlib
         import matplotlib.pyplot as plt
         import numpy as np
In [2]:  x = np.array([1, 3, 4])
         y = np.array([1, 5, 3])
In [3]:  fig = plt.figure()
         ax = fig.add_subplot(1, 1, 1)
         ax.scatter(x, y)
Out[3]:  <matplotlib.collections.PathCollection at 0x12341234>
         # AND HERE APPEARS THE PLOT AS DESIRED :)

Generate random numbers following a normal distribution in C/C++

If you're using C++11, you can use std::normal_distribution:

#include <random>

std::default_random_engine generator;
std::normal_distribution<double> distribution(/*mean=*/0.0, /*stddev=*/1.0);

double randomNumber = distribution(generator);

There are many other distributions you can use to transform the output of the random number engine.

Re-run Spring Boot Configuration Annotation Processor to update generated metadata

For me, other answers didn't work. I had to go to open Files and do Invalidate caches and restart on Intellij. After that, everything worked fine again.

Total Number of Row Resultset getRow Method

The best way to get number of rows from resultset is using count function query for database access and then rs.getInt(1) method to get number of rows. from my code look it:

    String query = "SELECT COUNT() FROM table";
ResultSet rs = new DatabaseConnection().selectData(query);
rs.getInt(1);

this will return int value number of rows fetched from database. Here DatabaseConnection().selectData() is my code for accessing database. I was also stuck here but then solved...

annotation to make a private method public only for test classes

An article on Testing Private Methods lays out some approaches to testing private code. using reflection puts extra burden on the programmer to remember if refactoring is done, the strings aren't automatically changed, but I think it's the cleanest approach.

An internal error occurred during: "Updating Maven Project". java.lang.NullPointerException

Above solutions did not work for me as the issue with open JDK 13 version https://github.com/spotify/dockerfile-maven/issues/163 So I degraded to open JDK8 and it works for me

Close virtual keyboard on button press

You use this code in your button click event

// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {  
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

Why does visual studio 2012 not find my tests?

Visual Studio 2015 (v.14.....) - same problem here

Cause: Different versions of NUnit and NUnit Test Adapter In my case I had the latest versions of both NUnit (3.5) and NUnit Test Adapter but the Test Adapter was not the right one. For NUnit 3 and higher there is a NUnit3TestAdapter that must be used

Solution: Uninstalled the "faulty" NUnint Test Adapter and installed the UNit3TestAdapter v.3.5.0 (the latest now is 3.6.0 but didn't use it in order to keep it same as NUnit)

After Rebuild of the Solution Tests poped up :)

Using CSS to align a button bottom of the screen using relative positions

<button style="position: absolute; left: 20%; right: 20%; bottom: 5%;"> Button </button>

Opencv - Grayscale mode Vs gray color conversion

Note: This is not a duplicate, because the OP is aware that the image from cv2.imread is in BGR format (unlike the suggested duplicate question that assumed it was RGB hence the provided answers only address that issue)

To illustrate, I've opened up this same color JPEG image:

enter image description here

once using the conversion

img = cv2.imread(path)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

and another by loading it in gray scale mode

img_gray_mode = cv2.imread(path, cv2.IMREAD_GRAYSCALE)

Like you've documented, the diff between the two images is not perfectly 0, I can see diff pixels in towards the left and the bottom

enter image description here

I've summed up the diff too to see

import numpy as np
np.sum(diff)
# I got 6143, on a 494 x 750 image

I tried all cv2.imread() modes

Among all the IMREAD_ modes for cv2.imread(), only IMREAD_COLOR and IMREAD_ANYCOLOR can be converted using COLOR_BGR2GRAY, and both of them gave me the same diff against the image opened in IMREAD_GRAYSCALE

The difference doesn't seem that big. My guess is comes from the differences in the numeric calculations in the two methods (loading grayscale vs conversion to grayscale)

Naturally what you want to avoid is fine tuning your code on a particular version of the image just to find out it was suboptimal for images coming from a different source.

In brief, let's not mix the versions and types in the processing pipeline.

So I'd keep the image sources homogenous, e.g. if you have capturing the image from a video camera in BGR, then I'd use BGR as the source, and do the BGR to grayscale conversion cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Vice versa if my ultimate source is grayscale then I'd open the files and the video capture in gray scale cv2.imread(path, cv2.IMREAD_GRAYSCALE)

Is there a command line utility for rendering GitHub flavored Markdown?

pandoc with browser works well for me.

Usage: cat README.md | pandoc -f markdown_github | browser

Installation (Assuming you are using Mac OSX):

  • $ brew install pandoc

  • $ brew install browser

Or on Debian/Ubuntu: apt-get install pandoc browser

Subtract two variables in Bash

Use Python:

#!/bin/bash
# home/victoria/test.sh

START=$(date +"%s")                                     ## seconds since Epoch
for i in $(seq 1 10)
do
  sleep 1.5
  END=$(date +"%s")                                     ## integer
  TIME=$((END - START))                                 ## integer
  AVG_TIME=$(python -c "print(float($TIME/$i))")        ## int to float
  printf 'i: %i | elapsed time: %0.1f sec | avg. time: %0.3f\n' $i $TIME $AVG_TIME
  ((i++))                                               ## increment $i
done

Output

$ ./test.sh 
i: 1 | elapsed time: 1.0 sec | avg. time: 1.000
i: 2 | elapsed time: 3.0 sec | avg. time: 1.500
i: 3 | elapsed time: 5.0 sec | avg. time: 1.667
i: 4 | elapsed time: 6.0 sec | avg. time: 1.500
i: 5 | elapsed time: 8.0 sec | avg. time: 1.600
i: 6 | elapsed time: 9.0 sec | avg. time: 1.500
i: 7 | elapsed time: 11.0 sec | avg. time: 1.571
i: 8 | elapsed time: 12.0 sec | avg. time: 1.500
i: 9 | elapsed time: 14.0 sec | avg. time: 1.556
i: 10 | elapsed time: 15.0 sec | avg. time: 1.500
$

How npm start runs a server on port 8000

You can change the port in the console by running the following on Windows:

SET PORT=8000

For Mac, Linux or Windows WSL use the following:

export PORT=8000

The export sets the environment variable for the current shell and all child processes like npm that might use it.

If you want the environment variable to be set just for the npm process, precede the command with the environment variable like this (on Mac and Linux and Windows WSL):

PORT=8000 npm run start

How to get the URL without any parameters in JavaScript?

You can use a regular expression: window.location.href.match(/^[^\#\?]+/)[0]

how to add json library

You can also install simplejson.

If you have pip (see https://pypi.python.org/pypi/pip) as your Python package manager you can install simplejson with:

 pip install simplejson

This is similar to the comment of installing with easy_install, but I prefer pip to easy_install as you can easily uninstall in pip with "pip uninstall package".

Multi-select dropdown list in ASP.NET

Here's a cool ASP.NET Web control called Multi-Select List Field at http://www.xnodesystems.com/. It's capable of:

(1) Multi-select; (2) Auto-complete; (3) Validation.

Angular2 Error: There is no directive with "exportAs" set to "ngForm"

I faced the same issue. I had missed the forms module import tag in the app.module.ts

import { FormsModule } from '@angular/forms';

@NgModule({
    imports: [BrowserModule,
        FormsModule
    ],

How to check if any Checkbox is checked in Angular

You can do something like:

function ChckbxsCtrl($scope, $filter) {
    $scope.chkbxs = [{
        label: "Led Zeppelin",
        val: false
    }, {
        label: "Electric Light Orchestra",
        val: false
    }, {
        label: "Mark Almond",
        val: false
    }];

    $scope.$watch("chkbxs", function(n, o) {
        var trues = $filter("filter")(n, {
            val: true
        });
        $scope.flag = trues.length;
    }, true);
}

And a template:

<div ng-controller="ChckbxsCtrl">
    <div ng-repeat="chk in chkbxs">
        <input type="checkbox" ng-model="chk.val" />
        <label>{{chk.label}}</label>
    </div>
    <div ng-show="flag">I'm ON when band choosed</div>
</div>

Working: http://jsfiddle.net/cherniv/JBwmA/

UPDATE: Or you can go little bit different way , without using $scope's $watch() method, like:

$scope.bandChoosed = function() {
    var trues = $filter("filter")($scope.chkbxs, {
        val: true
    });
    return trues.length;
}

And in a template do:

<div ng-show="bandChoosed()">I'm ON when band choosed</div>

Fiddle: http://jsfiddle.net/uzs4sgnp/

How can I check the size of a file in a Windows batch script?

Another example

  FOR %I in (file1.txt) do @ECHO %~zI

What is a smart pointer and when should I use one?

The existing answers are good but don't cover what to do when a smart pointer is not the (complete) answer to the problem you are trying to solve.

Among other things (explained well in other answers) using a smart pointer is a possible solution to How do we use a abstract class as a function return type? which has been marked as a duplicate of this question. However, the first question to ask if tempted to specify an abstract (or in fact, any) base class as a return type in C++ is "what do you really mean?". There is a good discussion (with further references) of idiomatic object oriented programming in C++ (and how this is different to other languages) in the documentation of the boost pointer container library. In summary, in C++ you have to think about ownership. Which smart pointers help you with, but are not the only solution, or always a complete solution (they don't give you polymorphic copy) and are not always a solution you want to expose in your interface (and a function return sounds an awful lot like an interface). It might be sufficient to return a reference, for example. But in all of these cases (smart pointer, pointer container or simply returning a reference) you have changed the return from a value to some form of reference. If you really needed copy you may need to add more boilerplate "idiom" or move beyond idiomatic (or otherwise) OOP in C++ to more generic polymorphism using libraries like Adobe Poly or Boost.TypeErasure.

Maven error "Failure to transfer..."

It happened to me as Iam behind a firewall. The dependencies doesn't get downloaded sometimes when you are running in Eclipse IDE. Make sure you use mvn clean install -U to resolve the problem. You would see the dependencies download after this.

How to convert array to SimpleXML

Here is my entry, simple and clean..

function array2xml($array, $xml = false){
    if($xml === false){
        $xml = new SimpleXMLElement('<root/>');
    }
    foreach($array as $key => $value){
        if(is_array($value)){
            array2xml($value, $xml->addChild($key));
        }else{
            $xml->addChild($key, $value);
        }
    }
    return $xml->asXML();
}


header('Content-type: text/xml');
print array2xml($array);

Recommended method for escaping HTML in Java

Nice short method:

public static String escapeHTML(String s) {
    StringBuilder out = new StringBuilder(Math.max(16, s.length()));
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (c > 127 || c == '"' || c == '\'' || c == '<' || c == '>' || c == '&') {
            out.append("&#");
            out.append((int) c);
            out.append(';');
        } else {
            out.append(c);
        }
    }
    return out.toString();
}

Based on https://stackoverflow.com/a/8838023/1199155 (the amp is missing there). The four characters checked in the if clause are the only ones below 128, according to http://www.w3.org/TR/html4/sgml/entities.html

How to echo in PHP, HTML tags

You can replace '<' with &lt; and '>' with &gt;. For example:

echo "&lt;div&gt;";

The output will be visible <div>.

For longer strings, make a function, for example

function example($input) {
    $output = str_replace('>', '&gt;', str_replace('<', '&lt;', $html));
    return $output;
}

echo example($your_html);

Don't forget to put backslashes href=\"#\" or do it with single quotes href='#' or change it in a function too with str_replace.

how to dynamically add options to an existing select in vanilla javascript

I guess something like this would do the job.

var option = document.createElement("option");
option.text = "Text";
option.value = "myvalue";
var select = document.getElementById("daySelect");
select.appendChild(option);

Javascript set img src

Your src property is an object because you are setting the src element to be the entire image you created in JavaScript.

Try

document["pic1"].src = searchPic.src;

Good Free Alternative To MS Access

Are you aware that the Access 2007 runtime can be downloaded for free?

Links for newer versions:

Replacing .NET WebBrowser control with a better browser, like Chrome?

I had the same problem, the WebBrowser was using an old version of IE, with some googling I came across the following code that makes a change into registry and makes the WebBrowser to use the lastest IE version possible:

 public enum BrowserEmulationVersion
    {
        Default = 0,
        Version7 = 7000,
        Version8 = 8000,
        Version8Standards = 8888,
        Version9 = 9000,
        Version9Standards = 9999,
        Version10 = 10000,
        Version10Standards = 10001,
        Version11 = 11000,
        Version11Edge = 11001
    }
    public static class WBEmulator
    {
        private const string InternetExplorerRootKey = @"Software\Microsoft\Internet Explorer";

        public static int GetInternetExplorerMajorVersion()
        {
            int result;

            result = 0;

            try
            {
                RegistryKey key;

                key = Registry.LocalMachine.OpenSubKey(InternetExplorerRootKey);

                if (key != null)
                {
                    object value;

                    value = key.GetValue("svcVersion", null) ?? key.GetValue("Version", null);

                    if (value != null)
                    {
                        string version;
                        int separator;

                        version = value.ToString();
                        separator = version.IndexOf('.');
                        if (separator != -1)
                        {
                            int.TryParse(version.Substring(0, separator), out result);
                        }
                    }
                }
            }
            catch (SecurityException)
            {
                // The user does not have the permissions required to read from the registry key.
            }
            catch (UnauthorizedAccessException)
            {
                // The user does not have the necessary registry rights.
            }

            return result;
        }
        private const string BrowserEmulationKey = InternetExplorerRootKey + @"\Main\FeatureControl\FEATURE_BROWSER_EMULATION";

        public static BrowserEmulationVersion GetBrowserEmulationVersion()
        {
            BrowserEmulationVersion result;

            result = BrowserEmulationVersion.Default;

            try
            {
                RegistryKey key;

                key = Registry.CurrentUser.OpenSubKey(BrowserEmulationKey, true);
                if (key != null)
                {
                    string programName;
                    object value;

                    programName = Path.GetFileName(Environment.GetCommandLineArgs()[0]);
                    value = key.GetValue(programName, null);

                    if (value != null)
                    {
                        result = (BrowserEmulationVersion)Convert.ToInt32(value);
                    }
                }
            }
            catch (SecurityException)
            {
                // The user does not have the permissions required to read from the registry key.
            }
            catch (UnauthorizedAccessException)
            {
                // The user does not have the necessary registry rights.
            }

            return result;
        }
        public static bool SetBrowserEmulationVersion(BrowserEmulationVersion browserEmulationVersion)
        {
            bool result;

            result = false;

            try
            {
                RegistryKey key;

                key = Registry.CurrentUser.OpenSubKey(BrowserEmulationKey, true);

                if (key != null)
                {
                    string programName;

                    programName = Path.GetFileName(Environment.GetCommandLineArgs()[0]);

                    if (browserEmulationVersion != BrowserEmulationVersion.Default)
                    {
                        // if it's a valid value, update or create the value
                        key.SetValue(programName, (int)browserEmulationVersion, RegistryValueKind.DWord);
                    }
                    else
                    {
                        // otherwise, remove the existing value
                        key.DeleteValue(programName, false);
                    }

                    result = true;
                }
            }
            catch (SecurityException)
            {
                // The user does not have the permissions required to read from the registry key.
            }
            catch (UnauthorizedAccessException)
            {
                // The user does not have the necessary registry rights.
            }

            return result;
        }

        public static bool SetBrowserEmulationVersion()
        {
            int ieVersion;
            BrowserEmulationVersion emulationCode;

            ieVersion = GetInternetExplorerMajorVersion();

            if (ieVersion >= 11)
            {
                emulationCode = BrowserEmulationVersion.Version11;
            }
            else
            {
                switch (ieVersion)
                {
                    case 10:
                        emulationCode = BrowserEmulationVersion.Version10;
                        break;
                    case 9:
                        emulationCode = BrowserEmulationVersion.Version9;
                        break;
                    case 8:
                        emulationCode = BrowserEmulationVersion.Version8;
                        break;
                    default:
                        emulationCode = BrowserEmulationVersion.Version7;
                        break;
                }
            }

            return SetBrowserEmulationVersion(emulationCode);
        }
        public static bool IsBrowserEmulationSet()
        {
            return GetBrowserEmulationVersion() != BrowserEmulationVersion.Default;
        }
    } 

You just need to create a class and put this code in it, then run the following code when the program starts:

 if (!WBEmulator.IsBrowserEmulationSet())
            {
                WBEmulator.SetBrowserEmulationVersion();
            }

VB.NET:

Imports Microsoft.Win32
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Imports System.Security
Imports System.Text
Imports System.Threading.Tasks

Public Enum BrowserEmulationVersion
    [Default] = 0
    Version7 = 7000
    Version8 = 8000
    Version8Standards = 8888
    Version9 = 9000
    Version9Standards = 9999
    Version10 = 10000
    Version10Standards = 10001
    Version11 = 11000
    Version11Edge = 11001
End Enum


Public Class WBEmulator
    Private Const InternetExplorerRootKey As String = "Software\Microsoft\Internet Explorer"
    Public Shared Function GetInternetExplorerMajorVersion() As Integer

        Dim result As Integer

        result = 0

        Try
            Dim key As RegistryKey
            key = Registry.LocalMachine.OpenSubKey(InternetExplorerRootKey)
            If key IsNot Nothing Then
                Dim value As Object = If(key.GetValue("svcVersion", Nothing), key.GetValue("Version", Nothing))

                Dim Version As String
                Dim separator As Integer
                Version = value.ToString()
                separator = Version.IndexOf(".")
                If separator <> -1 Then
                    Integer.TryParse(Version.Substring(0, separator), result)
                End If
            End If

        Catch ex As SecurityException
            'The user does Not have the permissions required to read from the registry key.
        Catch ex As UnauthorizedAccessException
            'The user does Not have the necessary registry rights.
        Catch

        End Try
        GetInternetExplorerMajorVersion = result
    End Function
    Private Const BrowserEmulationKey = InternetExplorerRootKey + "\Main\FeatureControl\FEATURE_BROWSER_EMULATION"

    Public Shared Function GetBrowserEmulationVersion() As BrowserEmulationVersion

        Dim result As BrowserEmulationVersion
        result = BrowserEmulationVersion.Default

        Try
            Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(BrowserEmulationKey, True)
            If key IsNot Nothing Then
                Dim programName As String
                Dim value As Object
                programName = Path.GetFileName(Environment.GetCommandLineArgs()(0))
                value = key.GetValue(programName, Nothing)
                If value IsNot Nothing Then
                    result = CType(Convert.ToInt32(value), BrowserEmulationVersion)
                End If
            End If
        Catch ex As SecurityException
            'The user does Not have the permissions required to read from the registry key.
        Catch ex As UnauthorizedAccessException
            'The user does Not have the necessary registry rights.
        Catch

        End Try

        GetBrowserEmulationVersion = result
    End Function
    Public Shared Function SetBrowserEmulationVersion(BEVersion As BrowserEmulationVersion) As Boolean

        Dim result As Boolean = False

        Try
            Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(BrowserEmulationKey, True)
            If key IsNot Nothing Then
                Dim programName As String = Path.GetFileName(Environment.GetCommandLineArgs()(0))
                If BEVersion <> BrowserEmulationVersion.Default Then
                    'if it's a valid value, update or create the value
                    key.SetValue(programName, CType(BEVersion, Integer), RegistryValueKind.DWord)
                Else
                    'otherwise, remove the existing value
                    key.DeleteValue(programName, False)
                End If
                result = True
            End If
        Catch ex As SecurityException

            ' The user does Not have the permissions required to read from the registry key.

        Catch ex As UnauthorizedAccessException

            ' The user does Not have the necessary registry rights.

        End Try

        SetBrowserEmulationVersion = result
    End Function


    Public Shared Function SetBrowserEmulationVersion() As Boolean
        Dim ieVersion As Integer
        Dim emulationCode As BrowserEmulationVersion
        ieVersion = GetInternetExplorerMajorVersion()

        If ieVersion >= 11 Then

            emulationCode = BrowserEmulationVersion.Version11
        Else

            Select Case ieVersion
                Case 10
                    emulationCode = BrowserEmulationVersion.Version10
                Case 9
                    emulationCode = BrowserEmulationVersion.Version9
                Case 8
                    emulationCode = BrowserEmulationVersion.Version8
                Case Else
                    emulationCode = BrowserEmulationVersion.Version7
            End Select
        End If

        SetBrowserEmulationVersion = SetBrowserEmulationVersion(emulationCode)
    End Function

    Public Shared Function IsBrowserEmulationSet() As Boolean
        IsBrowserEmulationSet = GetBrowserEmulationVersion() <> BrowserEmulationVersion.Default
    End Function
End Class

You may use it like:

If Not WBEmulator.IsBrowserEmulationSet() Then
    WBEmulator.SetBrowserEmulationVersion()
End If

CreateProcess: No such file or directory

I had the same problem.

I already had a g++ compiler installed thru MinGW (the package mingw32-gcc-g++) but I needed a C compiler so I ran mingw-get-setup.exe where I was able to have it install the mingw32-base package, the one with the C compiler.

Alas! I had this error when I use gcc to compile:

gcc: error: createprocess: no such file or directory

What I did was, still using the MinGW Installation Manager, I removed the C and C++ compiler packages, namely mingw32-base and mingw32-gcc-g++ and ALSO deleted the C:\MinGW directory itself. Then I reran mingw-get-setup.exe, installed mingw32-base, and voila, it worked :)

Allow only numbers to be typed in a textbox

You also can use some HTML5 attributes, some browsers might already take advantage of them (type="number" min="0").

Whatever you do, remember to re-check your inputs on the server side: you can never assume the client-side validation has been performed.

Python dictionary : TypeError: unhashable type: 'list'

The error you gave is due to the fact that in python, dictionary keys must be immutable types (if key can change, there will be problems), and list is a mutable type.

Your error says that you try to use a list as dictionary key, you'll have to change your list into tuples if you want to put them as keys in your dictionary.

According to the python doc :

The only types of values not acceptable as keys are values containing lists or dictionaries or other mutable types that are compared by value rather than by object identity, the reason being that the efficient implementation of dictionaries requires a key’s hash value to remain constant

Excel concatenation quotes

I was Forming some Programming Logic Used CHAR(34) for Quotes at Excel : A small Part of same I am posting which can be helpfull ,Hopefully

1   Customers
2   Invoices

Formula Used :

=CONCATENATE("listEvents.Add(",D4,",",CHAR(34),E4,CHAR(34),");")

Result :

listEvents.Add(1,"Customers");
listEvents.Add(2,"Invoices");

How to create an array of object literals in a loop?

If you want to go even further than @tetra with ES6 you can use the Object spread syntax and do something like this:

let john = {
    firstName: "John",
    lastName: "Doe",
};

let people = new Array(10).fill().map((e, i) => {(...john, id: i});

How to check if one DateTime is greater than the other in C#

if (StartDate>=EndDate)
{
    throw new InvalidOperationException("Ack!  StartDate is not before EndDate!");
}

php - add + 7 days to date format mm dd, YYYY

echo date('d/m/Y', strtotime('+7 days'));

How to get all table names from a database?

 public void getDatabaseMetaData()
    {
        try {

            DatabaseMetaData dbmd = conn.getMetaData();
            String[] types = {"TABLE"};
            ResultSet rs = dbmd.getTables(null, null, "%", types);
            while (rs.next()) {
                System.out.println(rs.getString("TABLE_NAME"));
            }
        } 
            catch (SQLException e) {
            e.printStackTrace();
        }
    }

How to place div side by side

There are many ways to do what you're asking for:

  1. Using CSS float property:

_x000D_
_x000D_
 <div style="width: 100%; overflow: hidden;">
     <div style="width: 600px; float: left;"> Left </div>
     <div style="margin-left: 620px;"> Right </div>
</div>
_x000D_
_x000D_
_x000D_

  1. Using CSS display property - which can be used to make divs act like a table:

_x000D_
_x000D_
<div style="width: 100%; display: table;">
    <div style="display: table-row">
        <div style="width: 600px; display: table-cell;"> Left </div>
        <div style="display: table-cell;"> Right </div>
    </div>
</div>
_x000D_
_x000D_
_x000D_

There are more methods, but those two are the most popular.

How to validate email id in angularJs using ng-pattern

This is jQuery Email Validation using Regex Expression. you can also use the same concept for AngularJS if you have idea of AngularJS.

var expression = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;

Source.

Get an object's class name at runtime

Simple answer :

class MyClass {}

const instance = new MyClass();

console.log(instance.constructor.name); // MyClass
console.log(MyClass.name);              // MyClass

However: beware that the name will likely be different when using minified code.

Div not expanding even with content inside

Putting a <br clear="all" /> after the last floated div worked the best for me. Thanks to Brent Fiare & Paul Waite for the info that floated divs will not expand the height of the parent div! This has been driving me nuts! ;-}

What was the strangest coding standard rule that you were forced to follow?

If I remember correctly the delphi IDE did a default indent of two spaces. Most of the legacy code for the company had three spaces and was written by the VP IT and the CEO. One day, all the programmers were talking about what we should do to make our lives easier and a contractor who knew Delphi pretty well said, "Hey the ide defaults to two spaces does anyone have a problem with us doing this going forward for new code?" All of us looked at each other, and pretty much thought it was a no brainer and said that we agreed.

Two days later the VP and CEO found out we were going to make such a dangerous change that could "cause problems" and instructed us that we would be using three indents for everything until the two of them could accurately evaluate the impact of such a change. Now I am all for following standards, but these are the same people who thought oo programming was creating an object with one function that had all of the logic necessary to perform an action, and that source control was moving the code files to a different directory.

How to use addTarget method in swift 3

In swift 3 use this -

object?.addTarget(objectWhichHasMethod, action: #selector(classWhichHasMethod.yourMethod), for: someUIControlEvents)

For example(from my code) -

self.datePicker?.addTarget(self, action:#selector(InfoTableViewCell.datePickerValueChanged), for: .valueChanged)

Just give a : after method name if you want the sender as parameter.

Ubuntu: OpenJDK 8 - Unable to locate package

I was having the same issue and tried all of the solutions on this page but none of them did the trick.

What finally worked was adding the universe repo to my repo list. To do that run the following command

sudo add-apt-repository universe

After running the above command I was able to run

sudo apt install openjdk-8-jre

without an issue and the package was installed.

Hope this helps someone.

Angular 4 - get input value

html

<input type="hidden" #fondovalor value="valores">
     <button (click)="getFotoFondo()">Obtener</button>

ts

@ViewChild('fondovalor') fondovalor:ElementRef;

getFotoFondo(){ 
        const valueInput = this.fondovalor.nativeElement.value
}

Append data frames together in a for loop

x <- c(1:10) 

# empty data frame with variables ----

df <- data.frame(x1=character(),
                     y1=character())

for (i in x) {
  a1 <- c(x1 == paste0("The number is ",x[i]),y1 == paste0("This is another number ", x[i]))
  df <- rbind(df,a1)
}

names(df) <- c("st_column","nd_column")
View(df)

that might be a good way to do so....

Action bar navigation modes are deprecated in Android L

The new Android Design Support Library adds TabLayout, providing a tab implementation that matches the material design guidelines for tabs. A complete walkthrough of how to implement Tabs and ViewPager can be found in this video

Now deprecated: The PagerTabStrip is part of the support library (and has been for some time) and serves as a direct replacement. If you prefer the newer Google Play style tabs, you can use the PagerSlidingTabStrip library or modify either of the Google provided examples SlidingTabsBasic or SlidingTabsColors as explained in this Dev Bytes video.

How to save LogCat contents to file?

To save the Log cat content to the file, you need to redirect to the android sdk's platform tools folder and hit the below command

adb logcat > logcat.txt

In Android Studio, version 3.6RC1, file will be created of the name "logcat.txt" in respective project folder. you can change the name according to your interest. enjoy

sql insert into table with select case values

If FName and LName contain NULL values, then you will need special handling to avoid unnecessary extra preceeding, trailing, and middle spaces. Also, if Address1 contains NULL values, then you need to have special handling to prevent adding unnecessary ', ' at the beginning of your address string.

If you are using SQL Server 2012, then you can use CONCAT (NULLs are automatically treated as empty strings) and IIF:

INSERT INTO TblStuff (FullName, Address, City, Zip)
SELECT FullName = REPLACE(RTRIM(LTRIM(CONCAT(FName, ' ', Middle, ' ', LName))), '  ', ' ')
    , Address = CONCAT(Address1, IIF(Address2 IS NOT NULL, CONCAT(', ', Address2), ''))
    , City
    , Zip
FROM tblImport (NOLOCK);

Otherwise, this will work:

INSERT INTO TblStuff (FullName, Address, City, Zip)
SELECT FullName = REPLACE(RTRIM(LTRIM(ISNULL(FName, '') + ' ' + ISNULL(Middle, '') + ' ' + ISNULL(LName, ''))), '  ', ' ')
    , Address = ISNULL(Address1, '') + CASE
        WHEN Address2 IS NOT NULL THEN ', ' + Address2
        ELSE '' END
    , City
    , Zip
FROM tblImport (NOLOCK);

Best C++ IDE or Editor for Windows

SlickEdit is very cool, and does support something like intellisense. At my current company I now use Visual Studio, and I've mostly gotten used to it - but there are still some SlickEdit features I miss.

Call child method from parent

Here my demo: https://stackblitz.com/edit/react-dgz1ee?file=styles.css

I am using useEffect to call the children component's methods. I have tried with Proxy and Setter_Getter but sor far useEffect seems to be the more convenient way to call a child method from parent. To use Proxy and Setter_Getter it seems there is some subtlety to overcome first, because the element firstly rendered is an objectLike's element through the ref.current return => <div/>'s specificity. Concerning useEffect, you can also leverage on this approach to set the parent's state depending on what you want to do with the children.

In the demo's link I have provided, you will find my full ReactJS' code with my draftwork inside's so you can appreciate the workflow of my solution.

Here I am providing you my ReactJS' snippet with the relevant code only. :

import React, {
  Component,
  createRef,
  forwardRef,
  useState,
  useEffect
} from "react"; 

{...}

// Child component
// I am defining here a forwardRef's element to get the Child's methods from the parent
// through the ref's element.
let Child = forwardRef((props, ref) => {
  // I am fetching the parent's method here
  // that allows me to connect the parent and the child's components
  let { validateChildren } = props;
  // I am initializing the state of the children
  // good if we can even leverage on the functional children's state
  let initialState = {
    one: "hello world",
    two: () => {
      console.log("I am accessing child method from parent :].");
      return "child method achieve";
    }
  };
  // useState initialization
  const [componentState, setComponentState] = useState(initialState);
  // useEffect will allow me to communicate with the parent
  // through a lifecycle data flow
  useEffect(() => {
    ref.current = { componentState };
    validateChildren(ref.current.componentState.two);
  });

{...}

});

{...}

// Parent component
class App extends Component {
  // initialize the ref inside the constructor element
  constructor(props) {
    super(props);
    this.childRef = createRef();
  }

  // I am implementing a parent's method
  // in child useEffect's method
  validateChildren = childrenMethod => {
    // access children method from parent
    childrenMethod();
    // or signaling children is ready
    console.log("children active");
  };

{...}
render(){
       return (
          {
            // I am referencing the children
            // also I am implementing the parent logic connector's function
            // in the child, here => this.validateChildren's function
          }
          <Child ref={this.childRef} validateChildren={this.validateChildren} />
        </div>
       )
}

How to find out what the date was 5 days ago?

Use the built in date_sub and date_add functions to math with dates. (See http://php.net/manual/en/datetime.sub.php)

Similar to Sazzad's answer, but in procedural style PHP,

$date = date_create('2008-12-02');
date_sub($date, date_interval_create_from_date_string('5 days'));
echo date_format($date, 'Y-m-d'); //outputs 2008-11-27

Do a "git export" (like "svn export")?

I have another solution that works fine if you have a local copy of the repository on the machine where you would like to create the export. In this case move to this repository directory, and enter this command:

GIT_WORK_TREE=outputdirectory git checkout -f

This is particularly useful if you manage a website with a git repository and would like to checkout a clean version in /var/www/. In this case, add thiscommand in a .git/hooks/post-receive script (hooks/post-receive on a bare repository, which is more suitable in this situation)

Hide axis values but keep axis tick labels in matplotlib

If you use the matplotlib object-oriented approach, this is a simple task using ax.set_xticklabels() and ax.set_yticklabels():

import matplotlib.pyplot as plt

# Create Figure and Axes instances
fig,ax = plt.subplots(1)

# Make your plot, set your axes labels
ax.plot(sim_1['t'],sim_1['V'],'k')
ax.set_ylabel('V')
ax.set_xlabel('t')

# Turn off tick labels
ax.set_yticklabels([])
ax.set_xticklabels([])

plt.show()

android - setting LayoutParams programmatically

For Xamarin Android align to the left of an object

int dp24 = (int)TypedValue.ApplyDimension( ComplexUnitType.Dip, 24, Resources.System.DisplayMetrics );
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( dp24, dp24 );
            lp.AddRule( LayoutRules.CenterInParent, 1 );
            lp.AddRule( LayoutRules.LeftOf, //Id of the field Eg m_Button.Id ); 
            m_Button.LayoutParameters = lp;

Is it possible in Java to check if objects fields are null and then add default value to all those attributes?

Non-reflective solution for Java 8, without using a series of if's, would be to stream all fields and check for nullness:

return Stream.of(id, name).allMatch(Objects::isNull);

This remains quite easy to maintain while avoiding the reflection hammer. This will return true for null attributes.

JavaScript - populate drop down list with array

["1","2","3","4"].forEach( function(item) { 
   const optionObj = document.createElement("option");
   optionObj.textContent = item;
   document.getElementById("myselect").appendChild(optionObj);
});

What is VanillaJS?

This is VanillaJS (unmodified):

// VanillaJS v1.0
// Released into the Public Domain
// Your code goes here:

As you can see, it's not really a framework or a library. It's just a running gag for framework-loving bosses or people who think you NEED to use a JS framework. It means you just use whatever your (for you own sake: non-legacy) browser gives you (using Vanilla JS when working with legacy browsers is a bad idea).

Swift - iOS - Dates and times in different format

func convertDateFormater(date: String) -> String {   
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    dateFormatter.timeZone = NSTimeZone(name: "UTC")

    guard let date = dateFormatter.dateFromString(date) else {
        assert(false, "no date from string")
        return ""
    }

    dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"
    dateFormatter.timeZone = NSTimeZone(name: "UTC")
    let timeStamp = dateFormatter.stringFromDate(date)

    return timeStamp
}

Edit for Swift 4

func convertDateFormatter(date: String) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"//this your string date format
    dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
    dateFormatter.locale = Locale(identifier: "your_loc_id")
    let convertedDate = dateFormatter.date(from: date)

    guard dateFormatter.date(from: date) != nil else {
        assert(false, "no date from string")
        return ""
    } 

    dateFormatter.dateFormat = "yyyy MMM HH:mm EEEE"///this is what you want to convert format
    dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
    let timeStamp = dateFormatter.string(from: convertedDate!)

    return timeStamp
}

How to convert JSON to XML or XML to JSON?

Here is the full c# code to convert xml to json

public static class JSon
{
public static string XmlToJSON(string xml)
{
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);

    return XmlToJSON(doc);
}
public static string XmlToJSON(XmlDocument xmlDoc)
{
    StringBuilder sbJSON = new StringBuilder();
    sbJSON.Append("{ ");
    XmlToJSONnode(sbJSON, xmlDoc.DocumentElement, true);
    sbJSON.Append("}");
    return sbJSON.ToString();
}

//  XmlToJSONnode:  Output an XmlElement, possibly as part of a higher array
private static void XmlToJSONnode(StringBuilder sbJSON, XmlElement node, bool showNodeName)
{
    if (showNodeName)
        sbJSON.Append("\"" + SafeJSON(node.Name) + "\": ");
    sbJSON.Append("{");
    // Build a sorted list of key-value pairs
    //  where   key is case-sensitive nodeName
    //          value is an ArrayList of string or XmlElement
    //  so that we know whether the nodeName is an array or not.
    SortedList<string, object> childNodeNames = new SortedList<string, object>();

    //  Add in all node attributes
    if (node.Attributes != null)
        foreach (XmlAttribute attr in node.Attributes)
            StoreChildNode(childNodeNames, attr.Name, attr.InnerText);

    //  Add in all nodes
    foreach (XmlNode cnode in node.ChildNodes)
    {
        if (cnode is XmlText)
            StoreChildNode(childNodeNames, "value", cnode.InnerText);
        else if (cnode is XmlElement)
            StoreChildNode(childNodeNames, cnode.Name, cnode);
    }

    // Now output all stored info
    foreach (string childname in childNodeNames.Keys)
    {
        List<object> alChild = (List<object>)childNodeNames[childname];
        if (alChild.Count == 1)
            OutputNode(childname, alChild[0], sbJSON, true);
        else
        {
            sbJSON.Append(" \"" + SafeJSON(childname) + "\": [ ");
            foreach (object Child in alChild)
                OutputNode(childname, Child, sbJSON, false);
            sbJSON.Remove(sbJSON.Length - 2, 2);
            sbJSON.Append(" ], ");
        }
    }
    sbJSON.Remove(sbJSON.Length - 2, 2);
    sbJSON.Append(" }");
}

//  StoreChildNode: Store data associated with each nodeName
//                  so that we know whether the nodeName is an array or not.
private static void StoreChildNode(SortedList<string, object> childNodeNames, string nodeName, object nodeValue)
{
    // Pre-process contraction of XmlElement-s
    if (nodeValue is XmlElement)
    {
        // Convert  <aa></aa> into "aa":null
        //          <aa>xx</aa> into "aa":"xx"
        XmlNode cnode = (XmlNode)nodeValue;
        if (cnode.Attributes.Count == 0)
        {
            XmlNodeList children = cnode.ChildNodes;
            if (children.Count == 0)
                nodeValue = null;
            else if (children.Count == 1 && (children[0] is XmlText))
                nodeValue = ((XmlText)(children[0])).InnerText;
        }
    }
    // Add nodeValue to ArrayList associated with each nodeName
    // If nodeName doesn't exist then add it
    List<object> ValuesAL;

    if (childNodeNames.ContainsKey(nodeName))
    {
        ValuesAL = (List<object>)childNodeNames[nodeName];
    }
    else
    {
        ValuesAL = new List<object>();
        childNodeNames[nodeName] = ValuesAL;
    }
    ValuesAL.Add(nodeValue);
}

private static void OutputNode(string childname, object alChild, StringBuilder sbJSON, bool showNodeName)
{
    if (alChild == null)
    {
        if (showNodeName)
            sbJSON.Append("\"" + SafeJSON(childname) + "\": ");
        sbJSON.Append("null");
    }
    else if (alChild is string)
    {
        if (showNodeName)
            sbJSON.Append("\"" + SafeJSON(childname) + "\": ");
        string sChild = (string)alChild;
        sChild = sChild.Trim();
        sbJSON.Append("\"" + SafeJSON(sChild) + "\"");
    }
    else
        XmlToJSONnode(sbJSON, (XmlElement)alChild, showNodeName);
    sbJSON.Append(", ");
}

// Make a string safe for JSON
private static string SafeJSON(string sIn)
{
    StringBuilder sbOut = new StringBuilder(sIn.Length);
    foreach (char ch in sIn)
    {
        if (Char.IsControl(ch) || ch == '\'')
        {
            int ich = (int)ch;
            sbOut.Append(@"\u" + ich.ToString("x4"));
            continue;
        }
        else if (ch == '\"' || ch == '\\' || ch == '/')
        {
            sbOut.Append('\\');
        }
        sbOut.Append(ch);
    }
    return sbOut.ToString();
 }
}

To convert a given XML string to JSON, simply call XmlToJSON() function as below.

string xml = "<menu id=\"file\" value=\"File\"> " +
              "<popup>" +
                "<menuitem value=\"New\" onclick=\"CreateNewDoc()\" />" +
                "<menuitem value=\"Open\" onclick=\"OpenDoc()\" />" +
                "<menuitem value=\"Close\" onclick=\"CloseDoc()\" />" +
              "</popup>" +
            "</menu>";

string json = JSON.XmlToJSON(xml);
// json = { "menu": {"id": "file", "popup": { "menuitem": [ {"onclick": "CreateNewDoc()", "value": "New" }, {"onclick": "OpenDoc()", "value": "Open" }, {"onclick": "CloseDoc()", "value": "Close" } ] }, "value": "File" }}

How to stop mongo DB in one command

create a file called mongostop.bat

save the following code in it

 mongo admin --eval "db.shutdownServer()"

run the file mongostop.bat and you successfully have mongo stopped

What is the better API to Reading Excel sheets in java - JXL or Apache POI

I am not familiar with JXL and but we use POI. POI is well maintained and can handle both the binary .xls format and the new xml based format that was introduced in Office 2007.

CSV files are not excel files, they are text based files, so these libraries don't read them. You will need to parse out a CSV file yourself. I am not aware of any CSV file libraries, but I haven't looked either.

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

^ outside of the character class ("[a-zA-Z]") notes that it is the "begins with" operator.
^ inside of the character negates the specified class.

So, "^[a-zA-Z]" translates to "begins with character from a-z or A-Z", and "[^a-zA-Z]" translates to "is not either a-z or A-Z"

Here's a quick reference: http://www.regular-expressions.info/reference.html

Unable to install gem - Failed to build gem native extension - cannot load such file -- mkmf (LoadError)

For MacOS users:

Just do this and easily it will solve your problem:

brew install cocoapods

Bulk Insertion in Laravel using eloquent ORM

From Laravel 5.7 with Illuminate\Database\Query\Builder you can use insertUsing method.

$query = [];
foreach($oXML->results->item->item as $oEntry){
    $date = date("Y-m-d H:i:s")
    $query[] = "('{$oEntry->firstname}', '{$oEntry->lastname}', '{$date}')";
}

Builder::insertUsing(['first_name', 'last_name', 'date_added'], implode(', ', $query));

"Invalid signature file" when attempting to run a .jar

Assuming you build your jar file with ant, you can just instruct ant to leave out the META-INF dir. This is a simplified version of my ant target:

<jar destfile="app.jar" basedir="${classes.dir}">
    <zipfileset excludes="META-INF/**/*" src="${lib.dir}/bcprov-jdk16-145.jar"></zipfileset>
    <manifest>
        <attribute name="Main-Class" value="app.Main"/>
    </manifest>
</jar>