Programs & Examples On #Online game

ps1 cannot be loaded because running scripts is disabled on this system

Another solution is Remove ng.ps1 from the directory C:\Users%username%\AppData\Roaming\npm\ and clearing the npm cache

Selecting a Record With MAX Value

Say, for an user, there is revision for each date. The following will pick up record for the max revision of each date for each employee.

select job, adate, rev, usr, typ 
from tbl
where exists (  select 1 from ( select usr, adate, max(rev) as max_rev 
                                from tbl
                                group by usr, adate 
                              ) as cond
                where tbl.usr=cond.usr 
                and tbl.adate =cond.adate 
                and tbl.rev =cond.max_rev
             )
order by adate, job, usr

How do I get the current Date/time in DD/MM/YYYY HH:MM format?

For date:

#!/usr/bin/ruby -w

date = Time.new
#set 'date' equal to the current date/time. 

date = date.day.to_s + "/" + date.month.to_s + "/" + date.year.to_s
#Without this it will output 2015-01-10 11:33:05 +0000; this formats it to display DD/MM/YYYY

puts date
#output the date

The above will display, for example, 10/01/15

And for time

time = Time.new
#set 'time' equal to the current time. 

time = time.hour.to_s + ":" + time.min.to_s
#Without this it will output 2015-01-10 11:33:05 +0000; this formats it to display hour and           minute

puts time
#output the time

The above will display, for example, 11:33

Then to put it together, add to the end:

puts date + " " + time

Is there a way to detach matplotlib plots so that the computation can continue?

On my system show() does not block, although I wanted the script to wait for the user to interact with the graph (and collect data using 'pick_event' callbacks) before continuing.

In order to block execution until the plot window is closed, I used the following:

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(x,y)

# set processing to continue when window closed
def onclose(event):
    fig.canvas.stop_event_loop()
fig.canvas.mpl_connect('close_event', onclose)

fig.show() # this call does not block on my system
fig.canvas.start_event_loop_default() # block here until window closed

# continue with further processing, perhaps using result from callbacks

Note, however, that canvas.start_event_loop_default() produced the following warning:

C:\Python26\lib\site-packages\matplotlib\backend_bases.py:2051: DeprecationWarning: Using default event loop until function specific to this GUI is implemented
  warnings.warn(str,DeprecationWarning)

although the script still ran.

How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

You can use Delorean to travel in space and time!

import datetime
import delorean
dt = datetime.datetime.utcnow()
delorean.Delorean(dt, timezone="UTC").epoch

http://delorean.readthedocs.org/en/latest/quickstart.html  

Converting Array to List

the first way is better, the second way cost more time on creating a new array and converting to a list

node.js: cannot find module 'request'

if some module you cant find, try with Static URI, for example:

var Mustache = require("/media/fabio/Datos/Express/2_required_a_module/node_modules/mustache/mustache.js");

This example, run on Ubuntu Gnome 16.04 of 64 bits, node -v: v4.2.6, npm: 3.5.2 Refer to: Blog of Ben Nadel

How to check if all elements of a list matches a condition?

You could use itertools's takewhile like this, it will stop once a condition is met that fails your statement. The opposite method would be dropwhile

for x in itertools.takewhile(lambda x: x[2] == 0, list)
    print x

send/post xml file using curl command line

If you have multiple headers then you might want to use the following:

curl -X POST --header "Content-Type:application/json" --header "X-Auth:AuthKey" --data @hello.json Your_url

Java Could not reserve enough space for object heap error

Double click Liferay CE Server -> add -XX:MaxHeapSize=512m to Memory args -> Start server! Enjoy...

It's work for me!

AngularJS: How can I pass variables between controllers?

If you don't want to make service then you can do like this.

var scope = angular.element("#another ctrl scope element id.").scope();
scope.plean_assign = some_value;

How to get an input text value in JavaScript

<script type="text/javascript">
function kk(){
    var lol = document.getElementById('lolz').value;
    alert(lol);
}


</script>

<body onload="onload();">
    <input type="text" name="enter" class="enter" id="lolz" value=""/>
    <input type="button" value="click" onclick="kk();"/>
</body>

use this

TypeError: got multiple values for argument

This happens when a keyword argument is specified that overwrites a positional argument. For example, let's imagine a function that draws a colored box. The function selects the color to be used and delegates the drawing of the box to another function, relaying all extra arguments.

def color_box(color, *args, **kwargs):
    painter.select_color(color)
    painter.draw_box(*args, **kwargs)

Then the call

color_box("blellow", color="green", height=20, width=30)

will fail because two values are assigned to color: "blellow" as positional and "green" as keyword. (painter.draw_box is supposed to accept the height and width arguments).

This is easy to see in the example, but of course if one mixes up the arguments at call, it may not be easy to debug:

# misplaced height and width
color_box(20, 30, color="green")

Here, color is assigned 20, then args=[30] and color is again assigned "green".

Include another HTML file in a HTML file

PHP is a server level scripting language. It can do many things, but one popular use is to include HTML documents inside your pages, much the same as SSI. Like SSI, this is a server level technology. If you are not sure if you have PHP functionality on your website contact your hosting provider.

Here is a simple PHP script you can use to include a snippet of HTML on any PHP-enabled web page:

Save the HTML for the common elements of your site to separate files. For example, your navigation section might be saved as navigation.html or navigation.php. Use the following PHP code to include that HTML in each page.

<?php require($DOCUMENT_ROOT . "navigation.php"); ?>

Use that same code on every page that you want to include the file. Make sure to change the higlighted file name to the name and path to your include file.

Hot deploy on JBoss - how do I make JBoss "see" the change?

Hot deployment is stable only for changes on static parts of the application (jsf, xhtml, etc.).

Here is a working solution, according to JBoss AS 7.1.1.Final:

  • Build your project.
  • Navigate to [JBOSS_HOME]/standalone/tmp/vfs.
  • Open the most recently modified folder named "deployment[some_alphanumeric_values]", i.e. "deployment344b1c870c8edbd".
  • Navigate to the specific view that you want to edit (usually, this is included into the packaged .war folder) and open it with a text editor (i.e. Notepad++).
  • Make the changes you want and save the file.
  • Refresh the respective page on your browser. The changes should be visible now.
  • When finished, don't forget to copy these changes to your actual development environment, rebuild and redeploy.

    CSS Layout - Dynamic width DIV

    Or, if you know the width of the two "side" images and don't want to deal with floats:

    <div class="container">
        <div class="left-panel"><img src="myleftimage" /></div>
        <div class="center-panel">Content goes here...</div>
        <div class="right-panel"><img src="myrightimage" /></div>
    </div>
    

    CSS:

    .container {
        position:relative;
        padding-left:50px;
        padding-right:50px;
    }
    
    .container .left-panel {
        width: 50px;
        position:absolute;
        left:0px;
        top:0px;
    }
    
    .container .right-panel {
        width: 50px;
        position:absolute;
        right:0px;
        top:0px;
    }
    
    .container .center-panel {
        background: url('mymiddleimage');
    }
    

    Notes:

    Position:relative on the parent div is used to make absolutely positioned children position themselves relative to that node.

    Why is my element value not getting changed? Am I using the wrong function?

    If you are using Chrome, then debug with the console. Press SHIFT+CTRL+j to get the console on screen.

    Trust me, it helps a lot.

    Calculate the date yesterday in JavaScript

    This will produce yesterday at 00:00 with minutes precision

    var d = new Date();
    d.setDate(d.getDate() - 1);
    d.setTime(d.getTime()-d.getHours()*3600*1000-d.getMinutes()*60*1000);
    

    How to Find Item in Dictionary Collection?

    thisTag = _tags.FirstOrDefault(t => t.Key == tag);
    

    is an inefficient and a little bit strange way to find something by key in a dictionary. Looking things up for a Key is the basic function of a Dictionary.

    The basic solution would be:

    if (_tags.Containskey(tag)) { string myValue = _tags[tag]; ... }
    

    But that requires 2 lookups.

    TryGetValue(key, out value) is more concise and efficient, it only does 1 lookup. And that answers the last part of your question, the best way to do a lookup is:

    string myValue;
    if (_tags.TryGetValue(tag, out myValue)) { /* use myValue */ }
    

    VS 2017 update, for C# 7 and beyond we can declare the result variable inline:

    if (_tags.TryGetValue(tag, out string myValue))
    {
        // use myValue;
    }
    // use myValue, still in scope, null if not found
    

    Adding and removing extensionattribute to AD object

    Or the -Remove parameter

    Set-ADUser -Identity anyUser -Remove @{extensionAttribute4="myString"}
    

    Repair all tables in one go

    for plesk hosts, one of these should do: (both do the same)

    mysqlrepair -uadmin -p$(cat /etc/psa/.psa.shadow) -A
    # or
    mysqlcheck -uadmin -p$(cat /etc/psa/.psa.shadow) --repair -A
    

    How do I do an initial push to a remote repository with Git?

    You can try this:

    on Server:

    adding new group to /etc/group like (example)

    mygroup:1001:michael,nir
    

    create new git repository:

    mkdir /srv/git
    cd /srv/git
    mkdir project_dir
    cd project_dir
    git --bare init (initial git repository )
    chgrp -R mygroup objects/ refs/ (change owner of directory )
    chmod -R g+w objects/ refs/ (give permission write)
    

    on Client:

    mkdir my_project
    cd my_project
    touch .gitignore
    git init
    git add .
    git commit -m "Initial commit"
    git remote add origin [email protected]:/path/to/my_project.git
    git push origin master
    

    (Thanks Josh Lindsey for client side)

    after Client, do on Server this commands:

    cd /srv/git/project_dir
    chmod -R g+w objects/ refs/
    

    If got this error after git pull:

    There is no tracking information for the current branch. Please specify which branch you want to merge with. See git-pull(1) for details
    
    git pull <remote> <branch>
    If you wish to set tracking information for this branch you can do so with:
    
    git branch --set-upstream new origin/<branch>
    

    try:

    git push -u origin master
    

    It will help.

    Recommended method for escaping HTML in Java

    For those who use Google Guava:

    import com.google.common.html.HtmlEscapers;
    [...]
    String source = "The less than sign (<) and ampersand (&) must be escaped before using them in HTML";
    String escaped = HtmlEscapers.htmlEscaper().escape(source);
    

    Bootstrap: change background color

    You can target that div from your stylesheet in a number of ways.

    Simply use

    .col-md-6:first-child {
      background-color: blue;
    }
    

    Another way is to assign a class to one div and then apply the style to that class.

    <div class="col-md-6 blue"></div>
    
    .blue {
      background-color: blue;
    }
    

    There are also inline styles.

    <div class="col-md-6" style="background-color: blue"></div>
    

    Your example code works fine to me. I'm not sure if I undestand what you intend to do, but if you want a blue background on the second div just remove the bg-primary class from the section and add you custom class to the div.

    _x000D_
    _x000D_
    .blue {_x000D_
      background-color: blue;_x000D_
    }
    _x000D_
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
    _x000D_
    <section id="about">_x000D_
      <div class="container">_x000D_
        <div class="row">_x000D_
        <!-- Columns are always 50% wide, on mobile and desktop -->_x000D_
          <div class="col-xs-6">_x000D_
            <h2 class="section-heading text-center">Title</h2>_x000D_
            <p class="text-faded text-center">.col-md-6</p>_x000D_
          </div>_x000D_
          <div class="col-xs-6 blue">_x000D_
            <h2 class="section-heading text-center">Title</h2>_x000D_
            <p class="text-faded text-center">.col-md-6</p>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </section>
    _x000D_
    _x000D_
    _x000D_

    Make an image responsive - the simplest way

    I use this all the time

    You can customize the img class and the max-width property:

    img{
        width: 100%;
        max-width: 800px;
    }
    

    max-width is important. Otherwise your image will scale too much for the desktop. There isn't any need to put in the height property, because by default it is auto mode.

    Firefox and SSL: sec_error_unknown_issuer

    June 2014:

    This is the configuration I used and it working fine after banging my head on the wall for some days. I use Express 3.4 (I think is the same for Express 4.0)

    var privateKey  = fs.readFileSync('helpers/sslcert/key.pem', 'utf8');
    var certificate = fs.readFileSync('helpers/sslcert/csr.pem', 'utf8');
    
    files = ["COMODORSADomainValidationSecureServerCA.crt",
             "COMODORSAAddTrustCA.crt",
             "AddTrustExternalCARoot.crt"
            ];
    
    ca = (function() {
      var _i, _len, _results;
    
      _results = [];
      for (_i = 0, _len = files.length; _i < _len; _i++) {
        file = files[_i];
        _results.push(fs.readFileSync("helpers/sslcert/" + file));
      }
      return _results;
    })();
    
    var credentials = {ca:ca, key: privateKey, cert: certificate};
    
    // process.env.PORT : Heroku Config environment
    var port = process.env.PORT || 4000;
    
    var app = express();
    var server = http.createServer(app).listen(port, function() {
            console.log('Express HTTP server listening on port ' + server.address().port);
    });
    https.createServer(credentials, app).listen(3000, function() {
            console.log('Express HTTPS server listening on port ' + server.address().port);
    });
    
    // redirect all http requests to https
    app.use(function(req, res, next) {
      if(!req.secure) {
        return res.redirect(['https://mydomain.com', req.url].join(''));
      }
      next();
    });
    

    Then I redirected the 80 and 443 ports:

    sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 4000
    sudo iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-ports 3000
    

    As you can see after checking my certifications I have 4 [0,1,2,3]:

    openssl s_client -connect mydomain.com:443 -showcerts | grep "^ "

    ubuntu@ip-172-31-5-134:~$ openssl s_client -connect mydomain.com:443 -showcerts | grep "^ "
    depth=3 C = SE, O = AddTrust AB, OU = AddTrust External TTP Network, CN = AddTrust External CA Root
    verify error:num=19:self signed certificate in certificate chain
    verify return:0
     0 s:/OU=Domain Control Validated/OU=PositiveSSL/CN=mydomain.com
       i:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Domain Validation Secure Server CA
     1 s:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Domain Validation Secure Server CA
       i:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Certification Authority
     2 s:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Certification Authority
       i:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root
     3 s:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root
       i:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root
        Protocol  : TLSv1.1
        Cipher    : AES256-SHA
        Session-ID: 8FDEAEE92ED20742.....3E7D80F93226142DD
        Session-ID-ctx:
        Master-Key: C9E4AB966E41A85EEB7....4D73C67088E1503C52A9353C8584E94
        Key-Arg   : None
        PSK identity: None
        PSK identity hint: None
        SRP username: None
        TLS session ticket lifetime hint: 300 (seconds)
        TLS session ticket:
        0000 - 7c c8 36 80 95 4d 4c 47-d8 e3 ca 2e 70 a5 8f ac   |.6..MLG....p...
        0010 - 90 bd 4a 26 ef f7 d6 bc-4a b3 dd 8f f6 13 53 e9   ..J&..........S.
        0020 - f7 49 c6 48 44 26 8d ab-a8 72 29 c8 15 73 f5 79   .I.HD&.......s.y
        0030 - ca 79 6a ed f6 b1 7f 8a-d2 68 0a 52 03 c5 84 32   .yj........R...2
        0040 - be c5 c8 12 d8 f4 36 fa-28 4f 0e 00 eb d1 04 ce   ........(.......
        0050 - a7 2b d2 73 df a1 8b 83-23 a6 f7 ef 6e 9e c4 4c   .+.s...........L
        0060 - 50 22 60 e8 93 cc d8 ee-42 22 56 a7 10 7b db 1e   P"`.....B.V..{..
        0070 - 0a ad 4a 91 a4 68 7a b0-9e 34 01 ec b8 7b b2 2f   ..J......4...{./
        0080 - e8 33 f5 a9 48 11 36 f8-69 a6 7a a6 22 52 b1 da   .3..H...i....R..
        0090 - 51 18 ed c4 d9 3d c4 cc-5b d7 ff 92 4e 91 02 9e   .....=......N...
        Start Time: 140...549
        Timeout   : 300 (sec)
        Verify return code: 19 (self signed certificate in certificate chain)
    

    Good luck! PD: if u want more answers please check: http://www.benjiegillam.com/2012/06/node-dot-js-ssl-certificate-chain/

    Numpy: find index of the elements within range

    Other way is with:

    np.vectorize(lambda x: 6 <= x <= 10)(a)
    

    which returns:

    array([False, False, False,  True,  True,  True, False, False, False])
    

    It is sometimes useful for masking time series, vectors, etc.

    How to format a DateTime in PowerShell

    If you got here to use this in cmd.exe (in a batch file):

    powershell -Command (Get-Date).ToString('yyyy-MM-dd')
    

    SSRS Query execution failed for dataset

    I enabled remote errors to pinpoint the problem.

    I identified that a column in a particular dataset (one of my views) was throwing an error.

    So using a tool "SQL Delta", I compared the development version of the database with the live version on the reporting server. I noticed that one of the views had an extra column on the development server, that was not on the live version of the db.

    SQL Delta generated the script I needed to run to update the view on my live db.

    I ran this script, re-ran the report, everything worked.

    .NET HttpClient. How to POST string value?

    Below is example to call synchronously but you can easily change to async by using await-sync:

    var pairs = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("login", "abc")
                };
    
    var content = new FormUrlEncodedContent(pairs);
    
    var client = new HttpClient {BaseAddress = new Uri("http://localhost:6740")};
    
        // call sync
    var response = client.PostAsync("/api/membership/exist", content).Result; 
    if (response.IsSuccessStatusCode)
    {
    }
    

    Git fatal: protocol 'https' is not supported

    Edit: This particular users problem was solved by starting a new terminal session.

    A ? before the protocol (https) is not support. You want this:

    git clone [email protected]:octocat/Spoon-Knife.git

    or this:

    git clone https://github.com/octocat/Spoon-Knife.git

    Selecting the location to clone

    Getting the PublicKeyToken of .Net assemblies

    As an alternative, you can also use linq like this -

        string key = string.Join ("",assembly
                                    .GetName()
                                    .GetPublicKeyToken()
                                    .Select (b => b.ToString ("x2")));
    

    Why is Github asking for username/password when following the instructions on screen and pushing a new repo?

    Don't use HTTP use SSH instead

    change

    https://github.com/WEMP/project-slideshow.git 
    

    to

    [email protected]:WEMP/project-slideshow.git
    

    you can do it in .git/config file

    How to match, but not capture, part of a regex?

    I have modified one of the answers (by @op1ekun):

    123-(apple(?=-)|banana(?=-)|(?!-))-?456
    

    The reason is that the answer from @op1ekun also matches "123-apple456", without the hyphen after apple.

    python numpy/scipy curve fitting

    I suggest you to start with simple polynomial fit, scipy.optimize.curve_fit tries to fit a function f that you must know to a set of points.

    This is a simple 3 degree polynomial fit using numpy.polyfit and poly1d, the first performs a least squares polynomial fit and the second calculates the new points:

    import numpy as np
    import matplotlib.pyplot as plt
    
    points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
    # get x and y vectors
    x = points[:,0]
    y = points[:,1]
    
    # calculate polynomial
    z = np.polyfit(x, y, 3)
    f = np.poly1d(z)
    
    # calculate new x's and y's
    x_new = np.linspace(x[0], x[-1], 50)
    y_new = f(x_new)
    
    plt.plot(x,y,'o', x_new, y_new)
    plt.xlim([x[0]-1, x[-1] + 1 ])
    plt.show()
    

    enter image description here

    Set folder for classpath

    If you are using Java 6 or higher you can use wildcards of this form:

    java -classpath ".;c:\mylibs\*;c:\extlibs\*" MyApp
    

    If you would like to add all subdirectories: lib\a\, lib\b\, lib\c\, there is no mechanism for this in except:

    java -classpath ".;c:\lib\a\*;c:\lib\b\*;c:\lib\c\*" MyApp
    

    There is nothing like lib\*\* or lib\** wildcard for the kind of job you want to be done.

    Add string in a certain position in Python

    If you want many inserts

    from rope.base.codeanalyze import ChangeCollector
    
    c = ChangeCollector(code)
    c.add_change(5, 5, '<span style="background-color:#339999;">')
    c.add_change(10, 10, '</span>')
    rend_code = c.get_changed()
    

    How to test REST API using Chrome's extension "Advanced Rest Client"

    The shortcut format generally used for basic auth is http://username:[email protected]/path. You will also want to include the accept header in the request.

    enter image description here

    How to add new contacts in android

    These examples are fine, I wanted to point out that you can achieve the same result using an Intent. The intent opens the Contacts app with the fields you provide already filled in.

    It's up to the user to save the newly created contact.

    You can read about it here: https://developer.android.com/training/contacts-provider/modify-data.html

    Intent contactIntent = new Intent(ContactsContract.Intents.Insert.ACTION);
    contactIntent.setType(ContactsContract.RawContacts.CONTENT_TYPE);
    
    contactIntent
            .putExtra(ContactsContract.Intents.Insert.NAME, "Contact Name")
            .putExtra(ContactsContract.Intents.Insert.PHONE, "5555555555");
    
    startActivityForResult(contactIntent, 1);
    

    startActivityForResult() gives you the opportunity to see the result.

    I've noticed the resultCode works on >5.0 devices,

    but I have an older Samsung (<5) that always returns RESULT_CANCELLED (0).

    Which I understand is the default return if an activity doesn't expect to return anything.

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
    
        if (requestCode == 1)
        {
            if (resultCode == Activity.RESULT_OK) {
                Toast.makeText(this, "Added Contact", Toast.LENGTH_SHORT).show();
            }
            if (resultCode == Activity.RESULT_CANCELED) {
                Toast.makeText(this, "Cancelled Added Contact", Toast.LENGTH_SHORT).show();
            }
        }
    }
    

    Arrays.asList() of an array

    there are two cause of this exception:

    1

    Arrays.asList(factors) returns a List<int[]> where factors is an int array

    2

    you forgot to add the type parameter to:

    ArrayList<Integer> f = new ArrayList(Arrays.asList(factors));
    

    with:

    ArrayList<Integer> f = new ArrayList<Integer>(Arrays.asList(factors));  
    

    resulting in a compile-time error:

    found   : java.util.List<int[]>
    required: java.util.List<java.lang.Integer>
    

    document.getElementByID is not a function

    It worked like this for me:

    document.getElementById("theElementID").setAttribute("src", source);
    document.getElementById("task-text").innerHTML = "";
    

    Change the

    getElementById("theElementID")
    

    for your element locator (name, css, xpath...)

    Use FontAwesome or Glyphicons with css :before

    @keithwyland answer is great. Here's a SCSS mixin:

    @mixin font-awesome($content){
        font-family: FontAwesome;
        font-weight: normal;
        font-style: normal;
        display: inline-block;
        text-decoration: inherit;
        content: $content;
    }
    

    Usage:

    @include font-awesome("\f054");
    

    Viewing all `git diffs` with vimdiff

    git config --global diff.tool vimdiff
    git config --global difftool.prompt false
    

    Typing git difftool yields the expected behavior.

    Navigation commands,

    • :qa in vim cycles to the next file in the changeset without saving anything.

    Aliasing (example)

    git config --global alias.d difftool
    

    .. will let you type git d to invoke vimdiff.

    Advanced use-cases,

    • By default, git calls vimdiff with the -R option. You can override it with git config --global difftool.vimdiff.cmd 'vimdiff "$LOCAL" "$REMOTE"'. That will open vimdiff in writeable mode which allows edits while diffing.
    • :wq in vim cycles to the next file in the changeset with changes saved.

    How do I get a value of datetime.today() in Python that is "timezone aware"?

    In the standard library, there is no cross-platform way to create aware timezones without creating your own timezone class.

    On Windows, there's win32timezone.utcnow(), but that's part of pywin32. I would rather suggest to use the pytz library, which has a constantly updated database of most timezones.

    Working with local timezones can be very tricky (see "Further reading" links below), so you may rather want to use UTC throughout your application, especially for arithmetic operations like calculating the difference between two time points.

    You can get the current date/time like so:

    import pytz
    from datetime import datetime
    datetime.utcnow().replace(tzinfo=pytz.utc)
    

    Mind that datetime.today() and datetime.now() return the local time, not the UTC time, so applying .replace(tzinfo=pytz.utc) to them would not be correct.

    Another nice way to do it is:

    datetime.now(pytz.utc)
    

    which is a bit shorter and does the same.


    Further reading/watching why to prefer UTC in many cases:

    Fully backup a git repo?

    If it is on Github, Navigate to bitbucket and use "import repository" method to import your github repo as a private repo.

    If it is in bitbucket, Do the otherway around.

    It's a full backup but stays in the cloud which is my ideal method.

    Pass in an array of Deferreds to $.when()

    When calling multiple parallel AJAX calls, you have two options for handling the respective responses.

    1. Use Synchronous AJAX call/ one after another/ not recommended
    2. Use Promises' array and $.when which accepts promises and its callback .done gets called when all the promises are return successfully with respective responses.

    Example

    _x000D_
    _x000D_
    function ajaxRequest(capitalCity) {_x000D_
       return $.ajax({_x000D_
            url: 'https://restcountries.eu/rest/v1/capital/'+capitalCity,_x000D_
            success: function(response) {_x000D_
            },_x000D_
            error: function(response) {_x000D_
              console.log("Error")_x000D_
            }_x000D_
        });_x000D_
    }_x000D_
    $(function(){_x000D_
       var capitalCities = ['Delhi', 'Beijing', 'Washington', 'Tokyo', 'London'];_x000D_
       $('#capitals').text(capitalCities);_x000D_
    _x000D_
       function getCountryCapitals(){ //do multiple parallel ajax requests_x000D_
          var promises = [];   _x000D_
          for(var i=0,l=capitalCities.length; i<l; i++){_x000D_
                var promise = ajaxRequest(capitalCities[i]);_x000D_
                promises.push(promise);_x000D_
          }_x000D_
      _x000D_
          $.when.apply($, promises)_x000D_
            .done(fillCountryCapitals);_x000D_
       }_x000D_
      _x000D_
       function fillCountryCapitals(){_x000D_
            var countries = [];_x000D_
            var responses = arguments;_x000D_
            for(i in responses){_x000D_
                console.dir(responses[i]);_x000D_
                countries.push(responses[i][0][0].nativeName)_x000D_
            }  _x000D_
            $('#countries').text(countries);_x000D_
       }_x000D_
      _x000D_
       getCountryCapitals()_x000D_
    })
    _x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
    <div>_x000D_
      <h4>Capital Cities : </h4> <span id="capitals"></span>_x000D_
      <h4>Respective Country's Native Names : </h4> <span id="countries"></span>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    How can I get form data with JavaScript/jQuery?

    Here is a nice vanilla JS function I wrote to extract form data as an object. It also has options for inserting additions into the object, and for clearing the form input fields.

    const extractFormData = ({ form, clear, add }) => {
      return [].slice.call(form.children).filter(node => node.nodeName === 'INPUT')
      .reduce((formData, input) => {
        const value = input.value
        if (clear) { input.value = '' }
        return {
          ...formData,
          [input.name]: value
        }
      }, add)
    }
    

    Here is an example of its use with a post request:

    submitGrudge(e) {
      e.preventDefault()
    
      const form = e.target
      const add = { id: Date.now(), forgiven: false }
      const grudge = extractFormData({ form, add, clear: true })
    
      // grudge = {
      //  "name": "Example name",
      //  "offense": "Example string",
      //  "date": "2017-02-16",
      //  "id": 1487877281983,
      //  "forgiven": false
      // }
    
      fetch('http://localhost:3001/api/grudge', {
        method: 'post',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(grudge)
      })
        .then(response => response.json())
        .then(grudges => this.setState({ grudges }))
        .catch(err => console.log('error: ', err))
    }
    

    Installed Ruby 1.9.3 with RVM but command line doesn't show ruby -v

    • Open Terminal.
    • Go to Edit -> Profile Preferences.
    • Select the Title & command Tab in the window opened.
    • Mark the checkbox Run command as login shell.
    • close the window and restart the Terminal.

    Check this Official Linkenter image description here

    How to drop rows of Pandas DataFrame whose value in a certain column is NaN

    You could use dataframe method notnull or inverse of isnull, or numpy.isnan:

    In [332]: df[df.EPS.notnull()]
    Out[332]:
       STK_ID  RPT_Date  STK_ID.1  EPS  cash
    2  600016  20111231    600016  4.3   NaN
    4  601939  20111231    601939  2.5   NaN
    
    
    In [334]: df[~df.EPS.isnull()]
    Out[334]:
       STK_ID  RPT_Date  STK_ID.1  EPS  cash
    2  600016  20111231    600016  4.3   NaN
    4  601939  20111231    601939  2.5   NaN
    
    
    In [347]: df[~np.isnan(df.EPS)]
    Out[347]:
       STK_ID  RPT_Date  STK_ID.1  EPS  cash
    2  600016  20111231    600016  4.3   NaN
    4  601939  20111231    601939  2.5   NaN
    

    how to query child objects in mongodb

    Assuming your "states" collection is like:

    {"name" : "Spain", "cities" : [ { "name" : "Madrid" }, { "name" : null } ] }
    {"name" : "France" }
    

    The query to find states with null cities would be:

    db.states.find({"cities.name" : {"$eq" : null, "$exists" : true}});
    

    It is a common mistake to query for nulls as:

    db.states.find({"cities.name" : null});
    

    because this query will return all documents lacking the key (in our example it will return Spain and France). So, unless you are sure the key is always present you must check that the key exists as in the first query.

    Quickest way to convert XML to JSON in Java

    To convert XML File in to JSON include the following dependency

    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20140107</version>
    </dependency>
    

    and you can Download Jar from Maven Repository here. Then implement as:

    String soapmessageString = "<xml>yourStringURLorFILE</xml>";
    JSONObject soapDatainJsonObject = XML.toJSONObject(soapmessageString);
    System.out.println(soapDatainJsonObject);
    

    How to make layout with rounded corners..?

    Try this...

    1.create drawable xml(custom_layout.xml):

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" >
    
    <solid android:color="#FFFFFF" />
    
    <stroke
        android:width="2dp"
        android:color="#FF785C" />
    
    <corners android:radius="10dp" />
    
    </shape>
    

    2.add your view background

    android:background="@drawable/custom_layout"
    

    "405 method not allowed" in IIS7.5 for "PUT" method

    In my case I had relocated Web Deploy to another port, which was also the IIS port (not 80). I didn't realize at first, but even though there were no errors running both under the same port, seems Web Deploy was most likely responding first instead of IIS for some reason, causing this error. I just moved my IIS binding to another port and all is well. ;)

    How to Generate Unique Public and Private Key via RSA

    When you use a code like this:

    using (var rsa = new RSACryptoServiceProvider(1024))
    {
       // Do something with the key...
       // Encrypt, export, etc.
    }
    

    .NET (actually Windows) stores your key in a persistent key container forever. The container is randomly generated by .NET

    This means:

    1. Any random RSA/DSA key you have EVER generated for the purpose of protecting data, creating custom X.509 certificate, etc. may have been exposed without your awareness in the Windows file system. Accessible by anyone who has access to your account.

    2. Your disk is being slowly filled with data. Normally not a big concern but it depends on your application (e.g. it might generates hundreds of keys every minute).

    To resolve these issues:

    using (var rsa = new RSACryptoServiceProvider(1024))
    {
       try
       {
          // Do something with the key...
          // Encrypt, export, etc.
       }
       finally
       {
          rsa.PersistKeyInCsp = false;
       }
    }
    

    ALWAYS

    Notification not showing in Oreo

    In android Oreo,notification app is done by using channels and NotificationHelper class.It should have a channel id and channel name.

    First u have to create a NotificationHelper Class

    public class NotificationHelper extends ContextWrapper {
    
    private static final String EDMT_CHANNEL_ID="com.example.safna.notifier1.EDMTDEV";
    private static final String EDMT_CHANNEL_NAME="EDMTDEV Channel";
    private NotificationManager manager;
    
    public  NotificationHelper(Context base)
    {
        super(base);
        createChannels();
    }
    private void createChannels()
    {
        NotificationChannel edmtChannel=new NotificationChannel(EDMT_CHANNEL_ID,EDMT_CHANNEL_NAME,NotificationManager.IMPORTANCE_DEFAULT);
        edmtChannel.enableLights(true);
        edmtChannel.enableVibration(true);
        edmtChannel.setLightColor(Color.GREEN);
        edmtChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
    
        getManager().createNotificationChannel(edmtChannel);
    
    }
    public NotificationManager getManager()
    {
       if (manager==null)
           manager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
       return manager;
    
    }
    public NotificationCompat.Builder getEDMTChannelNotification(String title,String body)
    {
        return new NotificationCompat.Builder(getApplicationContext(),EDMT_CHANNEL_ID)
                .setContentText(body)
                .setContentTitle(title)
                .setSmallIcon(R.mipmap.ic_launcher_round)
                .setAutoCancel(true);
        }
    }
    

    Create a button in activity xml file,then In the main activity

    protected void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        helper=new NotificationHelper(this);
    
        btnSend=(Button)findViewById(R.id.btnSend);
    
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String title="Title";
                String content="Content";
                Notification.Builder builder=helper.getEDMTChannelNotification(title,content);
                helper.getManager().notify(new Random().nextInt(),builder.build());
            }
        });
    
    }
    

    Then run ur project

    Move column by name to front of table in pandas

    I prefer this solution:

    col = df.pop("Mid")
    df.insert(0, col.name, col)
    

    It's simpler to read and faster than other suggested answers.

    def move_column_inplace(df, col, pos):
        col = df.pop(col)
        df.insert(pos, col.name, col)
    

    Performance assessment:

    For this test, the currently last column is moved to the front in each repetition. In-place methods generally perform better. While citynorman's solution can be made in-place, Ed Chum's method based on .loc and sachinnm's method based on reindex cannot.

    While other methods are generic, citynorman's solution is limited to pos=0. I didn't observe any performance difference between df.loc[cols] and df[cols], which is why I didn't include some other suggestions.

    I tested with python 3.6.8 and pandas 0.24.2 on a MacBook Pro (Mid 2015).

    import numpy as np
    import pandas as pd
    
    n_cols = 11
    df = pd.DataFrame(np.random.randn(200000, n_cols),
                      columns=range(n_cols))
    
    def move_column_inplace(df, col, pos):
        col = df.pop(col)
        df.insert(pos, col.name, col)
    
    def move_to_front_normanius_inplace(df, col):
        move_column_inplace(df, col, 0)
        return df
    
    def move_to_front_chum(df, col):
        cols = list(df)
        cols.insert(0, cols.pop(cols.index(col)))
        return df.loc[:, cols]
    
    def move_to_front_chum_inplace(df, col):
        col = df[col]
        df.drop(col.name, axis=1, inplace=True)
        df.insert(0, col.name, col)
        return df
    
    def move_to_front_elpastor(df, col):
        cols = [col] + [ c for c in df.columns if c!=col ]
        return df[cols] # or df.loc[cols]
    
    def move_to_front_sachinmm(df, col):
        cols = df.columns.tolist()
        cols.insert(0, cols.pop(cols.index(col)))
        df = df.reindex(columns=cols, copy=False)
        return df
    
    def move_to_front_citynorman_inplace(df, col):
        # This approach exploits that reset_index() moves the index
        # at the first position of the data frame.
        df.set_index(col, inplace=True)
        df.reset_index(inplace=True)
        return df
    
    def test(method, df):
        col = np.random.randint(0, n_cols)
        method(df, col)
    
    col = np.random.randint(0, n_cols)
    ret_mine = move_to_front_normanius_inplace(df.copy(), col)
    ret_chum1 = move_to_front_chum(df.copy(), col)
    ret_chum2 = move_to_front_chum_inplace(df.copy(), col)
    ret_elpas = move_to_front_elpastor(df.copy(), col)
    ret_sach = move_to_front_sachinmm(df.copy(), col)
    ret_city = move_to_front_citynorman_inplace(df.copy(), col)
    
    # Assert equivalence of solutions.
    assert(ret_mine.equals(ret_chum1))
    assert(ret_mine.equals(ret_chum2))
    assert(ret_mine.equals(ret_elpas))
    assert(ret_mine.equals(ret_sach))
    assert(ret_mine.equals(ret_city))
    

    Results:

    # For n_cols = 11:
    %timeit test(move_to_front_normanius_inplace, df)
    # 1.05 ms ± 42.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    %timeit test(move_to_front_citynorman_inplace, df)
    # 1.68 ms ± 46.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    %timeit test(move_to_front_sachinmm, df)
    # 3.24 ms ± 96.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    %timeit test(move_to_front_chum, df)
    # 3.84 ms ± 114 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    %timeit test(move_to_front_elpastor, df)
    # 3.85 ms ± 58.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    %timeit test(move_to_front_chum_inplace, df)
    # 9.67 ms ± 101 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    
    
    # For n_cols = 31:
    %timeit test(move_to_front_normanius_inplace, df)
    # 1.26 ms ± 31.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    %timeit test(move_to_front_citynorman_inplace, df)
    # 1.95 ms ± 260 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    %timeit test(move_to_front_sachinmm, df)
    # 10.7 ms ± 348 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    %timeit test(move_to_front_chum, df)
    # 11.5 ms ± 869 µs per loop (mean ± std. dev. of 7 runs, 100 loops each
    %timeit test(move_to_front_elpastor, df)
    # 11.4 ms ± 598 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    %timeit test(move_to_front_chum_inplace, df)
    # 31.4 ms ± 1.89 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
    

    hibernate could not get next sequence value

    Please use the following query and alter your table : CREATE SEQUENCE user_id_seq START 1; ALTER TABLE product.users ALTER COLUMN user_id SET DEFAULT nextval('user_id_seq'); ALTER SEQUENCE users.user_id_seq OWNED BY users.user_id;

    and use the this in your entity class

    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator="user_id_seq")

    Creating a recursive method for Palindrome

    Some of the codes are string heavy. Instead of creating substring which creates new object, we can just pass on indexes in recursive calls like below:

    private static boolean isPalindrome(String str, int left, int right) {
        if(left >= right) {
            return true;
        }
        else {
            if(str.charAt(left) == str.charAt(right)) {
    
                return isPalindrome(str, ++left, --right);
            }
            else {
                return false;
            }
        }
    }
    
    
     public static void main(String []args){
        String str = "abcdcbb"; 
        System.out.println(isPalindrome(str, 0, str.length()-1));
     }
    

    Converting a SimpleXML Object to an Array

    Just (array) is missing in your code before the simplexml object:

    ...
    
    $xml   = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);
    
    $array = json_decode(json_encode((array)$xml), TRUE);
                                     ^^^^^^^
    ...
    

    How to get single value of List<object>

    Define a class like this :

    public class myclass {
           string id ;
           string title ;
           string content;
     }
    
     public class program {
            public void Main () {
                   List<myclass> objlist = new List<myclass> () ;
                   foreach (var value in objlist)  {
                           TextBox1.Text = value.id ;
                           TextBox2.Text= value.title;
                           TextBox3.Text= value.content ;
                    }
             }
      }
    

    I tried to draw a sketch and you can improve it in many ways. Instead of defining class "myclass", you can define struct.

    How to set javascript variables using MVC4 with Razor

    Not so much an answer as a cautionary tale: this was bugging me as well - and I thought I had a solution by pre-pending a zero and using the @(...) syntax. i.e your code would have been:

    var nonID = 0@(nonProID);
    var proID = 0@(proID);
    

    Getting output like:

    var nonId = 0123;
    

    What I didn't realise was that this is how JavaScript (version 3) represents octal/base-8 numbers and is actually altering the value. Additionally, if you are using the "use strict"; command then it will break your code entirely as octal numbers have been removed.

    I'm still looking for a proper solution to this.

    Deleting multiple elements from a list

    If you're deleting multiple non-adjacent items, then what you describe is the best way (and yes, be sure to start from the highest index).

    If your items are adjacent, you can use the slice assignment syntax:

    a[2:10] = []
    

    How to display a list inline using Twitter's Bootstrap

    Bootstrap 2.3.2

    <ul class="inline">
      <li>...</li>
    </ul>
    

    Bootstrap 3

    <ul class="list-inline">
      <li>...</li>
    </ul>
    

    Bootstrap 4

    <ul class="list-inline">
      <li class="list-inline-item">Lorem ipsum</li>
      <li class="list-inline-item">Phasellus iaculis</li>
      <li class="list-inline-item">Nulla volutpat</li>
    </ul>
    

    source: http://v4-alpha.getbootstrap.com/content/typography/#inline

    Updated link https://getbootstrap.com/docs/4.4/content/typography/#inline

    How to iterate object in JavaScript?

    Use dot notation and/or bracket notation to access object properties and for loops to iterate arrays:

    var d, i;
    
    for (i = 0; i < dictionary.data.length; i++) {
      d = dictionary.data[i];
      alert(d.id + ' ' + d.name);
    }
    

    You can also iterate arrays using for..in loops; however, properties added to Array.prototype may show through, and you may not necessarily get array elements in their correct order, or even in any consistent order.

    Attach the Source in Eclipse of a jar

    I am using project is not Spring or spring boot based application. I have multiple subprojects and they are nested one within another. The answers shown here supports on first level of subproject. If I added another sub project for source code attachement, it is not allowing me saying folder already exists error.

    Looks like eclipse is out dated IDE. I am using the latest version of Eclipse version 2015-2019. It is killing all my time.

    My intension is run the application in debug mode navigate through the sub projects which are added as external dependencies (non modifiable).

    Using Html.ActionLink to call action on different controller

    Note that Details is a "View" page under the "Products" folder.

    ProductId is the primary key of the table . Here is the line from Index.cshtml

     @Html.ActionLink("Details", "Details","Products" , new  {  id=item.ProductId  },null)
    

    Change the "No file chosen":

     .vendor_logo_hide{
          display: inline !important;;
          color: transparent;
          width: 99px;
        }
        .vendor_logo{
          display: block !important;
          color: black;
          width: 100%; 
        }
    

    _x000D_
    _x000D_
    $(document).ready(function() {_x000D_
      // set text to select company logo _x000D_
      $("#Uploadfile").after("<span class='file_placeholder'>Select Company Logo</span>");_x000D_
      // on change_x000D_
      $('#Uploadfile').change(function() {_x000D_
        //  show file name _x000D_
        if ($("#Uploadfile").val().length > 0) {_x000D_
          $(".file_placeholder").empty();_x000D_
          $('#Uploadfile').removeClass('vendor_logo_hide').addClass('vendor_logo');_x000D_
          console.log($("#Uploadfile").val());_x000D_
        } else {_x000D_
          // show select company logo_x000D_
          $('#Uploadfile').removeClass('vendor_logo').addClass('vendor_logo_hide');_x000D_
          $("#Uploadfile").after("<span class='file_placeholder'>Select  Company Logo</span>");_x000D_
        }_x000D_
    _x000D_
      });_x000D_
    _x000D_
    });
    _x000D_
    .vendor_logo_hide {_x000D_
      display: inline !important;_x000D_
      ;_x000D_
      color: transparent;_x000D_
      width: 99px;_x000D_
    }_x000D_
    _x000D_
    .vendor_logo {_x000D_
      display: block !important;_x000D_
      color: black;_x000D_
      width: 100%;_x000D_
    }
    _x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>_x000D_
    <input type="file" class="vendor_logo_hide" name="v_logo" id='Uploadfile'>_x000D_
    <span class="fa fa-picture-o form-control-feedback"></span>_x000D_
    _x000D_
    <div>_x000D_
      <p>Here defualt no choose file is set to select company logo. if File is selected then it will displays file name</p>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    In CSS how do you change font size of h1 and h2

    What have you tried? This should work.

    h1 { font-size: 20pt; }
    h2 { font-size: 16pt; }
    

    Get list of all input objects using JavaScript, without accessing a form object

    querySelectorAll returns a NodeList which has its own forEach method:

    document.querySelectorAll('input').forEach( input => {
      // ...
    });
    

    getElementsByTagName now returns an HTMLCollection instead of a NodeList. So you would first need to convert it to an array to have access to methods like map and forEach:

    Array.from(document.getElementsByTagName('input')).forEach( input => {
      // ...
    });
    

    Send request to curl with post data sourced from a file

    You're looking for the --data-binary argument:

    curl -i -X POST host:port/post-file \
      -H "Content-Type: text/xml" \
      --data-binary "@path/to/file"
    

    In the example above, -i prints out all the headers so that you can see what's going on, and -X POST makes it explicit that this is a post. Both of these can be safely omitted without changing the behaviour on the wire. The path to the file needs to be preceded by an @ symbol, so curl knows to read from a file.

    Check if a parameter is null or empty in a stored procedure

    To check if variable is null or empty use this

    IF(@PreviousStartDate IS NULL OR @PreviousStartDate = '')
    

    How to make a promise from setTimeout

    Implementation:

    // Promisify setTimeout
    const pause = (ms, cb, ...args) =>
      new Promise((resolve, reject) => {
        setTimeout(async () => {
          try {
            resolve(await cb?.(...args))
          } catch (error) {
            reject(error)
          }
        }, ms)
      })
    

    Tests:

    // Test 1
    pause(1000).then(() => console.log('called'))
    // Test 2
    pause(1000, (a, b, c) => [a, b, c], 1, 2, 3).then(value => console.log(value))
    // Test 3
    pause(1000, () => {
      throw Error('foo')
    }).catch(error => console.error(error))
    

    PHP: How to use array_filter() to filter array keys?

    Starting from PHP 5.6, you can use the ARRAY_FILTER_USE_KEY flag in array_filter:

    $result = array_filter($my_array, function ($k) use ($allowed) {
        return in_array($k, $allowed);
    }, ARRAY_FILTER_USE_KEY);
    


    Otherwise, you can use this function (from TestDummy):

    function filter_array_keys(array $array, $callback)
    {
        $matchedKeys = array_filter(array_keys($array), $callback);
    
        return array_intersect_key($array, array_flip($matchedKeys));
    }
    
    $result = filter_array_keys($my_array, function ($k) use ($allowed) {
        return in_array($k, $allowed);
    });
    


    And here is an augmented version of mine, which accepts a callback or directly the keys:

    function filter_array_keys(array $array, $keys)
    {
        if (is_callable($keys)) {
            $keys = array_filter(array_keys($array), $keys);
        }
    
        return array_intersect_key($array, array_flip($keys));
    }
    
    // using a callback, like array_filter:
    $result = filter_array_keys($my_array, function ($k) use ($allowed) {
        return in_array($k, $allowed);
    });
    
    // or, if you already have the keys:
    $result = filter_array_keys($my_array, $allowed));
    


    Last but not least, you may also use a simple foreach:

    $result = [];
    foreach ($my_array as $key => $value) {
        if (in_array($key, $allowed)) {
            $result[$key] = $value;
        }
    }
    

    How to center horizontally div inside parent div

    <div id='parent' style='width: 100%;text-align:center;'>
     <div id='child' style='width:50px; height:100px;margin:0px auto;'>Text</div>
    </div>
    

    powershell is missing the terminator: "

    This error will also occur if you call .ps1 file from a .bat file and file path has spaces.

    The fix is to make sure there are no spaces in the path of .ps1 file.

    Which Architecture patterns are used on Android?

    In the Notifications case, the NotificationCompat.Builder uses Builder Pattern

    like,

    mBuilder = new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_stat_notification)
                        .setContentTitle(getString(R.string.notification))
                        .setContentText(getString(R.string.ping))
                        .setDefaults(Notification.DEFAULT_ALL);
    

    Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?'

    pip install pymysql
    

    Then, edit the __init__.py file in your project origin dir(the same as settings.py)

    add:

    import pymysql
    
    pymysql.install_as_MySQLdb()
    

    How can I stop "property does not exist on type JQuery" syntax errors when using Typescript?

    Since printArea is a jQuery plugin it is not included in jquery.d.ts.

    You need to create a jquery.printArea.ts definition file.

    If you create a complete definition file for the plugin you may want to submit it to DefinitelyTyped.

    Run chrome in fullscreen mode on Windows

    • Right click the Google Chrome icon and select Properties.
    • Copy the value of Target, for example: "C:\Users\zero\AppData\Local\Google\Chrome\Application\chrome.exe".
    • Create a shortcut on your Desktop.
    • Paste the value into Location of the item, and append --kiosk <your url>:

      "C:\Users\zero\AppData\Local\Google\Chrome\Application\chrome.exe" --kiosk http://www.google.com
      
    • Press Apply, then OK.

    • To start Chrome at Windows startup, copy this shortcut and paste it into the Startup folder (Start -> Program -> Startup).

    Is it possible to use std::string in a constexpr?

    No, and your compiler already gave you a comprehensive explanation.

    But you could do this:

    constexpr char constString[] = "constString";
    

    At runtime, this can be used to construct a std::string when needed.

    Why do abstract classes in Java have constructors?

    Because another class could extend it, and the child class needs to invoke a superclass constructor.

    RSA encryption and decryption in Python

    In order to make it work you need to convert key from str to tuple before decryption(ast.literal_eval function). Here is fixed code:

    import Crypto
    from Crypto.PublicKey import RSA
    from Crypto import Random
    import ast
    
    random_generator = Random.new().read
    key = RSA.generate(1024, random_generator) #generate pub and priv key
    
    publickey = key.publickey() # pub key export for exchange
    
    encrypted = publickey.encrypt('encrypt this message', 32)
    #message to encrypt is in the above line 'encrypt this message'
    
    print 'encrypted message:', encrypted #ciphertext
    f = open ('encryption.txt', 'w')
    f.write(str(encrypted)) #write ciphertext to file
    f.close()
    
    #decrypted code below
    
    f = open('encryption.txt', 'r')
    message = f.read()
    
    
    decrypted = key.decrypt(ast.literal_eval(str(encrypted)))
    
    print 'decrypted', decrypted
    
    f = open ('encryption.txt', 'w')
    f.write(str(message))
    f.write(str(decrypted))
    f.close()
    

    How can I open Java .class files in a human-readable way?

    As suggested you can use JAD to decompile it and view the files. To make it easier to read you can use the JADclipse plugin for eclipse to integrate JAD directly to eclipse or use DJ Java Decompiler which is much easier to use than command line JAD

    nodemon not working: -bash: nodemon: command not found

    From you own project.

    npx nodemon [your-app.js]
    

    With a local installation, nodemon will not be available in your system path. Instead, the local installation of nodemon can be run by calling it from within an npm script (such as npm start) or using npx nodemon.

    OR

    Create a simple symbolik link

    ln -s /Users/YourUsername/.npm-global/bin/nodemon /usr/local/bin
    

    ln -s [from: where is you install 'nodemon'] [to: folder where are general module for node]

    node : v12.1.0

    npm : 6.9.0

    How to copy directories with spaces in the name

    You should write brackets only before path: "c:\program files\

    Why is my asynchronous function returning Promise { <pending> } instead of a value?

    Your Promise is pending, complete it by

    userToken.then(function(result){
    console.log(result)
    })
    

    after your remaining code. All this code does is that .then() completes your promise & captures the end result in result variable & print result in console. Keep in mind, you cannot store the result in global variable. Hope that explanation might help you.

    Datanode process not running in Hadoop

    You need to check :

    /app/hadoop/tmp/dfs/data/current/VERSION and /app/hadoop/tmp/dfs/name/current/VERSION ---

    in those two files and that to Namespace ID of name node and datanode.

    If and only if data node's NamespaceID is same as name node's NamespaceID then your datanode will run.

    If those are different copy the namenode NamespaceID to your Datanode's NamespaceID using vi editor or gedit and save and re run the deamons it will work perfectly.

    Methods vs Constructors in Java

    A constructor is a special kind of method that allows you to create a new instance of a class. It concerns itself with initialization logic.

    Installing PIL (Python Imaging Library) in Win7 64 bits, Python 2.6.4

    http://www.lfd.uci.edu/~gohlke/pythonlibs/

    press contrl F type Pillow-2.4.0.win-amd64-py3.3.exe

    then click and downloadd the 64 bit version

    Pillow is a replacement for PIL, the Python Image Library, which provides image processing functionality and supports many file formats. Note: use from PIL import Image instead of import Image. PIL-1.1.7.win-amd64-py2.5.exe PIL-1.1.7.win32-py2.5.exe Pillow-2.4.0.win-amd64-py2.6.exe Pillow-2.4.0.win-amd64-py2.7.exe Pillow-2.4.0.win-amd64-py3.2.exe Pillow-2.4.0.win-amd64-py3.3.exe Pillow-2.4.0.win-amd64-py3.4.exe Pillow-2.4.0.win32-py2.6.exe Pillow-2.4.0.win32-py2.7.exe Pillow-2.4.0.win32-py3.2.exe Pillow-2.4.0.win32-py3.3.exe Pillow-2.4.0.win32-py3.4.exe

    n-grams in python, four, five, six grams?

    Great native python based answers given by other users. But here's the nltk approach (just in case, the OP gets penalized for reinventing what's already existing in the nltk library).

    There is an ngram module that people seldom use in nltk. It's not because it's hard to read ngrams, but training a model base on ngrams where n > 3 will result in much data sparsity.

    from nltk import ngrams
    
    sentence = 'this is a foo bar sentences and i want to ngramize it'
    
    n = 6
    sixgrams = ngrams(sentence.split(), n)
    
    for grams in sixgrams:
      print grams
    

    Entity framework code-first null foreign key

    I have the same problem now , I have foreign key and i need put it as nullable, to solve this problem you should put

        modelBuilder.Entity<Country>()
            .HasMany(c => c.Users)
            .WithOptional(c => c.Country)
            .HasForeignKey(c => c.CountryId)
            .WillCascadeOnDelete(false);
    

    in DBContext class I am sorry for answer you very late :)

    Sorting arrays in NumPy by column

    In case someone wants to make use of sorting at a critical part of their programs here's a performance comparison for the different proposals:

    import numpy as np
    table = np.random.rand(5000, 10)
    
    %timeit table.view('f8,f8,f8,f8,f8,f8,f8,f8,f8,f8').sort(order=['f9'], axis=0)
    1000 loops, best of 3: 1.88 ms per loop
    
    %timeit table[table[:,9].argsort()]
    10000 loops, best of 3: 180 µs per loop
    
    import pandas as pd
    df = pd.DataFrame(table)
    %timeit df.sort_values(9, ascending=True)
    1000 loops, best of 3: 400 µs per loop
    

    So, it looks like indexing with argsort is the quickest method so far...

    How do I make Git ignore file mode (chmod) changes?

    If you have used chmod command already then check the difference of file, It shows previous file mode and current file mode such as:

    new mode : 755

    old mode : 644

    set old mode of all files using below command

    sudo chmod 644 .

    now set core.fileMode to false in config file either using command or manually.

    git config core.fileMode false
    

    then apply chmod command to change the permissions of all files such as

    sudo chmod 755 .
    

    and again set core.fileMode to true.

    git config core.fileMode true
    

    For best practises don't Keep core.fileMode false always.

    Removing spaces from a variable input using PowerShell 4.0

    You also have the Trim, TrimEnd and TrimStart methods of the System.String class. The trim method will strip whitespace (with a couple of Unicode quirks) from the leading and trailing portion of the string while allowing you to optionally specify the characters to remove.

    #Note there are spaces at the beginning and end
    Write-Host " ! This is a test string !%^ "
     ! This is a test string !%^
    #Strips standard whitespace
    Write-Host " ! This is a test string !%^ ".Trim()
    ! This is a test string !%^
    #Strips the characters I specified
    Write-Host " ! This is a test string !%^ ".Trim('!',' ')
    This is a test string !%^
    #Now removing ^ as well
    Write-Host " ! This is a test string !%^ ".Trim('!',' ','^')
    This is a test string !%
    Write-Host " ! This is a test string !%^ ".Trim('!',' ','^','%')
    This is a test string
    #Powershell even casts strings to character arrays for you
    Write-Host " ! This is a test string !%^ ".Trim('! ^%')
    This is a test string
    

    TrimStart and TrimEnd work the same way just only trimming the start or end of the string.

    Disable scrolling on `<input type=number>`

    You can simply use the HTML onwheel attribute.

    This option have no effects on scrolling over other elements of the page.

    And add a listener for all inputs don't work in inputs dynamically created posteriorly.

    Aditionaly, you can remove the input arrows with CSS.

    _x000D_
    _x000D_
    input[type="number"]::-webkit-outer-spin-button, _x000D_
    input[type="number"]::-webkit-inner-spin-button {_x000D_
        -webkit-appearance: none;_x000D_
        margin: 0;_x000D_
    }_x000D_
    input[type="number"] {_x000D_
        -moz-appearance: textfield;_x000D_
    }
    _x000D_
    <input type="number" onwheel="this.blur()" />
    _x000D_
    _x000D_
    _x000D_

    Importing a GitHub project into Eclipse

    unanswered core problem persists:

    My working directory is now c:\users\projectname.git So then I try to import the project using the eclipse "import" option. When I try to import selecting the option "Use the new projects wizard" the source code is not imported, if I import selecting the option "Import as general project" the source code is imported but the created project created by Eclipse is not a java project. When selecting the option "Use the new projects wizard" and creating a new java project using the wizard should'nt the code be automatically imported ?

    Yes it should.

    It's a bug. Reported here.

    Here is a workaround:

    • Import as general project

    • Notice the imported data is no valid Eclipse project (no build path available)

    • Open the .project xml file in the project folder in Eclipse. If you can't see this file, see How can I get Eclipse to show .* files?.

    • Go to source tab

    • Search for <natures></natures> and change it to <natures><nature>org.eclipse.jdt.core.javanature</nature></natures> and save the file

      (idea comes from here)

    • Right click the src folder, go to Build Path... and click Use as Source Folder

    After that, you should be able to run & debug the project, and also use team actions via right-click in the package explorer.

    If you still have troubles running the project (something like "main class not found"), make sure the <buildSpec> inside the .project file is set (as described here):

    <buildSpec>
        <buildCommand>
            <name>org.eclipse.jdt.core.javabuilder</name>
            <arguments>
            </arguments>
        </buildCommand>
    </buildSpec>
    

    Convert integer value to matching Java Enum

    As @MeBigFatGuy says, except you can make your static {...} block use a loop over the values() collection:

    static {
        for (PcapLinkType type : PcapLinkType.values()) {
            intToTypeMap.put(type.getValue(), type);
        }
    }
    

    Java 8 Lambda Stream forEach with multiple statements

    List<String> items = new ArrayList<>();
    items.add("A");
    items.add("B");
    items.add("C");
    items.add("D");
    items.add("E");
    
    //lambda
    //Output : A,B,C,D,E
    items.forEach(item->System.out.println(item));
    
    //Output : C
    items.forEach(item->{
        System.out.println(item);
        System.out.println(item.toLowerCase());
      }
    });
    

    Insert data through ajax into mysql database

    The available answers led to the fact that I entered empty values into the database. I corrected this error by replacing the serialize () function with the following code.

    $(document).ready(function(){
    
    // When click the button.
    $("#button").click(function() {
    
        // Assigning Variables to Form Fields
        var email = $("#email").val();
    
        // Send the form data using the ajax method
        $.ajax({
            data: "email=" + email,
            type: "post",
            url: "your_file.php",
            success: function(data){
                alert("Data Save: " + data);
            }
        });
    
    });
    
    });
    

    Is there a difference between /\s/g and /\s+/g?

    + means "one or more characters" and without the plus it means "one character." In your case both result in the same output.

    Python Anaconda - How to Safely Uninstall

    To uninstall anaconda you have to:

    1) Remove the entire anaconda install directory with:

    rm -rf ~/anaconda2

    2) And (OPTIONAL):

    ->Edit ~/.bash_profile to remove the anaconda directory from your PATH environment variable.

    ->Remove the following hidden file and folders that may have been created in the home directory:

    rm -rf ~/.condarc ~/.conda ~/.continuum

    source

    Logical XOR operator in C++?

    There was some good code posted that solved the problem better than !a != !b

    Note that I had to add the BOOL_DETAIL_OPEN/CLOSE so it would work on MSVC 2010

    /* From: http://groups.google.com/group/comp.std.c++/msg/2ff60fa87e8b6aeb
    
       Proposed code    left-to-right?  sequence point?  bool args?  bool result?  ICE result?  Singular 'b'?
       --------------   --------------  ---------------  ---------- ------------  -----------  -------------
       a ^ b                  no              no             no          no           yes          yes
       a != b                 no              no             no          no           yes          yes
       (!a)!=(!b)             no              no             no          no           yes          yes
       my_xor_func(a,b)       no              no             yes         yes          no           yes
       a ? !b : b             yes             yes            no          no           yes          no
       a ? !b : !!b           yes             yes            no          no           yes          no
       [* see below]          yes             yes            yes         yes          yes          no
       (( a bool_xor b ))     yes             yes            yes         yes          yes          yes
    
       [* = a ? !static_cast<bool>(b) : static_cast<bool>(b)]
    
       But what is this funny "(( a bool_xor b ))"? Well, you can create some
       macros that allow you such a strange syntax. Note that the
       double-brackets are part of the syntax and cannot be removed! The set of
       three macros (plus two internal helper macros) also provides bool_and
       and bool_or. That given, what is it good for? We have && and || already,
       why do we need such a stupid syntax? Well, && and || can't guarantee
       that the arguments are converted to bool and that you get a bool result.
         Think "operator overloads". Here's how the macros look like:
    
       Note: BOOL_DETAIL_OPEN/CLOSE added to make it work on MSVC 2010
      */
    
    #define BOOL_DETAIL_AND_HELPER(x) static_cast<bool>(x):false
    #define BOOL_DETAIL_XOR_HELPER(x) !static_cast<bool>(x):static_cast<bool>(x)
    
    #define BOOL_DETAIL_OPEN (
    #define BOOL_DETAIL_CLOSE )
    
    #define bool_and BOOL_DETAIL_CLOSE ? BOOL_DETAIL_AND_HELPER BOOL_DETAIL_OPEN
    #define bool_or BOOL_DETAIL_CLOSE ? true:static_cast<bool> BOOL_DETAIL_OPEN
    #define bool_xor BOOL_DETAIL_CLOSE ? BOOL_DETAIL_XOR_HELPER BOOL_DETAIL_OPEN
    

    How can I check if a jQuery plugin is loaded?

    jQuery has a method to check if something is a function

    if ($.isFunction($.fn.dateJS)) {
        //your code using the plugin
    }
    

    API reference: https://api.jquery.com/jQuery.isFunction/

    How to write the code for the back button?

    Basically my code sends data to the next page like so:

    **Referring Page**
    $this = $_SERVER['PHP_SELF'];
    echo "<a href='next_page.php?prev=$this'>Next Page</a>";
    
    **Page with button**
    $prev = $_GET['prev'];
    echo "<a href='$prev'><button id='back'>Back</button></a>";
    

    Conda environments not showing up in Jupyter Notebook

    I had to run all the commands mentioned in the top 3 answers to get this working:

    conda install jupyter
    conda install nb_conda
    conda install ipykernel
    python -m ipykernel install --user --name mykernel
    

    How do I extract text that lies between parentheses (round brackets)?

    Assuming that you only have one pair of parenthesis.

    string s = "User name (sales)";
    int start = s.IndexOf("(") + 1;
    int end = s.IndexOf(")", start);
    string result = s.Substring(start, end - start);
    

    From io.Reader to string in Go

    var b bytes.Buffer
    b.ReadFrom(r)
    
    // b.String()
    

    How to loop through all elements of a form jQuery

    What happens, if you do this way:-

    $('#new_user_form input, #new_user_form select').each(function(key, value) {
    

    Refer LIVE DEMO

    How to check if a String contains another String in a case insensitive manner in Java?

    There is a simple concise way, using regex flag (case insensitive {i}):

     String s1 = "hello abc efg";
     String s2 = "ABC";
     s1.matches(".*(?i)"+s2+".*");
    
    /*
     * .*  denotes every character except line break
     * (?i) denotes case insensitivity flag enabled for s2 (String)
     * */
    

    java build path problems

    To configure your JRE in eclipse:

    • Window > Preferences > Java > Installed JREs...
    • Click Add
    • Find the directory of your JDK > Click OK

    How to serve an image using nodejs

    You should use the express framework.

    npm install express
    

    and then

    var express = require('express');
    var app = express();
    app.use(express.static(__dirname + '/public'));
    app.listen(8080);
    

    and then the URL localhost:8080/images/logo.gif should work.

    Can I start the iPhone simulator without "Build and Run"?

    To follow up on that the new command from @jimbojw to create a shortcut with the new Xcode (installing through preferences) is:

    ln -s /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone\ Simulator.app /Applications/iPhone\ Simulator.app
    

    Which will create a shortcut in the applications folder for you.

    jquery Ajax call - data parameters are not being passed to MVC Controller action

    You need add -> contentType: "application/json; charset=utf-8",

    <script type="text/javascript">
        $(document).ready( function() {
          $('#btnTest').click( function() {
            $.ajax({
              type: "POST", 
              url: "/Login/Test",
              data: { ListID: '1', ItemName: 'test' },
              dataType: "json",
              contentType: "application/json; charset=utf-8",
              success: function(response) { alert(response); },
              error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
            });
          });
        });
    </script>
    

    In SQL, is UPDATE always faster than DELETE+INSERT?

    A bit too late with this answer, but since I faced a similar question, I made a test with JMeter and a MySQL server on same machine, where I have used:

    1. A transaction Controller (generating parent sample) that contained two JDBC Requests: a Delete and an Insert statement
    2. A sepparate JDBC Request containing the Update statement.

    After running the test for 500 loops, I have obtained the following results:

    DEL + INSERT - Average: 62ms

    Update - Average: 30ms

    Results: Results

    How to prevent long words from breaking my div?

    For me on a div without fixed size and with dynamic content it worked using:

    display:table;
    word-break:break-all;
    

    How to install and use "make" in Windows?

    One solution that may helpful if you want to use the command line emulator cmder. You can install the package installer chocately. First we install chocately in windows command prompt using the following line:

    @"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"
    refreshenv
    

    After chocolatey is installed the choco command can be used to install make. Once installed, you will need add an alias to /cmder/config/user_aliases.cmd. The following line should be added:

    make="path_to_chocolatey\chocolatey\bin\make.exe" $*
    

    Make will then operate in the cmder environment.

    What is the difference between HTTP_HOST and SERVER_NAME in PHP?

    HTTP_HOST is the target host sent by the client. It can be manipulated freely by the user. It's no problem to send a request to your site asking for a HTTP_HOST value of www.stackoverflow.com.

    SERVER_NAME comes from the server's VirtualHost definition and is therefore considered more reliable. It can, however, also be manipulated from outside under certain conditions related to how your web server is set up: See this This SO question that deals with the security aspects of both variations.

    You shouldn't rely on either to be safe. That said, what to use really depends on what you want to do. If you want to determine which domain your script is running on, you can safely use HTTP_HOST as long as invalid values coming from a malicious user can't break anything.

    Why is list initialization (using curly braces) better than the alternatives?

    There are MANY reasons to use brace initialization, but you should be aware that the initializer_list<> constructor is preferred to the other constructors, the exception being the default-constructor. This leads to problems with constructors and templates where the type T constructor can be either an initializer list or a plain old ctor.

    struct Foo {
        Foo() {}
    
        Foo(std::initializer_list<Foo>) {
            std::cout << "initializer list" << std::endl;
        }
    
        Foo(const Foo&) {
            std::cout << "copy ctor" << std::endl;
        }
    };
    
    int main() {
        Foo a;
        Foo b(a); // copy ctor
        Foo c{a}; // copy ctor (init. list element) + initializer list!!!
    }
    

    Assuming you don't encounter such classes there is little reason not to use the intializer list.

    How to programmatically set drawableLeft on Android button?

    Try this:

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
         fillButton[i].setBackground(getBaseContext().getResources().getDrawable(R.drawable.drawable_name));
    }
    else {
        fillButton[i].setBackgroundColor(Color.argb(255,193,234,203));
    }
    

    How do I force a vertical scrollbar to appear?

    html { overflow-y: scroll; }
    

    This css rule causes a vertical scrollbar to always appear.

    Source: http://css-tricks.com/snippets/css/force-vertical-scrollbar/

    Remove all occurrences of char from string

    You can use str = str.replace("X", ""); as mentioned before and you will be fine. For your information '' is not an empty (or a valid) character but '\0' is.

    So you could use str = str.replace('X', '\0'); instead.

    bower proxy configuration

    For info, in your .bowerrc file you can add a no-proxy attribute. I don't know since when it is supported but it works on bower 1.7.4

    .bowerrc :

    {
      "directory": "bower_components", 
      "proxy": "http://yourProxy:yourPort",
      "https-proxy":"http://yourProxy:yourPort",
      "no-proxy":"myserver.mydomain.com"
    }
    

    .bowerrc should be located in the root folder of your Javascript project, the folder in which you launch the bower command. You can also have it in your home folder (~/.bowerrc).

    MySQL Select all columns from one table and some from another table

    Just use the table name:

    SELECT myTable.*, otherTable.foo, otherTable.bar...
    

    That would select all columns from myTable and columns foo and bar from otherTable.

    JavaScript naming conventions

    As Geoff says, what Crockford says is good.

    The only exception I follow (and have seen widely used) is to use $varname to indicate a jQuery (or whatever library) object. E.g.

    var footer = document.getElementById('footer');

    var $footer = $('#footer');

    Jenkins - passing variables between jobs?

    I faced the same issue when I had to pass a pom version to a downstream Rundeck job.

    What I did, was using parameters injection via a properties file as such:

    1) Creating properties in properties file via shell :

    Build actions:

    • Execute a shell script
    • Inject environment variables

    E.g : properties definition

    2) Passing defined properties to the downstream job : Post Build Actions :

    • Trigger parameterized build on other project
    • Add parameters : Current build parameters
    • Add parameters : predefined parameters

    E.g : properties sending

    3) It was then possible to use $POM_VERSION as such in the downstream Rundeck job.

    /!\ Jenkins Version : 1.636

    /!\ For some reason when creating the triggered build, it was necessary to add the option 'Current build parameters' to pass the properties.

    Get string character by index - Java

    It is as simple as:

    String charIs = string.charAt(index) + "";
    

    How do I install Java on Mac OSX allowing version switching?

    If you have multiple versions installed on your machine, add the following in bash profile:

    export JAVA_HOME_7=$(/usr/libexec/java_home -v1.7)

    export JAVA_HOME_8=$(/usr/libexec/java_home -v1.8)

    export JAVA_HOME_9=$(/usr/libexec/java_home -v9)

    And add the following aliases:

    alias java7='export JAVA_HOME=$JAVA_HOME_7'

    alias java8='export JAVA_HOME=$JAVA_HOME_8'

    alias java9='export JAVA_HOME=$JAVA_HOME_9'

    And can switch to required version by using the alias:

    In terminal:

    ~ >> java7 export JAVA_HOME=$JAVA_7_HOME

    SoapFault exception: Could not connect to host

    I had a bad php.ini configuration. Verify the path and the certificate validity...

    [openssl]
    openssl.cafile = "C:/good/phpath/ca-bundle.crt"
    

    Because my new \SoapClient($wsdl) was https !

    Efficiently convert rows to columns in sql server

    There are several ways that you can transform data from multiple rows into columns.

    Using PIVOT

    In SQL Server you can use the PIVOT function to transform the data from rows to columns:

    select Firstname, Amount, PostalCode, LastName, AccountNumber
    from
    (
      select value, columnname
      from yourtable
    ) d
    pivot
    (
      max(value)
      for columnname in (Firstname, Amount, PostalCode, LastName, AccountNumber)
    ) piv;
    

    See Demo.

    Pivot with unknown number of columnnames

    If you have an unknown number of columnnames that you want to transpose, then you can use dynamic SQL:

    DECLARE @cols AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX)
    
    select @cols = STUFF((SELECT ',' + QUOTENAME(ColumnName) 
                        from yourtable
                        group by ColumnName, id
                        order by id
                FOR XML PATH(''), TYPE
                ).value('.', 'NVARCHAR(MAX)') 
            ,1,1,'')
    
    set @query = N'SELECT ' + @cols + N' from 
                 (
                    select value, ColumnName
                    from yourtable
                ) x
                pivot 
                (
                    max(value)
                    for ColumnName in (' + @cols + N')
                ) p '
    
    exec sp_executesql @query;
    

    See Demo.

    Using an aggregate function

    If you do not want to use the PIVOT function, then you can use an aggregate function with a CASE expression:

    select
      max(case when columnname = 'FirstName' then value end) Firstname,
      max(case when columnname = 'Amount' then value end) Amount,
      max(case when columnname = 'PostalCode' then value end) PostalCode,
      max(case when columnname = 'LastName' then value end) LastName,
      max(case when columnname = 'AccountNumber' then value end) AccountNumber
    from yourtable
    

    See Demo.

    Using multiple joins

    This could also be completed using multiple joins, but you will need some column to associate each of the rows which you do not have in your sample data. But the basic syntax would be:

    select fn.value as FirstName,
      a.value as Amount,
      pc.value as PostalCode,
      ln.value as LastName,
      an.value as AccountNumber
    from yourtable fn
    left join yourtable a
      on fn.somecol = a.somecol
      and a.columnname = 'Amount'
    left join yourtable pc
      on fn.somecol = pc.somecol
      and pc.columnname = 'PostalCode'
    left join yourtable ln
      on fn.somecol = ln.somecol
      and ln.columnname = 'LastName'
    left join yourtable an
      on fn.somecol = an.somecol
      and an.columnname = 'AccountNumber'
    where fn.columnname = 'Firstname'
    

    Use superscripts in R axis labels

    This is a quick example

    plot(rnorm(30), xlab = expression(paste("4"^"th")))
    

    Merging a lot of data.frames

    Put them into a list and use merge with Reduce

    Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
    #    id v1 v2 v3
    # 1   1  1 NA NA
    # 2  10  4 NA NA
    # 3   2  3  4 NA
    # 4  43  5 NA NA
    # 5  73  2 NA NA
    # 6  23 NA  2  1
    # 7  57 NA  3 NA
    # 8  62 NA  5  2
    # 9   7 NA  1 NA
    # 10 96 NA  6 NA
    

    You can also use this more concise version:

    Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))
    

    How to convert jsonString to JSONObject in Java

    NOTE that GSON with deserializing an interface will result in exception like below.

    "java.lang.RuntimeException: Unable to invoke no-args constructor for interface XXX. Register an InstanceCreator with Gson for this type may fix this problem."
    

    While deserialize; GSON don't know which object has to be intantiated for that interface.

    This is resolved somehow here.

    However FlexJSON has this solution inherently. while serialize time it is adding class name as part of json like below.

    {
        "HTTPStatus": "OK",
        "class": "com.XXX.YYY.HTTPViewResponse",
        "code": null,
        "outputContext": {
            "class": "com.XXX.YYY.ZZZ.OutputSuccessContext",
            "eligible": true
        }
    }
    

    So JSON will be cumber some; but you don't need write InstanceCreator which is required in GSON.

    Disable Chrome strict MIME type checking

    also had same problem once,

    if you are unable to solve the problem you can run the following command on command line
    chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security

    Note: you have to navigate to the installation path of your chrome.
    For example:cd C:\Program Files\Google\Chrome\Application

    A developer session chrome browser will be opened, you can now launch your app on the new chrome browse.
    I hope this should be helpful

    How to "crop" a rectangular image into a square with CSS?

    I actually came across this same problem recently and ended up with a slightly different approach (I wasn't able to use background images). It does require a tiny bit of jQuery though to determine the orientation of the images (I' sure you could use plain JS instead though).

    I wrote a blog post about it if you are interested in more explaination but the code is pretty simple:

    HTML:

    <ul class="cropped-images">
      <li><img src="http://fredparke.com/sites/default/files/cat-portrait.jpg" /></li>
      <li><img src="http://fredparke.com/sites/default/files/cat-landscape.jpg" /></li>
    </ul>
    

    CSS:

    li {
      width: 150px; // Or whatever you want.
      height: 150px; // Or whatever you want.
      overflow: hidden;
      margin: 10px;
      display: inline-block;
      vertical-align: top;
    }
    li img {
      max-width: 100%;
      height: auto;
      width: auto;
    }
    li img.landscape {
      max-width: none;
      max-height: 100%;
    }
    

    jQuery:

    $( document ).ready(function() {
    
        $('.cropped-images img').each(function() {
          if ($(this).width() > $(this).height()) {
            $(this).addClass('landscape');        
          }
        });
    
    });
    

    Setting up maven dependency for SQL Server

    I believe you are looking for the Microsoft SQL Server JDBC driver: http://msdn.microsoft.com/en-us/sqlserver/aa937724

    Does height and width not apply to span?

    Span takes width and height only when we make it block element.

    span {display:block;}
    

    Calling one Activity from another in Android

    First question:

    Use the Intent to call another Activity. In the Manifest, you should add

    <activity android:name="ListViewImage"></activity>
    <activity android:name="com.company.listview.ListViewImage">
    </activity>
    

    And in your current activity,

    btListe = (ImageButton)findViewById(R.id.Button_Liste);
        btListe.setOnClickListener(new OnClickListener()
        {    public void onClick(View v)
            {
                intent = new Intent(main.this, ListViewImage.class);
                startActivity(intent);
                finish();
            }
        });
    

    Second question:

    sendButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                String valueString = editValue.getText().toString();
                long value;
                if (valueString != null) {
                    value = Long.parseLong(valueString);
                }
                else {
                    value = 0;
                }
    
                Bundle sendBundle = new Bundle();
                sendBundle.putLong("value", value);
    
                Intent i = new Intent(Activity1.this, Activity2.class);
                i.putExtras(sendBundle);
                startActivity(i);
    
                finish();
            }
        });
    

    and in Activity2:

     Bundle receiveBundle = this.getIntent().getExtras();
        final long receiveValue = receiveBundle.getLong("value");
        receiveValueEdit.setText(String.valueOf(receiveValue));
        callReceiverButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Intent i = new Intent(Activity2.this, Receiver.class);
                i.putExtra("new value", receiveValue - 10);
            }
        });
    

    Send data from javascript to a mysql database

    The other posters are correct you cannot connect to MySQL directly from javascript. This is because JavaScript is at client side & mysql is server side.

    So your best bet is to use ajax to call a handler as quoted above if you can let us know what language your project is in we can better help you ie php/java/.net

    If you project is using php then the example from Merlyn is a good place to start, I would personally use jquery.ajax() to cut down you code and have a better chance of less cross browser issues.

    http://api.jquery.com/jQuery.ajax/

    How can I add (simple) tracing in C#?

    I followed around five different answers as well as all the blog posts in the previous answers and still had problems. I was trying to add a listener to some existing code that was tracing using the TraceSource.TraceEvent(TraceEventType, Int32, String) method where the TraceSource object was initialised with a string making it a 'named source'.

    For me the issue was not creating a valid combination of source and switch elements to target this source. Here is an example that will log to a file called tracelog.txt. For the following code:

    TraceSource source = new TraceSource("sourceName");
    source.TraceEvent(TraceEventType.Verbose, 1, "Trace message");
    

    I successfully managed to log with the following diagnostics configuration:

    <system.diagnostics>
        <sources>
            <source name="sourceName" switchName="switchName">
                <listeners>
                    <add
                        name="textWriterTraceListener"
                        type="System.Diagnostics.TextWriterTraceListener"
                        initializeData="tracelog.txt" />
                </listeners>
            </source>
        </sources>
    
        <switches>
            <add name="switchName" value="Verbose" />
        </switches>
    </system.diagnostics>
    

    Why should we include ttf, eot, woff, svg,... in a font-face

    Answer in 2019:

    Only use WOFF2, or if you need legacy support, WOFF. Do not use any other format

    (svg and eot are dead formats, ttf and otf are full system fonts, and should not be used for web purposes)

    Original answer from 2012:

    In short, font-face is very old, but only recently has been supported by more than IE.

    • eot is needed for Internet Explorers that are older than IE9 - they invented the spec, but eot was a proprietary solution.

    • ttf and otf are normal old fonts, so some people got annoyed that this meant anyone could download expensive-to-license fonts for free.

    • Time passes, SVG 1.1 adds a "fonts" chapter that explains how to model a font purely using SVG markup, and people start to use it. More time passes and it turns out that they are absolutely terrible compared to just a normal font format, and SVG 2 wisely removes the entire chapter again.

    • Then, woff gets invented by people with quite a bit of domain knowledge, which makes it possible to host fonts in a way that throws away bits that are critically important for system installation, but irrelevant for the web (making people worried about piracy happy) and allows for internal compression to better suit the needs of the web (making users and hosts happy). This becomes the preferred format.

    • 2019 edit A few years later, woff2 gets drafted and accepted, which improves the compression, leading to even smaller files, along with the ability to load a single font "in parts" so that a font that supports 20 scripts can be stored as "chunks" on disk instead, with browsers automatically able to load the font "in parts" as needed, rather than needing to transfer the entire font up front, further improving the typesetting experience.

    If you don't want to support IE 8 and lower, and iOS 4 and lower, and android 4.3 or earlier, then you can just use WOFF (and WOFF2, a more highly compressed WOFF, for the newest browsers that support it.)

    @font-face {
      font-family: 'MyWebFont';
      src:  url('myfont.woff2') format('woff2'),
            url('myfont.woff') format('woff');
    }
    

    Support for woff can be checked at http://caniuse.com/woff
    Support for woff2 can be checked at http://caniuse.com/woff2

    Stopping a JavaScript function when a certain condition is met

    The return statement exits a function from anywhere within the function:

    function something(x)
    {
        if (x >= 10)
            // this leaves the function if x is at least 10.
            return;
    
        // this message displays only if x is less than 10.
        alert ("x is less than 10!");
    }
    

    IE8 crashes when loading website - res://ieframe.dll/acr_error.htm

    I had this happening with a Drupal theme. None of the many suggestions on various threads (change IE security settings or some other advanced settings, update Java, update Flash, fiddle with registry, remove certain Windows updates, check plugins, scan for malware, completely reinstall IE8) worked for me.

    In this case, it turned out to be a problem with setting a background-image on a body element - changing body to an html element fixed things. It is apparently related to loading respond.js - try putting that at the bottom.

    CSS animation delay in repeating

    Heres a little snippet that shows the same thing for 75% of the time, then it slides. This repeat schema emulates delay nicely:

    @-webkit-keyframes slide    {
    0%   {background-position: 0 0;}
    25%  {background-position: 0 0;}
    50%  {background-position: 0 0;}
    75%  {background-position: 0 0;}
    100% {background-position: 13em 0;}
    }
    
    @-moz-keyframes slide       {
    0%   {background-position: 0 0;}
    25%  {background-position: 0 0;}
    50%  {background-position: 0 0;}
    75%  {background-position: 0 0;}
    100% {background-position: 13em 0;}
    }
    
    @keyframes slide            {
    0%   {background-position: 0 0;}
    25%  {background-position: 0 0;}
    50%  {background-position: 0 0;}
    75%  {background-position: 0 0;}
    100% {background-position: 13em 0;}
    }
    

    Use Invoke-WebRequest with a username and password for basic authentication on the GitHub API

    I had to do this to get it to work:

    $pair = "$($user):$($pass)"
    $encodedCredentials = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($Pair))
    $headers = @{ Authorization = "Basic $encodedCredentials" }
    Invoke-WebRequest -Uri $url -Method Get -Headers $headers -OutFile Config.html
    

    How to set timeout for a line of c# code

    You can use the IAsyncResult and Action class/interface to achieve this.

    public void TimeoutExample()
    {
        IAsyncResult result;
        Action action = () =>
        {
            // Your code here
        };
    
        result = action.BeginInvoke(null, null);
    
        if (result.AsyncWaitHandle.WaitOne(10000))
             Console.WriteLine("Method successful.");
        else
             Console.WriteLine("Method timed out.");
    }
    

    Fill username and password using selenium in python

    In some cases when the element is not interactable, sendKeys() doesn't work and you're likely to encounter an ElementNotInteractableException.

    In such cases, you can opt to execute javascript that sets the values and then can post back.

    Example:

    url = 'https://www.your_url.com/'
    
    driver = Chrome(executable_path="./chromedriver")
    driver.get(url)
    
    username = 'your_username'
    password = 'your_password'
    
    #Setting the value of email input field
    driver.execute_script(f'var element = document.getElementById("email"); element.value = "{username}";')
    
    #Setting the value of password input field
    driver.execute_script(f'var element = document.getElementById("password"); element.value = "{password}";')
    
    #Submitting the form or click the login button also
    driver.execute_script(f'document.getElementsByClassName("login_form")[0].submit();')
    
    print(driver.page_source)
    
    

    Reference:

    https://www.quora.com/How-do-I-resolve-the-ElementNotInteractableException-in-Selenium-WebDriver

    How to make a round button?

    You can use google's FloatingActionButton

    XMl:

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@android:drawable/ic_dialog_email" />
    

    Java:

      @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        FloatingActionButton bold = (FloatingActionButton) findViewById(R.id.fab);
        bold.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            // Do Stuff
            }
        });
    }
    

    Gradle:

        compile 'com.android.support:design:23.4.0'
    

    How do I validate a date in this format (yyyy-mm-dd) using jquery?

    Since jQuery is tagged, here's an easy / user-friendly way to validate a field that must be a date (you will need the jQuery validation plugin):

    html

    <form id="frm">
    <input id="date_creation" name="date_creation" type="text" />
    </form>
    

    jQuery

    $('#frm').validate({
      rules: {
        date_creation: {
          required: true,
          date: true
        }
      }
    });
    

    DEMO + Example


    UPDATE: After some digging, I found no evidence of a ready-to-go parameter to set a specific date format.

    However, you can plug in the regex of your choice in a custom rule :)

    $.validator.addMethod(
        "myDateFormat",
        function(value, element) {
            // yyyy-mm-dd
            var re = /^\d{4}-\d{1,2}-\d{1,2}$/;
    
            // valid if optional and empty OR if it passes the regex test
            return (this.optional(element) && value=="") || re.test(value);
        }
    );
    
    $('#frm').validate({
      rules: {
        date_creation: {
          // not optional
          required: true,
          // valid date
          date: true
        }
      }
    });
    

    This new rule would imply an update on your markup:

    <input id="date_creation" name="date_creation" type="text" class="myDateFormat" />
    

    Request string without GET arguments

    Solution:

    echoparse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);

    How can I get a count of the total number of digits in a number?

    It depends what exactly you want to do with the digits. You can iterate through the digits starting from the last to the first one like this:

    int tmp = number;
    int lastDigit = 0;
    do
    {
        lastDigit = tmp / 10;
        doSomethingWithDigit(lastDigit);
        tmp %= 10;
    } while (tmp != 0);
    

    What version of javac built my jar?

    There is no need to unpack the JAR (if one of the class names is known or is looked up e.g. using 7zip), so on Windows the following would be sufficient:

    javap -cp log4j-core-2.5.jar -verbose org.apache.logging.log4j.core.Logger | findstr major
    

    What size should apple-touch-icon.png be for iPad and iPhone?

    The icon on Apple's site is 152x152 pixels.
    http://www.apple.com/apple-touch-icon.png

    Hope that answers your question.

    How can I get the last day of the month in C#?

    Something like:

    DateTime today = DateTime.Today;
    DateTime endOfMonth = new DateTime(today.Year, today.Month, 1).AddMonths(1).AddDays(-1);
    

    Which is to say that you get the first day of next month, then subtract a day. The framework code will handle month length, leap years and such things.

    Difference between using bean id and name in Spring configuration file

    From the Spring reference, 3.2.3.1 Naming Beans:

    Every bean has one or more ids (also called identifiers, or names; these terms refer to the same thing). These ids must be unique within the container the bean is hosted in. A bean will almost always have only one id, but if a bean has more than one id, the extra ones can essentially be considered aliases.

    When using XML-based configuration metadata, you use the 'id' or 'name' attributes to specify the bean identifier(s). The 'id' attribute allows you to specify exactly one id, and as it is a real XML element ID attribute, the XML parser is able to do some extra validation when other elements reference the id; as such, it is the preferred way to specify a bean id. However, the XML specification does limit the characters which are legal in XML IDs. This is usually not a constraint, but if you have a need to use one of these special XML characters, or want to introduce other aliases to the bean, you may also or instead specify one or more bean ids, separated by a comma (,), semicolon (;), or whitespace in the 'name' attribute.

    So basically the id attribute conforms to the XML id attribute standards whereas name is a little more flexible. Generally speaking, I use name pretty much exclusively. It just seems more "Spring-y".

    Cast object to T

    try

    if (readData is T)
        return (T)(object)readData;
    

    Capture Signature using HTML5 and iPad

    Here is a quickly hacked up version of this using SVG I just did. Works well for me on my iPhone. Also works in a desktop browser using normal mouse events.

    Get all parameters from JSP page

    localhost:8080/esccapp/tst/submit.jsp?key=datr&key2=datr2&key3=datr3
    
        <%@page import="java.util.Enumeration"%>
    
        <%
        Enumeration in = request.getParameterNames();
        while(in.hasMoreElements()) {
         String paramName = in.nextElement().toString();
         out.println(paramName + " = " + request.getParameter(paramName)+"<br>");
        }
        %>
    
        key = datr
        key2 = datr2
        key3 = datr3
    

    How do you fix the "element not interactable" exception?

    Found a workaround years later after encountering the same problem again - unable to click element even though it SHOULD be clickable. The solution is to catch ElementNotInteractable exception and attempt to execute a script to click the element.

    Example in Typescript

    async clickElement(element: WebElement) {
        try {
            return await element.click();
        } catch (error) {
            if (error.name == 'ElementNotInteractableError') {
                return await this.driver.executeScript((element: WebElement) => {
                    element.click();
                }, element);
            }
        }
    }
    

    Difference between Relative path and absolute path in javascript

    I think this example will help you in understanding this more simply.

    Path differences in Windows

    Windows absolute path C:\Windows\calc.exe

    Windows non absolute path (relative path) calc.exe

    In the above example, the absolute path contains the full path to the file and not just the file as seen in the non absolute path. In this example, if you were in a directory that did not contain "calc.exe" you would get an error message. However, when using an absolute path you can be in any directory and the computer would know where to open the "calc.exe" file.

    Path differences in Linux

    Linux absolute path /home/users/c/computerhope/public_html/cgi-bin

    Linux non absolute path (relative path) /public_html/cgi-bin

    In these example, the absolute path contains the full path to the cgi-bin directory on that computer. How to find the absolute path of a file in Linux Since most users do not want to see the full path as their prompt, by default the prompt is relative to their personal directory as shown above. To find the full absolute path of the current directory use the pwd command.

    It is a best practice to use relative file paths (if possible).

    When using relative file paths, your web pages will not be bound to your current base URL. All links will work on your own computer (localhost) as well as on your current public domain and your future public domains.

    How do I update a GitHub forked repository?

    I update my forked repos with this one line:

    git pull https://github.com/forkuser/forkedrepo.git branch
    

    Use this if you dont want to add another remote endpoint to your project, as other solutions posted here.

    Convert PEM to PPK file format

    PuTTYgen for Ubuntu/Linux and PEM to PPK

    sudo apt install putty-tools
    puttygen -t rsa -b 2048 -C "user@host" -o keyfile.ppk
    

    How to make a vertical SeekBar in Android?

    Getting started

    Add these lines to build.gradle.

    dependencies {
        compile 'com.h6ah4i.android.widget.verticalseekbar:verticalseekbar:0.7.2'
    }
    

    Usage

    Java code

    public class TestVerticalSeekbar extends AppCompatActivity {
        private SeekBar volumeControl = null;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_test_vertical_seekbar);
    
            volumeControl = (SeekBar) findViewById(R.id.mySeekBar);
    
            volumeControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                int progressChanged = 0;
    
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    progressChanged = progress;
                }
    
                public void onStartTrackingTouch(SeekBar seekBar) {
                    // TODO Auto-generated method stub
                }
    
                public void onStopTrackingTouch(SeekBar seekBar) {
                    Toast.makeText(getApplicationContext(), "seek bar progress:" + progressChanged,
                            Toast.LENGTH_SHORT).show();
                }
            });
        }
    
    }
    

    Layout XML

    <!-- This library requires pair of the VerticalSeekBar and VerticalSeekBarWrapper classes -->
    <com.h6ah4i.android.widget.verticalseekbar.VerticalSeekBarWrapper
        android:layout_width="wrap_content"
        android:layout_height="150dp">
        <com.h6ah4i.android.widget.verticalseekbar.VerticalSeekBar
            android:id="@+id/mySeekBar"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:max="100"
            android:progress="0"
            android:splitTrack="false"
            app:seekBarRotation="CW90" /> <!-- Rotation: CW90 or CW270 -->
    </com.h6ah4i.android.widget.verticalseekbar.VerticalSeekBarWrapper>
    

    NOTE: android:splitTrack="false" is required for Android N+.

    Most efficient conversion of ResultSet to JSON?

    If anyone plan to use this implementation, You might wanna check this out and this

    This is my version of that convertion code:

    public class ResultSetConverter {
    public static JSONArray convert(ResultSet rs) throws SQLException,
            JSONException {
        JSONArray json = new JSONArray();
        ResultSetMetaData rsmd = rs.getMetaData();
        int numColumns = rsmd.getColumnCount();
        while (rs.next()) {
    
            JSONObject obj = new JSONObject();
    
            for (int i = 1; i < numColumns + 1; i++) {
                String column_name = rsmd.getColumnName(i);
    
                if (rsmd.getColumnType(i) == java.sql.Types.ARRAY) {
                    obj.put(column_name, rs.getArray(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.BIGINT) {
                    obj.put(column_name, rs.getLong(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.REAL) {
                    obj.put(column_name, rs.getFloat(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.BOOLEAN) {
                    obj.put(column_name, rs.getBoolean(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.BLOB) {
                    obj.put(column_name, rs.getBlob(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.DOUBLE) {
                    obj.put(column_name, rs.getDouble(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.FLOAT) {
                    obj.put(column_name, rs.getDouble(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.INTEGER) {
                    obj.put(column_name, rs.getInt(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.NVARCHAR) {
                    obj.put(column_name, rs.getNString(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.VARCHAR) {
                    obj.put(column_name, rs.getString(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.CHAR) {
                    obj.put(column_name, rs.getString(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.NCHAR) {
                    obj.put(column_name, rs.getNString(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.LONGNVARCHAR) {
                    obj.put(column_name, rs.getNString(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.LONGVARCHAR) {
                    obj.put(column_name, rs.getString(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.TINYINT) {
                    obj.put(column_name, rs.getByte(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.SMALLINT) {
                    obj.put(column_name, rs.getShort(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.DATE) {
                    obj.put(column_name, rs.getDate(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.TIME) {
                    obj.put(column_name, rs.getTime(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.TIMESTAMP) {
                    obj.put(column_name, rs.getTimestamp(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.BINARY) {
                    obj.put(column_name, rs.getBytes(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.VARBINARY) {
                    obj.put(column_name, rs.getBytes(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.LONGVARBINARY) {
                    obj.put(column_name, rs.getBinaryStream(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.BIT) {
                    obj.put(column_name, rs.getBoolean(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.CLOB) {
                    obj.put(column_name, rs.getClob(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.NUMERIC) {
                    obj.put(column_name, rs.getBigDecimal(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.DECIMAL) {
                    obj.put(column_name, rs.getBigDecimal(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.DATALINK) {
                    obj.put(column_name, rs.getURL(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.REF) {
                    obj.put(column_name, rs.getRef(column_name));
                } else if (rsmd.getColumnType(i) == java.sql.Types.STRUCT) {
                    obj.put(column_name, rs.getObject(column_name)); // must be a custom mapping consists of a class that implements the interface SQLData and an entry in a java.util.Map object.
                } else if (rsmd.getColumnType(i) == java.sql.Types.DISTINCT) {
                    obj.put(column_name, rs.getObject(column_name)); // must be a custom mapping consists of a class that implements the interface SQLData and an entry in a java.util.Map object.
                } else if (rsmd.getColumnType(i) == java.sql.Types.JAVA_OBJECT) {
                    obj.put(column_name, rs.getObject(column_name));
                } else {
                    obj.put(column_name, rs.getString(i));
                }
            }
    
            json.put(obj);
        }
    
        return json;
    }
    }
    

    MySQL Insert query doesn't work with WHERE clause

    After WHERE clause you put a condition, and it is used for either fetching data or for updating a row. When you are inserting data, it is assumed that the row does not exist.

    So, the question is, is there any row whose id is 1? if so, use MySQL UPDATE, else use MySQL INSERT.

    Valid to use <a> (anchor tag) without href attribute?

    Yes, it is valid to use the anchor tag without a href attribute.

    If the a element has no href attribute, then the element represents a placeholder for where a link might otherwise have been placed, if it had been relevant, consisting of just the element's contents.

    Yes, you can use class and other attributes, but you can not use target, download, rel, hreflang, and type.

    The target, download, rel, hreflang, and type attributes must be omitted if the href attribute is not present.

    As for the "Should I?" part, see the first citation: "where a link might otherwise have been placed if it had been relevant". So I would ask "If I had no JavaScript, would I use this tag as a link?". If the answer is yes, then yes, you should use <a> without href. If no, then I would still use it, because productivity is more important for me than edge case semantics, but this is just my personal opinion.

    Additionally, you should watch out for different behaviour and styling (e.g. no underline, no pointer cursor, not a :link).

    Source: W3C HTML5 Recommendation

    Writing outputs to log file and console

    I have found a way to get the desired output. Though it may be somewhat unorthodox way. Anyways here it goes. In the redir.env file I have following code:

    #####redir.env#####    
    export LOG_FILE=log.txt
    
          exec 2>>${LOG_FILE}
    
        function log {
         echo "$1">>${LOG_FILE}
        }
    
        function message {
         echo "$1"
         echo "$1">>${LOG_FILE}
        }
    

    Then in the actual script I have the following codes:

    #!/bin/sh 
    . redir.env
    echo "Echoed to console only"
    log "Written to log file only"
    message "To console and log"
    echo "This is stderr. Written to log file only" 1>&2
    

    Here echo outputs only to console, log outputs to only log file and message outputs to both the log file and console.

    After executing the above script file I have following outputs:

    In console

    In console
    Echoed to console only
    To console and log

    For the Log file

    In Log File Written to log file only
    This is stderr. Written to log file only
    To console and log

    Hope this help.

    Ruby: How to post a file via HTTP as multipart/form-data?

    curb looks like a great solution, but in case it doesn't meet your needs, you can do it with Net::HTTP. A multipart form post is just a carefully-formatted string with some extra headers. It seems like every Ruby programmer who needs to do multipart posts ends up writing their own little library for it, which makes me wonder why this functionality isn't built-in. Maybe it is... Anyway, for your reading pleasure, I'll go ahead and give my solution here. This code is based off of examples I found on a couple of blogs, but I regret that I can't find the links anymore. So I guess I just have to take all the credit for myself...

    The module I wrote for this contains one public class, for generating the form data and headers out of a hash of String and File objects. So for example, if you wanted to post a form with a string parameter named "title" and a file parameter named "document", you would do the following:

    #prepare the query
    data, headers = Multipart::Post.prepare_query("title" => my_string, "document" => my_file)
    

    Then you just do a normal POST with Net::HTTP:

    http = Net::HTTP.new(upload_uri.host, upload_uri.port)
    res = http.start {|con| con.post(upload_uri.path, data, headers) }
    

    Or however else you want to do the POST. The point is that Multipart returns the data and headers that you need to send. And that's it! Simple, right? Here's the code for the Multipart module (you need the mime-types gem):

    # Takes a hash of string and file parameters and returns a string of text
    # formatted to be sent as a multipart form post.
    #
    # Author:: Cody Brimhall <mailto:[email protected]>
    # Created:: 22 Feb 2008
    # License:: Distributed under the terms of the WTFPL (http://www.wtfpl.net/txt/copying/)
    
    require 'rubygems'
    require 'mime/types'
    require 'cgi'
    
    
    module Multipart
      VERSION = "1.0.0"
    
      # Formats a given hash as a multipart form post
      # If a hash value responds to :string or :read messages, then it is
      # interpreted as a file and processed accordingly; otherwise, it is assumed
      # to be a string
      class Post
        # We have to pretend we're a web browser...
        USERAGENT = "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/523.10.6 (KHTML, like Gecko) Version/3.0.4 Safari/523.10.6"
        BOUNDARY = "0123456789ABLEWASIEREISAWELBA9876543210"
        CONTENT_TYPE = "multipart/form-data; boundary=#{ BOUNDARY }"
        HEADER = { "Content-Type" => CONTENT_TYPE, "User-Agent" => USERAGENT }
    
        def self.prepare_query(params)
          fp = []
    
          params.each do |k, v|
            # Are we trying to make a file parameter?
            if v.respond_to?(:path) and v.respond_to?(:read) then
              fp.push(FileParam.new(k, v.path, v.read))
            # We must be trying to make a regular parameter
            else
              fp.push(StringParam.new(k, v))
            end
          end
    
          # Assemble the request body using the special multipart format
          query = fp.collect {|p| "--" + BOUNDARY + "\r\n" + p.to_multipart }.join("") + "--" + BOUNDARY + "--"
          return query, HEADER
        end
      end
    
      private
    
      # Formats a basic string key/value pair for inclusion with a multipart post
      class StringParam
        attr_accessor :k, :v
    
        def initialize(k, v)
          @k = k
          @v = v
        end
    
        def to_multipart
          return "Content-Disposition: form-data; name=\"#{CGI::escape(k)}\"\r\n\r\n#{v}\r\n"
        end
      end
    
      # Formats the contents of a file or string for inclusion with a multipart
      # form post
      class FileParam
        attr_accessor :k, :filename, :content
    
        def initialize(k, filename, content)
          @k = k
          @filename = filename
          @content = content
        end
    
        def to_multipart
          # If we can tell the possible mime-type from the filename, use the
          # first in the list; otherwise, use "application/octet-stream"
          mime_type = MIME::Types.type_for(filename)[0] || MIME::Types["application/octet-stream"][0]
          return "Content-Disposition: form-data; name=\"#{CGI::escape(k)}\"; filename=\"#{ filename }\"\r\n" +
                 "Content-Type: #{ mime_type.simplified }\r\n\r\n#{ content }\r\n"
        end
      end
    end
    

    How to open Atom editor from command line in OS X?

    Another simple solution is to add /usr/local/bin to your PATH. I had the same issue, I installed shell commands (see shaheenery's response) the symlinks already existed and pointing to the correct destination (see thomax's response), however I would still get 'not found'. I'm using Korn Shell btw.

    Here's what I did:

    1. Open your ~/.profile using your choice of editor (in my case $ emacs ~/.kshrc)
    2. Add this line: export PATH="/usr/local/bin:${PATH}"
    3. Save and exit
    4. Restart terminal or source ~/.profile
    5. Test $ atom -h

    Removing element from array in component state

    I believe referencing this.state inside of setState() is discouraged (State Updates May Be Asynchronous).

    The docs recommend using setState() with a callback function so that prevState is passed in at runtime when the update occurs. So this is how it would look:

    Using Array.prototype.filter without ES6

    removeItem : function(index) {
      this.setState(function(prevState){
        return { data : prevState.data.filter(function(val, i) {
          return i !== index;
        })};
      });
    }
    

    Using Array.prototype.filter with ES6 Arrow Functions

    removeItem(index) {
      this.setState((prevState) => ({
        data: prevState.data.filter((_, i) => i !== index)
      }));
    }
    

    Using immutability-helper

    import update from 'immutability-helper'
    ...
    removeItem(index) {
      this.setState((prevState) => ({
        data: update(prevState.data, {$splice: [[index, 1]]})
      }))
    }
    

    Using Spread

    function removeItem(index) {
      this.setState((prevState) => ({
        data: [...prevState.data.slice(0,index), ...prevState.data.slice(index+1)]
      }))
    }
    

    Note that in each instance, regardless of the technique used, this.setState() is passed a callback, not an object reference to the old this.state;

    ExecutorService that interrupts tasks after a timeout

    How about using the ExecutorService.shutDownNow() method as described in http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html? It seems to be the simplest solution.

    A monad is just a monoid in the category of endofunctors, what's the problem?

    That particular phrasing is by James Iry, from his highly entertaining Brief, Incomplete and Mostly Wrong History of Programming Languages, in which he fictionally attributes it to Philip Wadler.

    The original quote is from Saunders Mac Lane in Categories for the Working Mathematician, one of the foundational texts of Category Theory. Here it is in context, which is probably the best place to learn exactly what it means.

    But, I'll take a stab. The original sentence is this:

    All told, a monad in X is just a monoid in the category of endofunctors of X, with product × replaced by composition of endofunctors and unit set by the identity endofunctor.

    X here is a category. Endofunctors are functors from a category to itself (which is usually all Functors as far as functional programmers are concerned, since they're mostly dealing with just one category; the category of types - but I digress). But you could imagine another category which is the category of "endofunctors on X". This is a category in which the objects are endofunctors and the morphisms are natural transformations.

    And of those endofunctors, some of them might be monads. Which ones are monads? Exactly the ones which are monoidal in a particular sense. Instead of spelling out the exact mapping from monads to monoids (since Mac Lane does that far better than I could hope to), I'll just put their respective definitions side by side and let you compare:

    A monoid is...

    • A set, S
    • An operation, • : S × S ? S
    • An element of S, e : 1 ? S

    ...satisfying these laws:

    • (a • b) • c = a • (b • c), for all a, b and c in S
    • e • a = a • e = a, for all a in S

    A monad is...

    • An endofunctor, T : X ? X (in Haskell, a type constructor of kind * -> * with a Functor instance)
    • A natural transformation, µ : T × T ? T, where × means functor composition (µ is known as join in Haskell)
    • A natural transformation, ? : I ? T, where I is the identity endofunctor on X (? is known as return in Haskell)

    ...satisfying these laws:

    • µ ° Tµ = µ ° µT
    • µ ° T? = µ ° ?T = 1 (the identity natural transformation)

    With a bit of squinting you might be able to see that both of these definitions are instances of the same abstract concept.

    Cmake doesn't find Boost

    You can also specify the version of Boost that you would like CMake to use by passing -DBOOST_INCLUDEDIR or -DBOOST_ROOT pointing to the location of correct version boost headers

    Example:

    cmake -DBOOST_ROOT=/opt/latestboost

    This will also be useful when multiple boost versions are on the same system.

    Python mysqldb: Library not loaded: libmysqlclient.18.dylib

    My preferred method is to actually fix the library rather than playing with environment variables that may or may not actually be in scope depending on how the application is run. This is actually a fairly simple process.

    First, look at the error output to see where the offending python module is located:

    ImportError: dlopen(/Library/Python/2.7/site-packages/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib Referenced from: /Library/Python/2.7/site-packages/_mysql.so Reason: image not found

    Okay, so the offending file is /Library/Python/2.7/site-packages/_mysql.so

    Next, figure out where _mysql.so thinks it should find libmysqlclient.18.dylib:

    % otool -L /Library/Python/2.7/site-packages/_mysql.so
    /Library/Python/2.7/site-packages/_mysql.so:
        libmysqlclient.18.dylib (compatibility version 18.0.0, current version 18.0.0)
        /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 169.3.0)
    

    So, it's looking for libmysqlclient.18.dylib with no path information, let's fix that:

    % sudo install_name_tool -change libmysqlclient.18.dylib /usr/local/mysql/lib/libmysqlclient.18.dylib /Library/Python/2.7/site-packages/_mysql.so
    

    Now _mysql.so knows the full path to the library and everything works, regardless of environment variables.

    % otool -L /Library/Python/2.7/site-packages/_mysql.so                                                                                           
    /Library/Python/2.7/site-packages/_mysql.so:
        /usr/local/mysql/lib/libmysqlclient.18.dylib (compatibility version 18.0.0, current version 18.0.0)
        /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 169.3.0)
    

    XML to CSV Using XSLT

    This xsl:stylesheet can use a specified list of column headers and will ensure that the rows will be ordered correctly.

    <?xml version="1.0"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:csv="csv:csv">
        <xsl:output method="text" encoding="utf-8" />
        <xsl:strip-space elements="*" />
    
        <xsl:variable name="delimiter" select="','" />
    
        <csv:columns>
            <column>name</column>
            <column>sublease</column>
            <column>addressBookID</column>
            <column>boundAmount</column>
            <column>rentalAmount</column>
            <column>rentalPeriod</column>
            <column>rentalBillingCycle</column>
            <column>tenureIncome</column>
            <column>tenureBalance</column>
            <column>totalIncome</column>
            <column>balance</column>
            <column>available</column>
        </csv:columns>
    
        <xsl:template match="/property-manager/properties">
            <!-- Output the CSV header -->
            <xsl:for-each select="document('')/*/csv:columns/*">
                    <xsl:value-of select="."/>
                    <xsl:if test="position() != last()">
                        <xsl:value-of select="$delimiter"/>
                    </xsl:if>
            </xsl:for-each>
            <xsl:text>&#xa;</xsl:text>
    
            <!-- Output rows for each matched property -->
            <xsl:apply-templates select="property" />
        </xsl:template>
    
        <xsl:template match="property">
            <xsl:variable name="property" select="." />
    
            <!-- Loop through the columns in order -->
            <xsl:for-each select="document('')/*/csv:columns/*">
                <!-- Extract the column name and value -->
                <xsl:variable name="column" select="." />
                <xsl:variable name="value" select="$property/*[name() = $column]" />
    
                <!-- Quote the value if required -->
                <xsl:choose>
                    <xsl:when test="contains($value, '&quot;')">
                        <xsl:variable name="x" select="replace($value, '&quot;',  '&quot;&quot;')"/>
                        <xsl:value-of select="concat('&quot;', $x, '&quot;')"/>
                    </xsl:when>
                    <xsl:when test="contains($value, $delimiter)">
                        <xsl:value-of select="concat('&quot;', $value, '&quot;')"/>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:value-of select="$value"/>
                    </xsl:otherwise>
                </xsl:choose>
    
                <!-- Add the delimiter unless we are the last expression -->
                <xsl:if test="position() != last()">
                    <xsl:value-of select="$delimiter"/>
                </xsl:if>
            </xsl:for-each>
    
            <!-- Add a newline at the end of the record -->
            <xsl:text>&#xa;</xsl:text>
        </xsl:template>
    
    </xsl:stylesheet>
    

    How to check if a variable is null or empty string or all whitespace in JavaScript?

    isEmptyOrSpaces(str){
        return str === null || str.trim().length>0;
    }
    

    Update select2 data without rebuilding the control

    For Select2 4.X

    var instance = $('#select2Container').data('select2');
    var searchVal = instance.dropdown.$search.val();
    instance.trigger('query', {term:searchVal});
    

    How to get the selected date value while using Bootstrap Datepicker?

    Bootstrap datepicker (the first result from bootstrap datepickcer search) has a method to get the selected date.
    https://bootstrap-datepicker.readthedocs.io/en/latest/methods.html#getdate

    getDate: Returns a localized date object representing the internal date object of the first datepicker in the selection. For multidate pickers, returns the latest date selected.

    $('.datepicker').datepicker("getDate")
    

    or

    $('.datepicker').datepicker("getDate").valueOf() 
    

    How to check if user input is not an int value

    Try this one:
    
        for (;;) {
            if (!sc.hasNextInt()) {
                System.out.println(" enter only integers!: ");
                sc.next(); // discard
                continue;
            }
            choose = sc.nextInt();
            if (choose >= 0) {
                System.out.print("no problem with input");
    
            } else {
                System.out.print("invalid inputs");
    
            }
        break;
      }
    

    how to convert a string to an array in php

    You can achieve this even without using explode and implode function. Here is the example:

    Input:

    This is my world

    Code:

    $part1 = "This is my world"; 
    $part2 = str_word_count($part1, 1);
    

    Output:

    Array( [0] => 'This', [1] => 'is', [2] => 'my', [3] => 'world');

    How to select a directory and store the location using tkinter in Python

    This code may be helpful for you.

    from tkinter import filedialog
    from tkinter import *
    root = Tk()
    root.withdraw()
    folder_selected = filedialog.askdirectory()
    

    Regular expression matching a multiline block of text

    Try this:

    re.compile(r"^(.+)\n((?:\n.+)+)", re.MULTILINE)
    

    I think your biggest problem is that you're expecting the ^ and $ anchors to match linefeeds, but they don't. In multiline mode, ^ matches the position immediately following a newline and $ matches the position immediately preceding a newline.

    Be aware, too, that a newline can consist of a linefeed (\n), a carriage-return (\r), or a carriage-return+linefeed (\r\n). If you aren't certain that your target text uses only linefeeds, you should use this more inclusive version of the regex:

    re.compile(r"^(.+)(?:\n|\r\n?)((?:(?:\n|\r\n?).+)+)", re.MULTILINE)
    

    BTW, you don't want to use the DOTALL modifier here; you're relying on the fact that the dot matches everything except newlines.

    How to include bootstrap css and js in reactjs app?

    you can install it dirctly via

    $ npm install --save react react-dom
    $ npm install --save react-bootstrap
    

    then import what you really need from the bootstrap like :

    import Button from 'react-bootstrap/lib/Button';
    

    // or

    import  Button  from 'react-bootstrap';
    

    and also you can install :

    npm install --save reactstrap@next react react-dom
    

    check this out click here .

    and for the CSS you can read this link also carfuly

    read here

    Twitter Bootstrap 3: How to center a block

    center-block can be found in bootstrap 3.0 in utilities.less on line 12 and mixins.less on line 39

    What does java:comp/env/ do?

    Quoting https://web.archive.org/web/20140227201242/http://v1.dione.zcu.cz/java/docs/jndi-1.2/tutorial/beyond/misc/policy.html

    At the root context of the namespace is a binding with the name "comp", which is bound to a subtree reserved for component-related bindings. The name "comp" is short for component. There are no other bindings at the root context. However, the root context is reserved for the future expansion of the policy, specifically for naming resources that are tied not to the component itself but to other types of entities such as users or departments. For example, future policies might allow you to name users and organizations/departments by using names such as "java:user/alice" and "java:org/engineering".

    In the "comp" context, there are two bindings: "env" and "UserTransaction". The name "env" is bound to a subtree that is reserved for the component's environment-related bindings, as defined by its deployment descriptor. "env" is short for environment. The J2EE recommends (but does not require) the following structure for the "env" namespace.

    So the binding you did from spring or, for example, from a tomcat context descriptor go by default under java:comp/env/

    For example, if your configuration is:

    <bean id="someId" class="org.springframework.jndi.JndiObjectFactoryBean">
      <property name="jndiName" value="foo"/>
    </bean>
    

    Then you can access it directly using:

    Context ctx = new InitialContext();
    DataSource ds = (DataSource)ctx.lookup("java:comp/env/foo");
    

    or you could make an intermediate step so you don't have to specify "java:comp/env" for every resource you retrieve:

    Context ctx = new InitialContext();
    Context envCtx = (Context)ctx.lookup("java:comp/env");
    DataSource ds = (DataSource)envCtx.lookup("foo");
    

    moving changed files to another branch for check-in

    If you haven't already committed your changes, just use git checkout to move to the new branch and then commit them normally - changes to files are not tied to a particular branch until you commit them.

    If you have already committed your changes:

    1. Type git log and remember the SHA of the commit you want to move.
    2. Check out the branch you want to move the commit to.
    3. Type git cherry-pick SHA substituting the SHA from above.
    4. Switch back to your original branch.
    5. Use git reset HEAD~1 to reset back before your wrong-branch commit.

    cherry-pick takes a given commit and applies it to the currently checked-out head, thus allowing you to copy the commit over to a new branch.

    Passing argument to alias in bash

    to use parameters in aliases, i use this method:

    alias myalias='function __myalias() { echo "Hello $*"; unset -f __myalias; }; __myalias'
    

    its a self-destructive function wrapped in an alias, so it pretty much is the best of both worlds, and doesnt take up an extra line(s) in your definitions... which i hate, oh yeah and if you need that return value, you'll have to store it before calling unset, and then return the value using the "return" keyword in that self destructive function there:

    alias myalias='function __myalias() { echo "Hello $*"; myresult=$?; unset -f __myalias; return $myresult; }; __myalias'
    

    so..

    you could, if you need to have that variable in there

    alias mongodb='function __mongodb() { ./path/to/mongodb/$1; unset -f __mongodb; }; __mongodb'
    

    of course...

    alias mongodb='./path/to/mongodb/'
    

    would actually do the same thing without the need for parameters, but like i said, if you wanted or needed them for some reason (for example, you needed $2 instead of $1), you would need to use a wrapper like that. If it is bigger than one line you might consider just writing a function outright since it would become more of an eyesore as it grew larger. Functions are great since you get all the perks that functions give (see completion, traps, bind, etc for the goodies that functions can provide, in the bash manpage).

    I hope that helps you out :)

    How to test an Oracle Stored Procedure with RefCursor return type?

    Something like

    create or replace procedure my_proc( p_rc OUT SYS_REFCURSOR )
    as
    begin
      open p_rc
       for select 1 col1
             from dual;
    end;
    /
    
    variable rc refcursor;
    exec my_proc( :rc );
    print rc;
    

    will work in SQL*Plus or SQL Developer. I don't have any experience with Embarcardero Rapid XE2 so I have no idea whether it supports SQL*Plus commands like this.

    How to redirect the output of the time command to a file in Linux?

    If you want just the time in a shell variable then this works:

    var=`{ time <command> ; } 2>&1 1>/dev/null`
    

    typeof !== "undefined" vs. != null

    _x000D_
    _x000D_
    function greet(name, greeting) {_x000D_
      name = (typeof name !== 'undefined') ?  name : 'Student';_x000D_
      greeting = (typeof greeting !== 'undefined') ?  greeting : 'Welcome';_x000D_
    _x000D_
      console.log(greeting,name);_x000D_
    }_x000D_
    _x000D_
    greet(); // Welcome Student!_x000D_
    greet('James'); // Welcome James!_x000D_
    greet('Richard', 'Howdy'); // Howdy Richard!_x000D_
    _x000D_
    //ES6 provides new ways of introducing default function parameters this way:_x000D_
    _x000D_
    function greet2(name = 'Student', greeting = 'Welcome') {_x000D_
    //  return '${greeting} ${name}!';_x000D_
    console.log(greeting,name);_x000D_
    }_x000D_
    _x000D_
    greet2(); // Welcome Student!_x000D_
    greet2('James'); // Welcome James!_x000D_
    greet2('Richard', 'Howdy'); // Howdy Richard!
    _x000D_
    _x000D_
    _x000D_

    What is the best way to update the entity in JPA

    Using executeUpdate() on the Query API is faster because it bypasses the persistent context .However , by-passing persistent context would cause the state of instance in the memory and the actual values of that record in the DB are not synchronized.

    Consider the following example :

     Employee employee= (Employee)entityManager.find(Employee.class , 1);
     entityManager
         .createQuery("update Employee set name = \'xxxx\' where id=1")
         .executeUpdate();
    

    After flushing, the name in the DB is updated to the new value but the employee instance in the memory still keeps the original value .You have to call entityManager.refresh(employee) to reload the updated name from the DB to the employee instance.It sounds strange if your codes still have to manipulate the employee instance after flushing but you forget to refresh() the employee instance as the employee instance still contains the original values.

    Normally , executeUpdate() is used in the bulk update process as it is faster due to bypassing the persistent context

    The right way to update an entity is that you just set the properties you want to updated through the setters and let the JPA to generate the update SQL for you during flushing instead of writing it manually.

       Employee employee= (Employee)entityManager.find(Employee.class ,1);
       employee.setName("Updated Name");
    

    Can HTTP POST be limitless?

    Different IIS web servers can process different amounts of data in the 'header', according to this (now deleted) article; http://classicasp.aspfaq.com/forms/what-is-the-limit-on-form/post-parameters.html;

    Note that there is no limit on the number of FORM elements you can pass via POST, but only on the aggregate size of all name/value pairs. While GET is limited to as low as 1024 characters, POST data is limited to 2 MB on IIS 4.0, and 128 KB on IIS 5.0. Each name/value is limited to 1024 characters, as imposed by the SGML spec. Of course this does not apply to files uploaded using enctype='multipart/form-data' ... I have had no problems uploading files in the 90 - 100 MB range using IIS 5.0, aside from having to increase the server.scriptTimeout value as well as my patience!

    MVC 4 Razor File Upload

    View Page

    @using (Html.BeginForm("ActionmethodName", "ControllerName", FormMethod.Post, new { id = "formid" }))
     { 
       <input type="file" name="file" />
       <input type="submit" value="Upload" class="save" id="btnid" />
     }
    

    script file

    $(document).on("click", "#btnid", function (event) {
            event.preventDefault();
            var fileOptions = {
                success: res,
                dataType: "json"
            }
            $("#formid").ajaxSubmit(fileOptions);
        });
    

    In Controller

        [HttpPost]
        public ActionResult UploadFile(HttpPostedFileBase file)
        {
    
        }
    

    How can I change the text inside my <span> with jQuery?

    Syntax:

    • return the element's text content: $(selector).text()
    • set the element's text content to content: $(selector).text(content)
    • set the element's text content using a callback function: $(selector).text(function(index, curContent))

    JQuery - Change the text of a span element

    Interfaces vs. abstract classes

    The real question is: whether to use interfaces or base classes. This has been covered before.

    In C#, an abstract class (one marked with the keyword "abstract") is simply a class from which you cannot instantiate objects. This serves a different purpose than simply making the distinction between base classes and interfaces.

    How to check if an element of a list is a list (in Python)?

    1. Work out what specific properties of a list you want the items to have. Do they need to be indexable? Sliceable? Do they need an .append() method?

    2. Look up the abstract base class which describes that particular type in the collections module.

    3. Use isinstance:

      isinstance(x, collections.MutableSequence)
      

    You might ask "why not just use type(x) == list?" You shouldn't do that, because then you won't support things that look like lists. And part of the Python mentality is duck typing:

    I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck

    In other words, you shouldn't require that the objects are lists, just that they have the methods you will need. The collections module provides a bunch of abstract base classes, which are a bit like Java interfaces. Any type that is an instance of collections.Sequence, for example, will support indexing.

    How to check the function's return value if true or false

    you're comparing the result against a string ('false') not the built-in negative constant (false)

    just use

    if(ValidateForm() == false) {
    

    or better yet

    if(!ValidateForm()) {
    

    also why are you calling validateForm twice?