Programs & Examples On #Runge kutta

Runge–Kutta methods are an important family of implicit and explicit iterative methods, which are used in temporal discretization for the approximation of solutions of ordinary differential equations.

I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely

I found out, that I need to set the public property of devServer, to my request's host value. Being that it will be displayed at that external address.

So I needed this in my webpack.config.js

devServer: {
  compress: true,
  public: 'store-client-nestroia1.c9users.io' // That solved it
}

Another solution is using it on the CLI:

webpack-dev-server --public $C9_HOSTNAME <-- var for Cloud9 external IP

How is a JavaScript hash map implemented?

I was running into the problem where i had the json with some common keys. I wanted to group all the values having the same key. After some surfing I found hashmap package. Which is really helpful.

To group the element with the same key, I used multi(key:*, value:*, key2:*, value2:*, ...).

This package is somewhat similar to Java Hashmap collection, but not as powerful as Java Hashmap.

Get timezone from users browser using moment(timezone).js

var timedifference = new Date().getTimezoneOffset();

This returns the difference from the clients timezone from UTC time. You can then play around with it as you like.

What is the difference between a schema and a table and a database?

More on schemas:

In SQL 2005 a schema is a way to group objects. It is a container you can put objects into. People can own this object. You can grant rights on the schema.

In 2000 a schema was equivalent to a user. Now it has broken free and is quite useful. You could throw all your user procs in a certain schema and your admin procs in another. Grant EXECUTE to the appropriate user/role and you're through with granting EXECUTE on specific procedures. Nice.

The dot notation would go like this:

Server.Database.Schema.Object

or

myserver01.Adventureworks.Accounting.Beans

How to maintain page scroll position after a jquery event is carried out?

I had a similar problem getting scrollTop to work after reload of div content. The content scrolled to top each time the procedure below was run. I found that a little delay before setting the new scrolltop solved the issue.

This is cut from wdCalendar where I modified this procedure:

 function BuildDaysAndWeekView(startday, l, events, config)
   ....
        var scrollpos = $("#dvtec").scrollTop();
        gridcontainer.html(html.join(""));
        setTimeout(function() {
            $("#dvtec").scrollTop(scrollpos);
        }, 25);
   ....

Without the delay, it simply did not work.

Concatenating string and integer in python

if you only want to print yo can do this:

print(s , i)

PHP syntax question: What does the question mark and colon mean?

This is the PHP ternary operator (also known as a conditional operator) - if first operand evaluates true, evaluate as second operand, else evaluate as third operand.

Think of it as an "if" statement you can use in expressions. Can be very useful in making concise assignments that depend on some condition, e.g.

$param = isset($_GET['param']) ? $_GET['param'] : 'default';

There's also a shorthand version of this (in PHP 5.3 onwards). You can leave out the middle operand. The operator will evaluate as the first operand if it true, and the third operand otherwise. For example:

$result = $x ?: 'default';

It is worth mentioning that the above code when using i.e. $_GET or $_POST variable will throw undefined index notice and to prevent that we need to use a longer version, with isset or a null coalescing operator which is introduced in PHP7:

$param = $_GET['param'] ?? 'default';

Unknown SSL protocol error in connection

I was able to solve it by running

git config --list --show-origin

and then seeing that I had a line:

file:c:/Users/user/.gitconfig http.sslversion=sslv3

I edited the file, c:/Users/user/.gitconfig, and deleted the line [http] and the line sslversion=sslv3 and that fixed it for me.

How can I create an utility class?

I would make the class final and every method would be static.

So the class cannot be extended and the methods can be called by Classname.methodName. If you add members, be sure that they work thread safe ;)

ASP.NET Web API session or something?

in Global.asax add

public override void Init()
{
    this.PostAuthenticateRequest += MvcApplication_PostAuthenticateRequest;
    base.Init();
}

void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
    System.Web.HttpContext.Current.SetSessionStateBehavior(
        SessionStateBehavior.Required);
}

give it a shot ;)

How do I fetch only one branch of a remote Git repository?

If you want to change the default for "git pull" and "git fetch" to only fetch specific branches then you can edit .git/config so that the remote config looks like:

[remote "origin"]
  fetch = +refs/heads/master:refs/remotes/origin/master

This will only fetch master from origin by default. See for more info: https://git-scm.com/book/en/v2/Git-Internals-The-Refspec

EDIT: Just realized this is the same thing that the -t option does for git remote add. At least this is a nice way to do it after the remote is added if you don't want ot delete the remote and add it again using -t.

String array initialization in Java

First up, this has got nothing to do with String, it is about arrays.. and that too specifically about declarative initialization of arrays.

As discussed by everyone in almost every answer here, you can, while declaring a variable, use:

String names[] = {"x","y","z"};

However, post declaration, if you want to assign an instance of an Array:

names = new String[] {"a","b","c"};

AFAIK, the declaration syntax is just a syntactic sugar and it is not applicable anymore when assigning values to variables because when values are assigned you need to create an instance properly.

However, if you ask us why it is so? Well... good luck getting an answer to that. Unless someone from the Java committee answers that or there is explicit documentation citing the said syntactic sugar.

SHA1 vs md5 vs SHA256: which to use for a PHP login?

MD5 is bad because of collision problems - two different passwords possibly generating the same md-5.

Sha-1 would be plenty secure for this. The reason you store the salted sha-1 version of the password is so that you the swerver do not keep the user's apassword on file, that they may be using with other people's servers. Otherwise, what difference does it make?

If the hacker steals your entire unencrypted database some how, the only thing a hashed salted password does is prevent him from impersonating the user for future signons - the hacker already has the data.

What good does it do the attacker to have the hashed value, if what your user inputs is a plain password?

And even if the hacker with future technology could generate a million sha-1 keys a second for a brute force attack, would your server handle a million logons a second for the hacker to test his keys? That's if you are letting the hacker try to logon with the salted sha-1 instead of a password like a normal logon.

The best bet is to limit bad logon attempts to some reasonable number - 25 for example, and then time the user out for a minute or two. And if the cumulative bady logon attempts hits 250 within 24 hours, shut the account access down and email the owner.

Android Notification Sound

notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);

Get all messages from Whatsapp

Edit

As WhatsApp put some effort into improving their encryption system, getting the data is not that easy anymore. With newer versions of WhatsApp it is no longer possible to use adb backup. Apps can deny backups and the WhatsApp client does that. If you happen to have a rooted phone, you can use a root shell to get the unencrypted database file.

If you do not have root, you can still decrypt the data if you have an old WhatsApp APK. Find a version that still allows backups. Then you can make a backup of the app's data folder, which will contain an encryption key named, well, key.

Now you'll need the encrypted database. Use a file explorer of your choice or, if you like the command line more, use adb:

adb pull /sdcard/WhatsApp/Databases/msgstore.db.crypt12

Using the two files, you could now use https://gitlab.com/digitalinternals/whatsapp-crypt12 to get the plain text database. It is no longer possible to use Linux board tools like openssl because WhatsApp seems to use a modified version of the Spongy Castle API for cryptography that openssl does not understand.

Original Answer (only for the old crypt7)

As whatsapp is now using the crypt7 format, it is not that easy to get and decrypt the database anymore. There is a working approach using ADB and USB debugging.

You can either get the encryption keys via ADB and decrypt the message database stored on /sdcard, or you just get the plain version of the database via ADB backup, what seems to be the easier option.

To get the database, do the following:

Connect your Android phone to your computer. Now run

adb backup -f whatsapp_backup.ab -noapk com.whatsapp

to backup all files WhatsApp has created in its private folder.
You will get a zlib compressed file using tar format with some ADB headers. We need to get rid of those headers first as they confuse the decompression command:

dd if=whatsapp_backup.ab ibs=1 skip=24 of=whatsapp_backup.ab.nohdr

The file can now be decompressed:

cat whatsapp_backup.ab.nohdr | python -c "import zlib,sys;sys.stdout.write(zlib.decompress(sys.stdin.read()))" 1> whatsapp_backup.tar

This command runs Python and decompresses the file using zlib to whatsapp_backup.tar
Now we can unTAR the file:

tar xf whatsapp_backup.tar

The archive is now extracted to your current working directory and you can find the databases (msgstore.db and wa.db) in apps/com.whatsapp/db/

Rolling back bad changes with svn in Eclipse

You have two choices to do this.

The Quick and Dirty is selecting your files (using ctrl) in Project Explorer view, right-click them, choose Replace with... and then you choose the best option for you, from Latest from Repository, or some Branch version. After getting those files you modify them (with a space, or fix something, your call and commit them to create a newer revision.

A more clean way is choosing Merge at team menu and navigate through the wizard that will help you to recovery the old version in the actual revision.

Both commands have their command-line equivalents: svn revert and svn merge.

How can I set selected option selected in vue.js 2?

You simply need to remove v-bind (:) from selected and required attributes. Like this :-

_x000D_
_x000D_
<template>_x000D_
    <select class="form-control" v-model="selected" required @change="changeLocation">_x000D_
        <option selected>Choose Province</option>_x000D_
        <option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>_x000D_
    </select>_x000D_
</template>
_x000D_
_x000D_
_x000D_

You are not binding anything to the vue instance through these attributes thats why it is giving error.

How to include layout inside layout?

Try this

<include
            android:id="@+id/OnlineOffline"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            layout="@layout/YourLayoutName" />

How to read existing text files without defining path

You could use Directory.GetCurrentDirectory:

var path = Path.Combine(Directory.GetCurrentDirectory(), "\\fileName.txt");

Which will look for the file fileName.txt in the current directory of the application.

How to send an email with Gmail as provider using Python?

great answer from @David, here is for Python 3 without the generic try-except:

def send_email(user, password, recipient, subject, body):

    gmail_user = user
    gmail_pwd = password
    FROM = user
    TO = recipient if type(recipient) is list else [recipient]
    SUBJECT = subject
    TEXT = body

    # Prepare actual message
    message = """From: %s\nTo: %s\nSubject: %s\n\n%s
    """ % (FROM, ", ".join(TO), SUBJECT, TEXT)

    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.ehlo()
    server.starttls()
    server.login(gmail_user, gmail_pwd)
    server.sendmail(FROM, TO, message)
    server.close()

Outlets cannot be connected to repeating content iOS

Click on simulator , Navigate to Window and enable Device Bezels

Passing in class names to react components

For anyone interested, I ran into this same issue when using css modules and react css modules.

Most components have an associated css module style, and in this example my Button has its own css file, as does the Promo parent component. But I want to pass some additional styles to Button from Promo

So the styleable Button looks like this:

Button.js

import React, { Component } from 'react'
import CSSModules from 'react-css-modules'
import styles from './Button.css'

class Button extends Component {

  render() {

    let button = null,
        className = ''

    if(this.props.className !== undefined){
        className = this.props.className
    }

    button = (
      <button className={className} styleName='button'>
        {this.props.children}
      </button>
    )

    return (
        button
    );
  }
};

export default CSSModules(Button, styles, {allowMultiple: true} )

In the above Button component the Button.css styles handle the common button styles. In this example just a .button class

Then in my component where I want to use the Button, and I also want to modify things like the position of the button, I can set extra styles in Promo.css and pass through as the className prop. In this example again called .button class. I could have called it anything e.g. promoButton.

Of course with css modules this class will be .Promo__button___2MVMD whereas the button one will be something like .Button__button___3972N

Promo.js

import React, { Component } from 'react';
import CSSModules from 'react-css-modules';
import styles from './Promo.css';

import Button from './Button/Button'

class Promo extends Component {

  render() {

    return (
        <div styleName='promo' >
          <h1>Testing the button</h1>
          <Button className={styles.button} >
            <span>Hello button</span>
          </Button>
        </div>
      </Block>
    );
  }
};

export default CSSModules(Promo, styles, {allowMultiple: true} );

IP to Location using Javascript

A free open source community run geolocation ip service that runs on the MaxMind database is available here: https://ipstack.com/

Example

https://api.ipstack.com/160.39.144.19

Limitation

10,000 queries per month

On duplicate key ignore?

Mysql has this handy UPDATE INTO command ;)

edit Looks like they renamed it to REPLACE

REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted

How to use if statements in underscore.js templates?

Responding to blackdivine above (about how to stripe one's results), you may have already found your answer (if so, shame on you for not sharing!), but the easiest way of doing so is by using the modulus operator. say, for example, you're working in a for loop:

<% for(i=0, l=myLongArray.length; i<l; ++i) { %>
...
<% } %>

Within that loop, simply check the value of your index (i, in my case):

<% if(i%2) { %>class="odd"<% } else { %>class="even" <% }%>

Doing this will check the remainder of my index divided by two (toggling between 1 and 0 for each index row).

JQuery / JavaScript - trigger button click from another button click event

Well, you just fire the desired click event:

$(".first").click(function(){
    $(".second").click(); 
    return false;
});

SQL Server - transactions roll back on error?

If one of the inserts fail, or any part of the command fails, does SQL server roll back the transaction?

No, it does not.

If it does not rollback, do I have to send a second command to roll it back?

Sure, you should issue ROLLBACK instead of COMMIT.

If you want to decide whether to commit or rollback the transaction, you should remove the COMMIT sentence out of the statement, check the results of the inserts and then issue either COMMIT or ROLLBACK depending on the results of the check.

How do I use System.getProperty("line.separator").toString()?

I think your problem is that String.split() treats its argument as a regex, and regexes treat newlines specially. You may need to explicitly create a regex object to pass to split() (there is another overload of it) and configure that regex to allow newlines by passing MULTILINE in the flags param of Pattern.compile(). Docs

Setting public class variables

If you are going to follow the examples given (using getter/setter or setting it in the constructor) change it to private since those are ways to control what is set in the variable.

It doesn't make sense to keep the property public with all those things added to the class.

What is an Endpoint?

All of the answers posted so far are correct, an endpoint is simply one end of a communication channel. In the case of OAuth, there are three endpoints you need to be concerned with:

  1. Temporary Credential Request URI (called the Request Token URL in the OAuth 1.0a community spec). This is a URI that you send a request to in order to obtain an unauthorized Request Token from the server / service provider.
  2. Resource Owner Authorization URI (called the User Authorization URL in the OAuth 1.0a community spec). This is a URI that you direct the user to to authorize a Request Token obtained from the Temporary Credential Request URI.
  3. Token Request URI (called the Access Token URL in the OAuth 1.0a community spec). This is a URI that you send a request to in order to exchange an authorized Request Token for an Access Token which can then be used to obtain access to a Protected Resource.

Hope that helps clear things up. Have fun learning about OAuth! Post more questions if you run into any difficulties implementing an OAuth client.

Angular2 @Input to a property with get/set

Updated accepted answer to angular 7.0.1 on stackblitz here: https://stackblitz.com/edit/angular-inputsetter?embed=1&file=src/app/app.component.ts

directives are no more in Component decorator options. So I have provided sub directive to app module.

thank you @thierry-templier!

Getting visitors country from their IP

You can use a simple API from http://www.geoplugin.net/

$xml = simplexml_load_file("http://www.geoplugin.net/xml.gp?ip=".getRealIpAddr());
echo $xml->geoplugin_countryName ;


echo "<pre>";
foreach ($xml as $key => $value)
{
    echo $key , "= " , $value ,  " \n" ;
}
echo "</pre>";

Function Used

function getRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

Output

United States
geoplugin_city= San Antonio
geoplugin_region= TX
geoplugin_areaCode= 210
geoplugin_dmaCode= 641
geoplugin_countryCode= US
geoplugin_countryName= United States
geoplugin_continentCode= NA
geoplugin_latitude= 29.488899230957
geoplugin_longitude= -98.398696899414
geoplugin_regionCode= TX
geoplugin_regionName= Texas
geoplugin_currencyCode= USD
geoplugin_currencySymbol= $
geoplugin_currencyConverter= 1

It makes you have so many options you can play around with

Thanks

:)

How to turn off Wifi via ADB?

Using "svc" through ADB (rooted required):

Enable:

adb shell su -c 'svc wifi enable'

Disable:

adb shell su -c 'svc wifi disable'

Using Key Events through ADB:

adb shell am start -a android.intent.action.MAIN -n com.android.settings/.wifi.WifiSettings
adb shell input keyevent 20 & adb shell input keyevent 23

The first line launch "wifi.WifiSettings" activity which open the WiFi Settings page. The second line simulate key presses.

I tested those two lines on a Droid X. But Key Events above probably need to edit in other devices because of different Settings layout.

More info about "keyevents" here.

What does -XX:MaxPermSize do?

-XX:PermSize -XX:MaxPermSize are used to set size for Permanent Generation.

Permanent Generation: The Permanent Generation is where class files are kept. These are the result of compiled classes and JSP pages. If this space is full, it triggers a Full Garbage Collection. If the Full Garbage Collection cannot clean out old unreferenced classes and there is no room left to expand the Permanent Space, an Out-of- Memory error (OOME) is thrown and the JVM will crash.

How do I combine the first character of a cell with another cell in Excel?

Not sure why no one is using semicolons. This is how it works for me:

=CONCATENATE(LEFT(A1;1); B1)

Solutions with comma produce an error in Excel.

How to Rotate a UIImage 90 degrees?

As strange as this seems, the following code solved the problem for me:

+ (UIImage*)unrotateImage:(UIImage*)image {
    CGSize size = image.size;
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0,0,size.width ,size.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

What is the purpose and use of **kwargs?

kwargs are a syntactic sugar to pass name arguments as dictionaries(for func), or dictionaries as named arguments(to func)

jquery to loop through table rows and cells, where checkob is checked, concatenate

Try this:

function createcodes() {

    $('.authors-list tr').each(function () {
        //processing this row
        //how to process each cell(table td) where there is checkbox
        $(this).find('td input:checked').each(function () {

             // it is checked, your code here...
        });
    });
}

What is the difference between POST and GET?

If you are working RESTfully, GET should be used for requests where you are only getting data, and POST should be used for requests where you are making something happen.

Some examples:

  • GET the page showing a particular SO question

  • POST a comment

  • Send a POST request by clicking the "Add to cart" button.

Problems using Maven and SSL behind proxy

What worked for me:

Configure <proxy> settings in ${MAVEN_HOME}/conf/settings.xml:

(Note: For others, it worked when they configured ${user.home}/.m2/settings.xml. If there is no settings.xml in user.home, just copy it from conf/ in the maven directory.)

  <!-- proxies
   | This is a list of proxies which can be used on this machine to connect to the network.
   | Unless otherwise specified (by system property or command-line switch), the first proxy
   | specification in this list marked as active will be used.
   |-->
  <proxies>
    <!-- proxy
     | Specification for one proxy, to be used in connecting to the network.
     |
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>proxyuser</username>
      <password>proxypass</password>
      <host>proxy.host.net</host>
      <port>80</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
    -->

    <proxy>
      <id>my-proxy</id>
      <active>true</active>
      <protocol>http</protocol>
      <username></username>
      <password></password>
      <host>my.proxy.host.com</host>
      <port>8080</port>
      <nonProxyHosts></nonProxyHosts>
    </proxy>

  </proxies>

Then point pom.xml to download from http maven central repo:

<project>
...
    <repositories>
        <repository>
            <id>central</id>
            <name>Maven Plugin Repository</name>
            <url>http://repo1.maven.org/maven2</url>
            <layout>default</layout>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <releases>
                <updatePolicy>never</updatePolicy>
            </releases>
        </repository>
    </repositories>
...
</project>

You may also need to configure http proxy in your IDE. For VSCode in settings.json:

{
    ...
    "http.proxy": "http://my/proxy/script/address/my-proxy.pac",
    ...
}

For Win10: Start/Search > Network proxy settings > Script address enter image description here

Sources:

How can I import data into mysql database via mysql workbench?

  1. Open Connetion
  2. Select "Administration" tab
  3. Click on Data import

Upload sql file

enter image description here

Make sure to select your database in this award winning GUI:

enter image description here

How to AUTO_INCREMENT in db2?

Added a few optional parameters for creating "future safe" sequences.

CREATE SEQUENCE <NAME>
  START WITH 1
  INCREMENT BY 1
  NO MAXVALUE
  NO CYCLE
  CACHE 10;

apache redirect from non www to www

The code I use is:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

Convert pandas DataFrame into list of lists

EDIT: as_matrix is deprecated since version 0.23.0

You can use the built in values or to_numpy (recommended option) method on the dataframe:

In [8]:
df.to_numpy()

Out[8]:
array([[  0.9,   7. ,   5.2, ...,  13.3,  13.5,   8.9],
   [  0.9,   7. ,   5.2, ...,  13.3,  13.5,   8.9],
   [  0.8,   6.1,   5.4, ...,  15.9,  14.4,   8.6],
   ..., 
   [  0.2,   1.3,   2.3, ...,  16.1,  16.1,  10.8],
   [  0.2,   1.3,   2.4, ...,  16.5,  15.9,  11.4],
   [  0.2,   1.3,   2.4, ...,  16.5,  15.9,  11.4]])

If you explicitly want lists and not a numpy array add .tolist():

df.to_numpy().tolist()

return, return None, and no return at all?

They each return the same singleton None -- There is no functional difference.

I think that it is reasonably idiomatic to leave off the return statement unless you need it to break out of the function early (in which case a bare return is more common), or return something other than None. It also makes sense and seems to be idiomatic to write return None when it is in a function that has another path that returns something other than None. Writing return None out explicitly is a visual cue to the reader that there's another branch which returns something more interesting (and that calling code will probably need to handle both types of return values).

Often in Python, functions which return None are used like void functions in C -- Their purpose is generally to operate on the input arguments in place (unless you're using global data (shudders)). Returning None usually makes it more explicit that the arguments were mutated. This makes it a little more clear why it makes sense to leave off the return statement from a "language conventions" standpoint.

That said, if you're working in a code base that already has pre-set conventions around these things, I'd definitely follow suit to help the code base stay uniform...

Output a NULL cell value in Excel

As you've indicated, you can't output NULL in an excel formula. I think this has to do with the fact that the formula itself causes the cell to not be able to be NULL. "" is the next best thing, but sometimes it's useful to use 0.

--EDIT--

Based on your comment, you might want to check out this link. http://peltiertech.com/WordPress/mind-the-gap-charting-empty-cells/

It goes in depth on the graphing issues and what the various values represent, and how to manipulate their output on a chart.

I'm not familiar with VSTO I'm afraid. So I won't be much help there. But if you are really placing formulas in the cell, then there really is no way. ISBLANK() only tests to see if a cell is blank or not, it doesn't have a way to make it blank. It's possible to write code in VBA (and VSTO I imagine) that would run on a worksheet_change event and update the various values instead of using formulas. But that would be cumbersome and performance would take a hit.

SQL Server reports 'Invalid column name', but the column is present and the query works through management studio

I suspect that you have two tables with the same name. One is owned by the schema 'dbo' (dbo.PerfDiag), and the other is owned by the default schema of the account used to connect to SQL Server (something like userid.PerfDiag).

When you have an unqualified reference to a schema object (such as a table) — one not qualified by schema name — the object reference must be resolved. Name resolution occurs by searching in the following sequence for an object of the appropriate type (table) with the specified name. The name resolves to the first match:

  • Under the default schema of the user.
  • Under the schema 'dbo'.

The unqualified reference is bound to the first match in the above sequence.

As a general recommended practice, one should always qualify references to schema objects, for performance reasons:

  • An unqualified reference may invalidate a cached execution plan for the stored procedure or query, since the schema to which the reference was bound may change depending on the credentials executing the stored procedure or query. This results in recompilation of the query/stored procedure, a performance hit. Recompilations cause compile locks to be taken out, blocking others from accessing the needed resource(s).

  • Name resolution slows down query execution as two probes must be made to resolve to the likely version of the object (that owned by 'dbo'). This is the usual case. The only time a single probe will resolve the name is if the current user owns an object of the specified name and type.

[Edited to further note]

The other possibilities are (in no particular order):

  • You aren't connected to the database you think you are.
  • You aren't connected to the SQL Server instance you think you are.

Double check your connect strings and ensure that they explicitly specify the SQL Server instance name and the database name.

How to include multiple js files using jQuery $.getScript() method

This function will make sure that a file is loaded after the dependency file is loaded completely. You just need to provide the files in a sequence keeping in mind the dependencies on other files.

function loadFiles(files, fn) {
    if (!files.length) {
        files = [];
    }
    var head = document.head || document.getElementsByTagName('head')[0];

    function loadFile(index) {
        if (files.length > index) {
            var fileref = document.createElement('script');
            fileref.setAttribute("type", "text/javascript");
            fileref.setAttribute("src", files[index]);
            head.appendChild(fileref);
            index = index + 1;
            // Used to call a callback function
            fileref.onload = function () {
                loadFile(index);
            }
        } else if(fn){
            fn();
        }
    }
    loadFile(0);
}

How to get Tensorflow tensor dimensions (shape) as int values?

for a 2-D tensor, you can get the number of rows and columns as int32 using the following code:

rows, columns = map(lambda i: i.value, tensor.get_shape())

Mongod complains that there is no /data/db folder

If you are using Mac and running Catalina and Installed Mongodb via Homebrew what you have to do to start is just type this command and you are good to go.

brew services start mongodb-community

Giving multiple URL patterns to Servlet Filter

If an URL pattern starts with /, then it's relative to the context root. The /Admin/* URL pattern would only match pages on http://localhost:8080/EMS2/Admin/* (assuming that /EMS2 is the context path), but you have them actually on http://localhost:8080/EMS2/faces/Html/Admin/*, so your URL pattern never matches.

You need to prefix your URL patterns with /faces/Html as well like so:

<url-pattern>/faces/Html/Admin/*</url-pattern>

You can alternatively also just reconfigure your web project structure/configuration so that you can get rid of the /faces/Html path in the URLs so that you can just open the page by for example http://localhost:8080/EMS2/Admin/Upload.xhtml.

Your filter mapping syntax is all fine. However, a simpler way to specify multiple URL patterns is to just use only one <filter-mapping> with multiple <url-pattern> entries:

<filter-mapping>
    <filter-name>LoginFilter</filter-name>
    <url-pattern>/faces/Html/Employee/*</url-pattern>
    <url-pattern>/faces/Html/Admin/*</url-pattern>
    <url-pattern>/faces/Html/Supervisor/*</url-pattern>
</filter-mapping>

jQuery to remove an option from drop down list, given option's text/value

Once you have localized the dropdown element

dropdownElement = $("#dropdownElement");

Find the <option> element using the JQuery attribute selector

dropdownElement.find('option[value=foo]').remove();

multiple ways of calling parent method in php

There are three scenarios (that I can think of) where you would call a method in a subclass where the method exits in the parent class:

  1. Method is not overwritten by subclass, only exists in parent.

    This is the same as your example, and generally it's better to use $this -> get_species(); You are right that in this case the two are effectively the same, but the method has been inherited by the subclass, so there is no reason to differentiate. By using $this you stay consistent between inherited methods and locally declared methods.

  2. Method is overwritten by the subclass and has totally unique logic from the parent.

    In this case, you would obviously want to use $this -> get_species(); because you don't want the parent's version of the method executed. Again, by consistently using $this, you don't need to worry about the distinction between this case and the first.

  3. Method extends parent class, adding on to what the parent method achieves.

    In this case, you still want to use `$this -> get_species(); when calling the method from other methods of the subclass. The one place you will call the parent method would be from the method that is overwriting the parent method. Example:

    abstract class Animal {
    
        function get_species() {
    
            echo "I am an animal.";
    
        }
    
     }
    
     class Dog extends Animal {
    
         function __construct(){
    
             $this->get_species();
         }
    
         function get_species(){
    
             parent::get_species();
             echo "More specifically, I am a dog.";
         }
    }
    

The only scenario I can imagine where you would need to call the parent method directly outside of the overriding method would be if they did two different things and you knew you needed the parent's version of the method, not the local. This shouldn't be the case, but if it did present itself, the clean way to approach this would be to create a new method with a name like get_parentSpecies() where all it does is call the parent method:

function get_parentSpecies(){

     parent::get_species();
}

Again, this keeps everything nice and consistent, allowing for changes/modifications to the local method rather than relying on the parent method.

Postfix is installed but how do I test it?

(I just got this working, with my main issue being that I don't have a real internet hostname, so answering this question in case it helps someone)

You need to specify a hostname with HELO. Even so, you should get an error, so Postfix is probably not running.

Also, the => is not a command. The '.' on a single line without any text around it is what tells Postfix that the entry is complete. Here are the entries I used:

telnet localhost 25
(says connected)
EHLO howdy.com
(returns a bunch of 250 codes)
MAIL FROM: [email protected]
RCPT TO: (use a real email address you want to send to)
DATA (type whatever you want on muliple lines)
. (this on a single line tells Postfix that the DATA is complete)

You should get a response like:

250 2.0.0 Ok: queued as 6E414C4643A

The email will probably end up in a junk folder. If it is not showing up, then you probably need to setup the 'Postfix on hosts without a real Internet hostname'. Here is the breakdown on how I completed that step on my Ubuntu box:

sudo vim /etc/postfix/main.cf
smtp_generic_maps = hash:/etc/postfix/generic (add this line somewhere)
(edit or create the file 'generic' if it doesn't exist)
sudo vim /etc/postfix/generic
(add these lines, I don't think it matters what names you use, at least to test)
[email protected]             [email protected]
[email protected]             [email protected]
@localdomain.local                [email protected]
then run:
postmap /etc/postfix/generic (this needs to be run whenever you change the 
generic file)

Happy Trails

Convert array of indices to 1-hot encoded numpy array

Here's a dimensionality-independent standalone solution.

This will convert any N-dimensional array arr of nonnegative integers to a one-hot N+1-dimensional array one_hot, where one_hot[i_1,...,i_N,c] = 1 means arr[i_1,...,i_N] = c. You can recover the input via np.argmax(one_hot, -1)

def expand_integer_grid(arr, n_classes):
    """

    :param arr: N dim array of size i_1, ..., i_N
    :param n_classes: C
    :returns: one-hot N+1 dim array of size i_1, ..., i_N, C
    :rtype: ndarray

    """
    one_hot = np.zeros(arr.shape + (n_classes,))
    axes_ranges = [range(arr.shape[i]) for i in range(arr.ndim)]
    flat_grids = [_.ravel() for _ in np.meshgrid(*axes_ranges, indexing='ij')]
    one_hot[flat_grids + [arr.ravel()]] = 1
    assert((one_hot.sum(-1) == 1).all())
    assert(np.allclose(np.argmax(one_hot, -1), arr))
    return one_hot

chart.js load totally new data

ChartJS 2.6 supports data reference replacement (see Note in update(config) documentation). So when you have your Chart, you could basically just do this:

myChart.data.labels = ['1am', '2am', '3am', '4am'];
myChart.data.datasets[0].data = [0, 12, 35, 36];
myChart.update();

It doesn't do the animation you'd get from adding points, but existing points on the graph will be animated.

How to catch exception correctly from http.request()?

in the latest version of angular4 use

import { Observable } from 'rxjs/Rx'

it will import all the required things.

Collections.emptyList() vs. new instance

The given answers stress the fact that emptyList() returns an immutable List but do not give alternatives. The Constructor ArrayList(int initialCapacity) special cases 0 so returning new ArrayList<>(0) instead of new ArrayList<>() might also be a viable solution:

/**
 * Shared empty array instance used for empty instances.
 */
private static final Object[] EMPTY_ELEMENTDATA = {};

[...]

/**
 * Constructs an empty list with the specified initial capacity.
 *
 * @param  initialCapacity  the initial capacity of the list
 * @throws IllegalArgumentException if the specified initial capacity
 *         is negative
 */
public ArrayList(int initialCapacity) {
    if (initialCapacity > 0) {
        this.elementData = new Object[initialCapacity];
    } else if (initialCapacity == 0) {
        this.elementData = EMPTY_ELEMENTDATA;
    } else {
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    }
}

(sources from Java 1.8.0_72)

Converting float to char*

Long after accept answer.

Use sprintf(), or related functions, as many others have answers suggested, but use a better format specifier.

Using "%.*e", code solves various issues:

  • The maximum buffer size needed is far more reasonable, like 18 for float (see below). With "%f", sprintf(buf, "%f", FLT_MAX); could need 47+. sprintf(buf, "%f", DBL_MAX); may need 317+

  • Using ".*" allows code to define the number of decimal places needed to distinguish a string version of float x and it next highest float. For deatils, see Printf width specifier to maintain precision of floating-point value

  • Using "%e" allows code to distinguish small floats from each other rather than all printing "0.000000" which is the result when |x| < 0.0000005.

Example usage

#include <float.h>
#define FLT_STRING_SIZE (1+1+1+(FLT_DECIMAL_DIG-1)+1+1+ 4   +1)
                     //  - d .  dddddddd           e - dddd \0

char buf[FLT_STRING_SIZE];
sprintf(buf, "%.*e", FLT_DECIMAL_DIG-1, some_float);

Ideas:
IMO, better to use 2x buffer size for scratch pads like buf[FLT_STRING_SIZE*2].
For added robustness, use snprintf().


As a 2nd alterative consider "%.*g". It is like "%f" for values exponentially near 1.0 and like "%e" for others.

How to process images of a video, frame by frame, in video streaming using OpenCV and Python

In openCV's documentation there is an example for getting video frame by frame. It is written in c++ but it is very easy to port the example to python - you can search for each fumction documentation to see how to call them in python.

#include "opencv2/opencv.hpp"

using namespace cv;

int main(int, char**)
{
    VideoCapture cap(0); // open the default camera
    if(!cap.isOpened())  // check if we succeeded
        return -1;

    Mat edges;
    namedWindow("edges",1);
    for(;;)
    {
        Mat frame;
        cap >> frame; // get a new frame from camera
        cvtColor(frame, edges, CV_BGR2GRAY);
        GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5);
        Canny(edges, edges, 0, 30, 3);
        imshow("edges", edges);
        if(waitKey(30) >= 0) break;
    }
    // the camera will be deinitialized automatically in VideoCapture destructor
    return 0;
}

C++11 thread-safe queue

There is also GLib solution for this case, I did not try it yet, but I believe it is a good solution. https://developer.gnome.org/glib/2.36/glib-Asynchronous-Queues.html#g-async-queue-new

Get docker container id from container name

In my case I was running Tensorflow Docker container in Ubuntu 20.04 :Run your docker container in One terminal , I ran it with

docker run -it od

And then started another terminal and ran below docker ps with sudo:

sudo docker ps

I successfully got container id:

CONTAINER ID        IMAGE               COMMAND             CREATED             
STATUS              PORTS               NAMES
e4ca1ad20b84        od                  "/bin/bash"         18 minutes ago      
Up 18 minutes                           unruffled_stonebraker

Android SharedPreferences in Fragment

As a note of caution this answer provided by the user above me is correct.

SharedPreferences preferences = this.getActivity().getSharedPreferences("pref",0);

However, if you attempt to get anything in the fragment before onAttach is called getActivity() will return null.

justify-content property isn't working

This answer might be stupid, but I spent quite some time to figure it out.

What happened to me was I didn't set display: flex to the container. And of course, justify-content won't work without a container with that property.

How does the communication between a browser and a web server take place?

Your browser is sitting on top of TCP/IP, as the web is based on standards, usually port 80, what happens is when you enter an address, such as google.com, your computer where the browser is running on, creates packets of data, encapsulated at each layer accordingly to the OSI standards, (think of envelopes of different sizes, packed into each envelope of next size), OSI defines 7 layers, in one of the envelopes contains the source address and destination address(that is the website) encoded in binary.

As it reaches the 1st layer, in OSI terms, it gets transmitted across the media transmitter (such as cable, DSL).

If you are connected via ISP, the layered pack of envelopes gets transmitted to the ISP, the ISP's network system, peeks through the layered pack of envelopes by decoding in reverse order to find out the address, then the ISP checks their Domain Name System database to find out if they have a route to that address (cached in memory, if it does, it forwards it across the internet network - again layered pack of envelopes).

If it doesn't, the ISP interrogates the top level DNS server to say 'Hey, get me the route for the address as supplied by you, ie. the browser', the top level DNS server then passes the route to the ISP which is then stored in the ISP's server memory.

The layered pack of envelopes are transmitted and received by the website server after successful routing of the packets (think of routing as signposts for directions to get to the server), which in turn, unpacks the layered pack of envelopes, extracts the source address and says 'Aha, that is for me, right, I know the destination address (that is you, the browser), then the server packetizes the webpages into a packed layered envelopes and sends it back (usually in reverse route, but not always the case).

Your browser than receives the packetized envelopes and unpacks each of them. Then your computer descrambles the data and your browser renders the pages on the screen.

I hope this answer is sufficient enough for your understanding.

SQL Query - Change date format in query to DD/MM/YYYY

If DB is SQL Server then

select Convert(varchar(10),CONVERT(date,YourDateColumn,106),103)

How can I get Apache gzip compression to work?

Your .htaccess should run just fine; it depends on four different Apache modules (one per each <IfModule> directive). I guess one of the following:

  • your Apache server doesn't have either mod_filter, mod_deflate, mod_headers and/or mod_setenvif modules installed and running. If you can access the server config, please check /etc/apache2/httpd.conf (and the related Apache config files); otherwise, you can see which modules are loaded via phpinfo(), under the apache2handler section (see attached image); (EDIT) OR, you can open a terminal window and issue the command sudo apachectl -M that will list the loaded modules;

  • if you get an http 500 internal server error, your server may not be allowed to use .htaccess files;

  • you are trying to load a PHP file that sends its own headers (overwriting Apache'sheaders), thus "confusing" the browser.

In any case, you should double-check your server config and error logs to see what's going wrong. Just to be sure, try to use the fastest way suggested here in Apache docs:

AddOutputFilterByType DEFLATE text/html text/plain text/xml

and then try to load a large textfile (preferably, clean your cache first).

(EDIT) If the needed modules are there (in the Apache modules dir) but aren't loaded, just edit /etc/apache2/httpd.conf and add a LoadModule directive for each one of them.

If the needed modules aren't there (neither loaded, nor in the Apache modules directory), I fear that the only option is reinstalling Apache (a complete version).

phpinfo() apache2handler section

Android Facebook integration with invalid key hash

If you are typing the keyhash manually (for example from mobile to the Facebook Dashboard), make sure to differentiate between small L and capital I.

When to use MongoDB or other document oriented database systems?

Note that Mongo essentially stores JSON. If your app is dealing with a lot of JS Objects (with nesting) and you want to persist these objects then there is a very strong argument for using Mongo. It makes your DAL and MVC layers ultra thin, because they are not un-packaging all the JS object properties and trying to force-fit them into a structure (schema) that they don't naturally fit into.

We have a system that has several complex JS Objects at its heart, and we love Mongo because we can persist everything really, really easily. Our objects are also rather amorphous and unstructured, and Mongo soaks up that complication without blinking. We have a custom reporting layer that deciphers the amorphous data for human consumption, and that wasn't that difficult to develop.

Difference between HashMap and Map in Java..?

Map is an interface in Java. And HashMap is an implementation of that interface (i.e. provides all of the methods specified in the interface).

How can I check if an argument is defined when starting/calling a batch file?

A more-advanced example:

? unlimited arguments.

? exist on file system (either file or directory?) or a generic string.

? specify if is a file

? specify is a directory

? no extensions, would work in legacy scripts!

? minimal code ?

@echo off

:loop
      ::-------------------------- has argument ?
      if ["%~1"]==[""] (
        echo done.
        goto end
      )
      ::-------------------------- argument exist ?
      if not exist %~s1 (
        echo not exist
      ) else (
        echo exist
        if exist %~s1\NUL (
          echo is a directory
        ) else (
          echo is a file
        )
      )
      ::--------------------------
      shift
      goto loop
      
      
:end

pause

? other stuff..?

¦ in %~1 - the ~ removes any wrapping " or '.

¦ in %~s1 - the s makes the path be DOS 8.3 naming, which is a nice trick to avoid spaces in file-name while checking stuff (and this way no need to wrap the resource with more "s.

¦ the ["%~1"]==[""] "can not be sure" if the argument is a file/directory or just a generic string yet, so instead the expression uses brackets and the original unmodified %1 (just without the " wrapping, if any..)

if there were no arguments of if we've used shift and the arg-list pointer has passed the last one, the expression will be evaluated to [""]==[""].

¦ this is as much specific you can be without using more tricks (it would work even in windows-95's batch-scripts...)

¦ execution examples

save it as identifier.cmd

it can identify an unlimited arguments (normally you are limited to %1-%9), just remember to wrap the arguments with inverted-commas, or use 8.3 naming, or drag&drop them over (it automatically does either of above).


this allows you to run the following commands:

?identifier.cmd c:\windows and to get

exist
is a directory
done

?identifier.cmd "c:\Program Files (x86)\Microsoft Office\OFFICE11\WINWORD.EXE" and to get

exist
is a file
done

? and multiple arguments (of course this is the whole-deal..)

identifier.cmd c:\windows\system32 c:\hiberfil.sys "c:\pagefile.sys" hello-world

and to get

exist
is a directory
exist
is a file
exist
is a file
not exist
done.

naturally it can be a lot more complex, but nice examples should always be simple and minimal. :)

Hope it helps anyone :)

published here:CMD Ninja - Unlimited Arguments Processing, Identifying If Exist In File-System, Identifying If File Or Directory

and here is a working example that takes any amount of APK files (Android apps) and installs them on your device via debug-console (ADB.exe): Make The Previous Post A Mass APK Installer That Does Not Uses ADB Install-Multi Syntax

How do I specify the platform for MSBuild?

There is an odd case I got in VS2017, about the space between ‘Any’ and 'CPU'. this is not about using command prompt.

If you have a build project file, which could call other solution files. You can try to add the space between Any and CPU, like this (the Platform property value):

<MSBuild Projects="@(SolutionToBuild2)" Properties ="Configuration=$(ProjectConfiguration);Platform=Any CPU;Rerun=$(MsBuildReRun);" />

Before I fix this build issue, it is like this (ProjectPlatform is a global variable, was set to 'AnyCPU'):

<MSBuild Projects="@(SolutionToBuild1)" Properties ="Configuration=$(ProjectConfiguration);Platform=$(ProjectPlatform);Rerun=$(MsBuildReRun);" />

Also, we have a lot projects being called using $ (ProjectPlatform), which is 'AnyCPU' and work fine. If we open proj file, we can see lines liket this and it make sense.

<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">

So my conclusion is, 'AnyCPU' works for calling project files, but not for calling solution files, for calling solution files, using 'Any CPU' (add the space.)

For now, I am not sure if it is a bug of VS project file or MSBuild. I am using VS2017 with VS2017 build tools installed.

Default settings Raspberry Pi /etc/network/interfaces

Assuming that you have a DHCP server running at your router I would use:

# /etc/network/interfaces
auto lo eth0
iface lo inet loopback

iface eth0 inet dhcp

After changing the file issue (as root):

/etc/init.d/networking restart

resource error in android studio after update: No Resource Found

compileSDK should match appCompat version. TargetSDK can still be 22 (e.g. in case you didn't update to the new permission model yet)

How can I get Maven to stop attempting to check for updates for artifacts from a certain group from maven-central-repo?

The updatePolicy tag didn't work for me. However Rich Seller mentioned that snapshots should be disabled anyways so I looked further and noticed that the extra repository that I added to my settings.xml was causing the problem actually. Adding the snapshots section to this repository in my settings.xml did the trick!

<repository>
    <id>jboss</id>
    <name>JBoss Repository</name>
    <url>http://repository.jboss.com/maven2</url>
    <snapshots>
        <enabled>false</enabled>
    </snapshots>
</repository>

jwt check if token expired

// Pass in function expiration date to check token 
function checkToken(exp) {
    if (Date.now() <= exp * 1000) {
      console.log(true, 'token is not expired')
    } else { 
      console.log(false, 'token is expired') 
    }
  }

How can I reset or revert a file to a specific revision?

You can quickly review the changes made to a file using the diff command:

git diff <commit hash> <filename>

Then to revert a specific file to that commit use the reset command:

git reset <commit hash> <filename>

You may need to use the --hard option if you have local modifications.

A good workflow for managaging waypoints is to use tags to cleanly mark points in your timeline. I can't quite understand your last sentence but what you may want is diverge a branch from a previous point in time. To do this, use the handy checkout command:

git checkout <commit hash>
git checkout -b <new branch name>

You can then rebase that against your mainline when you are ready to merge those changes:

git checkout <my branch>
git rebase master
git checkout master
git merge <my branch>

Image size (Python, OpenCV)

Using openCV and numpy it is as easy as this:

import cv2

img = cv2.imread('path/to/img',0)
height, width = img.shape[:2]

python re.split() to split by spaces, commas, and periods, but not in cases like 1,000 or 1.50

Use a negative lookahead and a negative lookbehind:

> s = "one two 3.4 5,6 seven.eight nine,ten"
> parts = re.split('\s|(?<!\d)[,.](?!\d)', s)
['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten']

In other words, you always split by \s (whitespace), and only split by commas and periods if they are not followed (?!\d) or preceded (?<!\d) by a digit.

DEMO.

EDIT: As per @verdesmarald comment, you may want to use the following instead:

> s = "one two 3.4 5,6 seven.eight nine,ten,1.2,a,5"
> print re.split('\s|(?<!\d)[,.]|[,.](?!\d)', s)
['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten', '1.2', 'a', '5']

This will split "1.2,a,5" into ["1.2", "a", "5"].

DEMO.

Java SSLException: hostname in certificate didn't match

You can also try to set a HostnameVerifier as described here. This worked for me to avoid this error.

// Do not do this in production!!!
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

DefaultHttpClient client = new DefaultHttpClient();

SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

// Set verifier     
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

// Example send http request
final String url = "https://encrypted.google.com/";  
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost);

Set today's date as default date in jQuery UI datepicker

Its very simple you just add this script,

$("#mydate").datepicker({ dateFormat: "yy-mm-dd"}).datepicker("setDate", new Date());

Here, setDate set today date & dateFormat define which format you want set or show.

Hope its simple script work..

Get the current URL with JavaScript?

For complete URL with query strings:

document.location.toString().toLowerCase();

For host URL:

window.location

Initial bytes incorrect after Java AES/CBC decryption

It's often the good idea to rely on standard library provided solution:

private static void stackOverflow15554296()
    throws
        NoSuchAlgorithmException, NoSuchPaddingException,        
        InvalidKeyException, IllegalBlockSizeException,
        BadPaddingException
{

    // prepare key
    KeyGenerator keygen = KeyGenerator.getInstance("AES");
    SecretKey aesKey = keygen.generateKey();
    String aesKeyForFutureUse = Base64.getEncoder().encodeToString(
            aesKey.getEncoded()
    );

    // cipher engine
    Cipher aesCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

    // cipher input
    aesCipher.init(Cipher.ENCRYPT_MODE, aesKey);
    byte[] clearTextBuff = "Text to encode".getBytes();
    byte[] cipherTextBuff = aesCipher.doFinal(clearTextBuff);

    // recreate key
    byte[] aesKeyBuff = Base64.getDecoder().decode(aesKeyForFutureUse);
    SecretKey aesDecryptKey = new SecretKeySpec(aesKeyBuff, "AES");

    // decipher input
    aesCipher.init(Cipher.DECRYPT_MODE, aesDecryptKey);
    byte[] decipheredBuff = aesCipher.doFinal(cipherTextBuff);
    System.out.println(new String(decipheredBuff));
}

This prints "Text to encode".

Solution is based on Java Cryptography Architecture Reference Guide and https://stackoverflow.com/a/20591539/146745 answer.

How to convert a String into an ArrayList?

 String s1="[a,b,c,d]";
 String replace = s1.replace("[","");
 System.out.println(replace);
 String replace1 = replace.replace("]","");
 System.out.println(replace1);
 List<String> myList = new ArrayList<String>(Arrays.asList(replace1.split(",")));
 System.out.println(myList.toString());

receiving json and deserializing as List of object at spring mvc controller

Here is the code that works for me. The key is that you need a wrapper class.

public class Person {

    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }

A PersonWrapper class

public class PersonWrapper {

    private List<Person> persons;

    /**
     * @return the persons
     */
    public List<Person> getPersons() {
        return persons;
    }

    /**
     * @param persons the persons to set
     */
    public void setPersons(List<Person> persons) {
        this.persons = persons;
    }
}

My Controller methods

@RequestMapping(value="person", method=RequestMethod.POST,consumes="application/json",produces="application/json")
    @ResponseBody
    public List<String> savePerson(@RequestBody PersonWrapper wrapper) {
        List<String> response = new ArrayList<String>();
        for (Person person: wrapper.getPersons()){
        personService.save(person);
         response.add("Saved person: " + person.toString());
    }
        return response;
    }

The request sent is json in POST

{"persons":[{"name":"shail1","age":"2"},{"name":"shail2","age":"3"}]}

And the response is

["Saved person: Person [name=shail1, age=2]","Saved person: Person [name=shail2, age=3]"]

Finding sum of elements in Swift array

A possible solution: define a prefix operator for it. Like the reduce "+/" operator as in APL (e.g. GNU APL)

A bit of a different approach here.

Using a protocol en generic type allows us to to use this operator on Double, Float and Int array types

protocol Number 
{
   func +(l: Self, r: Self) -> Self
   func -(l: Self, r: Self) -> Self
   func >(l: Self, r: Self) -> Bool
   func <(l: Self, r: Self) -> Bool
}

extension Double : Number {}
extension Float  : Number {}
extension Int    : Number {}

infix operator += {}

func += <T:Number> (inout left: T, right: T)
{
   left = left + right
}

prefix operator +/ {}

prefix func +/ <T:Number>(ar:[T]?) -> T?
{
    switch true
    {
    case ar == nil:
        return nil

    case ar!.isEmpty:
        return nil

    default:
        var result = ar![0]
        for n in 1..<ar!.count
        {
            result += ar![n]
        }
        return result
   }
}

use like so:

let nmbrs = [ 12.4, 35.6, 456.65, 43.45 ]
let intarr = [1, 34, 23, 54, 56, -67, 0, 44]

+/nmbrs     // 548.1
+/intarr    // 145

(updated for Swift 2.2, tested in Xcode Version 7.3)

docker command not found even though installed with apt-get

The Ubuntu package docker actually refers to a GUI application, not the beloved DevOps tool we've come out to look for.

The instructions for docker can be followed per instructions on the docker page here: https://docs.docker.com/engine/install/ubuntu/

=== UPDATED (thanks @Scott Stensland) ===

You now run the following install script to get docker:

`sudo curl -sSL https://get.docker.com/ | sh`
  • Note: review the script on the website and make sure you have the right link before continuing since you are running this as sudo.

This will run a script that installs docker. Note the last part of the script:

If you would like to use Docker as a non-root user, you should now consider
adding your user to the "docker" group with something like:

  `sudo usermod -aG docker stens`

Remember that you will have to log out and back in for this to take effect!

To update Docker run:

`sudo apt-get update && sudo apt-get upgrade`

For more details on what's going on, See the docker install documentation or @Scott Stensland's answer below

.

=== UPDATE: For those uncomfortable w/ sudo | sh ===

Some in the comments have mentioned that it a risk to run an arbitrary script as sudo. The above option is a convenience script from docker to make the task simple. However, for those that are security-focused but don't want to read the script you can do the following:

  1. Add Dependencies
sudo apt-get update; \
sudo apt-get install \
 apt-transport-https \
 ca-certificates \
 curl \
 gnupg-agent \
 software-properties-common
  1. Add docker gpg key

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

(Security check, verify key fingerprint 9DC8 5822 9FC7 DD38 854A E2D8 8D81 803C 0EBF CD88

$ sudo apt-key fingerprint 0EBFCD88

pub   rsa4096 2017-02-22 [SCEA]
      9DC8 5822 9FC7 DD38 854A  E2D8 8D81 803C 0EBF CD88
uid           [ unknown] Docker Release (CE deb) <[email protected]>
sub   rsa4096 2017-02-22 [S]

)

  1. Setup Repository
sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"
  1. Install Docker
sudo apt-get update; \
sudo apt-get install docker-ce docker-ce-cli containerd.io

If you want to verify that it worked run: sudo docker run hello-world


The following explains why it is named like this: Why install docker on ubuntu should be `sudo apt-get install docker.io`?

How do I count the number of rows and columns in a file using bash?

Little twist to kirill_igum's answer, and you can easily count the number of columns of any certain row you want, which was why I've come to this question, even though the question is asking for the whole file. (Though if your file has same columns in each line this also still works of course):

head -2 file |tail -1 |tr '\t' '\n' |wc -l

Gives the number of columns of row 2. Replace 2 with 55 for example to get it for row 55.

-bash-4.2$ cat file
1       2       3
1       2       3       4
1       2
1       2       3       4       5

-bash-4.2$ head -1 file |tail -1 |tr '\t' '\n' |wc -l
3
-bash-4.2$ head -4 file |tail -1 |tr '\t' '\n' |wc -l
5

Code above works if your file is separated by tabs, as we define it to "tr". If your file has another separator, say commas, you can still count your "columns" using the same trick by simply changing the separator character "t" to ",":

-bash-4.2$ cat csvfile
1,2,3,4
1,2
1,2,3,4,5
-bash-4.2$ head -2 csvfile |tail -1 |tr '\,' '\n' |wc -l
2

List of installed gems?

The Gem command is included with Ruby 1.9+ now, and is a standard addition to Ruby pre-1.9.

require 'rubygems'

name = /^/i
dep = Gem::Dependency.new(name, Gem::Requirement.default)
specs = Gem.source_index.search(dep)
puts specs[0..5].map{ |s| "#{s.name} #{s.version}" }
# >> Platform 0.4.0
# >> abstract 1.0.0
# >> actionmailer 3.0.5
# >> actionpack 3.0.5
# >> activemodel 3.0.5
# >> activerecord 3.0.5

Here's an updated way to get a list:

require 'rubygems'

def local_gems
   Gem::Specification.sort_by{ |g| [g.name.downcase, g.version] }.group_by{ |g| g.name }
end

Because local_gems relies on group_by, it returns a hash of the gems, where the key is the gem's name, and the value is an array of the gem specifications. The value is an array of the instances of that gem that is installed, sorted by the version number.

That makes it possible to do things like:

my_local_gems = local_gems()

my_local_gems['actionmailer']
# => [Gem::Specification.new do |s|
#       s.authors = ["David Heinemeier Hansson"]
#       s.date = Time.utc(2013, 12, 3)
#       s.dependencies = [Gem::Dependency.new("actionpack",
#         Gem::Requirement.new(["= 4.0.2"]),
#         :runtime),
#        Gem::Dependency.new("mail",
#         Gem::Requirement.new(["~> 2.5.4"]),
#         :runtime)]
#       s.description = "Email on Rails. Compose, deliver, receive, and test emails using the familiar controller/view pattern. First-class support for multipart email and attachments."
#       s.email = "[email protected]"
#       s.homepage = "http://www.rubyonrails.org"
#       s.licenses = ["MIT"]
#       s.name = "actionmailer"
#       s.require_paths = ["lib"]
#       s.required_ruby_version = Gem::Requirement.new([">= 1.9.3"])
#       s.requirements = ["none"]
#       s.rubygems_version = "2.0.14"
#       s.specification_version = 4
#       s.summary = "Email composition, delivery, and receiving framework (part of Rails)."
#       s.version = Gem::Version.new("4.0.2")
#       end]

And:

puts my_local_gems.map{ |name, specs| 
  [ 
    name,
    specs.map{ |spec| spec.version.to_s }.join(',')
  ].join(' ') 
}
# >> actionmailer 4.0.2
...
# >> arel 4.0.1,5.0.0
...
# >> ZenTest 4.9.5
# >> zucker 13.1

The last example is similar to the gem query --local command-line, only you have access to all the information for a particular gem's specification.

How to get the nth occurrence in a string?

I was playing around with the following code for another question on StackOverflow and thought that it might be appropriate for here. The function printList2 allows the use of a regex and lists all the occurrences in order. (printList was an attempt at an earlier solution, but it failed in a number of cases.)

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
<title>Checking regex</title>_x000D_
<script>_x000D_
var string1 = "123xxx5yyy1234ABCxxxabc";_x000D_
var search1 = /\d+/;_x000D_
var search2 = /\d/;_x000D_
var search3 = /abc/;_x000D_
function printList(search) {_x000D_
   document.writeln("<p>Searching using regex: " + search + " (printList)</p>");_x000D_
   var list = string1.match(search);_x000D_
   if (list == null) {_x000D_
      document.writeln("<p>No matches</p>");_x000D_
      return;_x000D_
   }_x000D_
   // document.writeln("<p>" + list.toString() + "</p>");_x000D_
   // document.writeln("<p>" + typeof(list1) + "</p>");_x000D_
   // document.writeln("<p>" + Array.isArray(list1) + "</p>");_x000D_
   // document.writeln("<p>" + list1 + "</p>");_x000D_
   var count = list.length;_x000D_
   document.writeln("<ul>");_x000D_
   for (i = 0; i < count; i++) {_x000D_
      document.writeln("<li>" +  "  " + list[i] + "   length=" + list[i].length + _x000D_
          " first position=" + string1.indexOf(list[i]) + "</li>");_x000D_
   }_x000D_
   document.writeln("</ul>");_x000D_
}_x000D_
function printList2(search) {_x000D_
   document.writeln("<p>Searching using regex: " + search + " (printList2)</p>");_x000D_
   var index = 0;_x000D_
   var partial = string1;_x000D_
   document.writeln("<ol>");_x000D_
   for (j = 0; j < 100; j++) {_x000D_
       var found = partial.match(search);_x000D_
       if (found == null) {_x000D_
          // document.writeln("<p>not found</p>");_x000D_
          break;_x000D_
       }_x000D_
       var size = found[0].length;_x000D_
       var loc = partial.search(search);_x000D_
       var actloc = loc + index;_x000D_
       document.writeln("<li>" + found[0] + "  length=" + size + "  first position=" + actloc);_x000D_
       // document.writeln("  " + partial + "  " + loc);_x000D_
       partial = partial.substring(loc + size);_x000D_
       index = index + loc + size;_x000D_
       document.writeln("</li>");_x000D_
   }_x000D_
   document.writeln("</ol>");_x000D_
_x000D_
}_x000D_
</script>_x000D_
</head>_x000D_
<body>_x000D_
<p>Original string is <script>document.writeln(string1);</script></p>_x000D_
<script>_x000D_
   printList(/\d+/g);_x000D_
   printList2(/\d+/);_x000D_
   printList(/\d/g);_x000D_
   printList2(/\d/);_x000D_
   printList(/abc/g);_x000D_
   printList2(/abc/);_x000D_
   printList(/ABC/gi);_x000D_
   printList2(/ABC/i);_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

LINQ: Distinct values

Since we are talking about having every element exactly once, a "set" makes more sense to me.

Example with classes and IEqualityComparer implemented:

 public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public Product(int x, string y)
        {
            Id = x;
            Name = y;
        }
    }

    public class ProductCompare : IEqualityComparer<Product>
    {
        public bool Equals(Product x, Product y)
        {  //Check whether the compared objects reference the same data.
            if (Object.ReferenceEquals(x, y)) return true;

            //Check whether any of the compared objects is null.
            if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
                return false;

            //Check whether the products' properties are equal.
            return x.Id == y.Id && x.Name == y.Name;
        }
        public int GetHashCode(Product product)
        {
            //Check whether the object is null
            if (Object.ReferenceEquals(product, null)) return 0;

            //Get hash code for the Name field if it is not null.
            int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode();

            //Get hash code for the Code field.
            int hashProductCode = product.Id.GetHashCode();

            //Calculate the hash code for the product.
            return hashProductName ^ hashProductCode;
        }
    }

Now

List<Product> originalList = new List<Product> {new Product(1, "ad"), new Product(1, "ad")};
var setList = new HashSet<Product>(originalList, new ProductCompare()).ToList();

setList will have unique elements

I thought of this while dealing with .Except() which returns a set-difference

REST API - file (ie images) processing - best practices

OP here (I am answering this question after two years, the post made by Daniel Cerecedo was not bad at a time, but the web services are developing very fast)

After three years of full-time software development (with focus also on software architecture, project management and microservice architecture) I definitely choose the second way (but with one general endpoint) as the best one.

If you have a special endpoint for images, it gives you much more power over handling those images.

We have the same REST API (Node.js) for both - mobile apps (iOS/android) and frontend (using React). This is 2017, therefore you don't want to store images locally, you want to upload them to some cloud storage (Google cloud, s3, cloudinary, ...), therefore you want some general handling over them.

Our typical flow is, that as soon as you select an image, it starts uploading on background (usually POST on /images endpoint), returning you the ID after uploading. This is really user-friendly, because user choose an image and then typically proceed with some other fields (i.e. address, name, ...), therefore when he hits "send" button, the image is usually already uploaded. He does not wait and watching the screen saying "uploading...".

The same goes for getting images. Especially thanks to mobile phones and limited mobile data, you don't want to send original images, you want to send resized images, so they do not take that much bandwidth (and to make your mobile apps faster, you often don't want to resize it at all, you want the image that fits perfectly into your view). For this reason, good apps are using something like cloudinary (or we do have our own image server for resizing).

Also, if the data are not private, then you send back to app/frontend just URL and it downloads it from cloud storage directly, which is huge saving of bandwidth and processing time for your server. In our bigger apps there are a lot of terabytes downloaded every month, you don't want to handle that directly on each of your REST API server, which is focused on CRUD operation. You want to handle that at one place (our Imageserver, which have caching etc.) or let cloud services handle all of it.


Cons : The only "cons" which you should think of is "not assigned images". User select images and continue with filling other fields, but then he says "nah" and turn off the app or tab, but meanwhile you successfully uploaded the image. This means you have uploaded an image which is not assigned anywhere.

There are several ways of handling this. The most easiest one is "I don't care", which is a relevant one, if this is not happening very often or you even have desire to store every image user send you (for any reason) and you don't want any deletion.

Another one is easy too - you have CRON and i.e. every week and you delete all unassigned images older than one week.

VirtualBox: mount.vboxsf: mounting failed with the error: No such device

I have similar issue, check header if it's not match then run below command

CentOS: sudo yum update && sudo yum -y install kernel-headers kernel-devel

Pull new updates from original GitHub repository into forked GitHub repository

If you're using the GitHub desktop application, there is a synchronise button on the top right corner. Click on it then Update from <original repo> near top left.

If there are no changes to be synchronised, this will be inactive.

Here are some screenshots to make this easy.

How do I read a specified line in a text file?

No unfortunately there is not. At the raw level files do not work on a line number basis. Instead they work at a position / offset basis. The root filesystem has no concept of lines. It's a concept added by higher level components.

So there is no way to tell the operating system, please open file at line blah. Instead you have to open the file and skip around counting new lines until you've passed the specified number. Then store the next set of bytes into an array until you hit the next new line.

How to vertically center content with variable height within a div?

This is something I have needed to do many times and a consistent solution still requires you add a little non-semantic markup and some browser specific hacks. When we get browser support for css 3 you'll get your vertical centering without sinning.

For a better explanation of the technique you can look the article I adapted it from, but basically it involves adding an extra element and applying different styles in IE and browsers that support position:table\table-cell on non-table elements.

<div class="valign-outer">
    <div class="valign-middle">
        <div class="valign-inner">
            Excuse me. What did you sleep in your clothes again last night. Really. You're gonna be in the car with her. Hey, not too early I sleep in on Saturday. Oh, McFly, your shoe's untied. Don't be so gullible, McFly. You got the place fixed up nice, McFly. I have you're car towed all the way to your house and all you've got for me is light beer. What are you looking at, butthead. Say hi to your mom for me.
        </div>
    </div>
</div>

<style>
    /* Non-structural styling */
    .valign-outer { height: 400px; border: 1px solid red; }
    .valign-inner { border: 1px solid blue; }
</style>

<!--[if lte IE 7]>
<style>
    /* For IE7 and earlier */
    .valign-outer { position: relative; overflow: hidden; }
    .valign-middle { position: absolute; top: 50%; }
    .valign-inner { position: relative; top: -50% }
</style>
<![endif]-->
<!--[if gt IE 7]> -->
<style>
    /* For other browsers */
    .valign-outer { position: static; display: table; overflow: hidden; }
    .valign-middle { position: static; display: table-cell; vertical-align: middle; width: 100%; }
</style>

There are many ways (hacks) to apply styles in specific sets of browsers. I used conditional comments but look at the article linked above to see two other techniques.

Note: There are simple ways to get vertical centering if you know some heights in advance, if you are trying to center a single line of text, or in several other cases. If you have more details then throw them in because there may be a method that doesn't require browser hacks or non-semantic markup.

Update: We are beginning to get better browser support for CSS3, bringing both flex-box and transforms as alternative methods for getting vertical centering (among other effects). See this other question for more information about modern methods, but keep in mind that browser support is still sketchy for CSS3.

MySQL : ERROR 1215 (HY000): Cannot add foreign key constraint

foreign key (dept_name) references department

This syntax is not valid for MySQL. It should instead be:

foreign key (dept_name) references department(dept_name)

MySQL requires dept_name to be used twice. Once to define the foreign column, and once to define the primary column.

13.1.17.2. Using FOREIGN KEY Constraints

... [the] essential syntax for a foreign key constraint definition in a CREATE TABLE or ALTER TABLE statement looks like this:

[CONSTRAINT [symbol]] FOREIGN KEY
    [index_name] (index_col_name, ...)
    REFERENCES tbl_name (index_col_name, ...)
    [ON DELETE reference_option]
    [ON UPDATE reference_option]

reference_option:
    RESTRICT | CASCADE | SET NULL | NO ACTION

How to show code but hide output in RMarkdown?

The results = 'hide' option doesn't prevent other messages to be printed. To hide them, the following options are useful:

  • {r, error=FALSE}
  • {r, warning=FALSE}
  • {r, message=FALSE}

In every case, the corresponding warning, error or message will be printed to the console instead.

"unmappable character for encoding" warning in Java

put this line in yor file .gradle above the Java conf.

apply plugin: 'java'
compileJava {options.encoding = "UTF-8"}   

HTML/CSS: how to put text both right and left aligned in a paragraph

Ok what you probably want will be provide to you by result of:

  1. in CSS:

    div { column-count: 2; }

  2. in html:

    <div> some text, bla bla bla </div>

In CSS you make div to split your paragraph on to column, you can make them 3, 4...

If you want to have many differend paragraf like that, then put id or class in your div:

How to pattern match using regular expression in Scala?

To expand a little on Andrew's answer: The fact that regular expressions define extractors can be used to decompose the substrings matched by the regex very nicely using Scala's pattern matching, e.g.:

val Process = """([a-cA-C])([^\s]+)""".r // define first, rest is non-space
for (p <- Process findAllIn "aha bah Cah dah") p match {
  case Process("b", _) => println("first: 'a', some rest")
  case Process(_, rest) => println("some first, rest: " + rest)
  // etc.
}

Ruby Hash to array of values

hash  = { :a => ["a", "b", "c"], :b => ["b", "c"] }
hash.values #=> [["a","b","c"],["b","c"]]

SQL Server: Database stuck in "Restoring" state

OK, I have similar problem and exactly as it was in case of Pauk, it was caused by the server running out of disk space while restoring and so caused a permanent restoring state. How to end this state without stopping SQL Server services?

I have found a solution :)

Drop database *dbname*

MySQL parameterized queries

Here is another way to do it. It's documented on the MySQL official website. https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html

In the spirit, it's using the same mechanic of @Trey Stout's answer. However, I find this one prettier and more readable.

insert_stmt = (
  "INSERT INTO employees (emp_no, first_name, last_name, hire_date) "
  "VALUES (%s, %s, %s, %s)"
)
data = (2, 'Jane', 'Doe', datetime.date(2012, 3, 23))
cursor.execute(insert_stmt, data)

And to better illustrate any need for variables:

NB: note the escape being done.

employee_id = 2
first_name = "Jane"
last_name = "Doe"

insert_stmt = (
  "INSERT INTO employees (emp_no, first_name, last_name, hire_date) "
  "VALUES (%s, %s, %s, %s)"
)
data = (employee_id, conn.escape_string(first_name), conn.escape_string(last_name), datetime.date(2012, 3, 23))
cursor.execute(insert_stmt, data)

Python loop to run for certain amount of seconds

try this:

import time
import os

n = 0
for x in range(10): #enter your value here
    print(n)
    time.sleep(1) #to wait a second
    os.system('cls') #to clear previous number
                     #use ('clear') if you are using linux or mac!
    n = n + 1

Combining the results of two SQL queries as separate columns

You can use a CROSS JOIN:

SELECT *
FROM (  SELECT SUM(Fdays) AS fDaysSum 
        FROM tblFieldDays 
        WHERE tblFieldDays.NameCode=35 
        AND tblFieldDays.WeekEnding=1) A -- use you real query here
CROSS JOIN (SELECT SUM(CHdays) AS hrsSum 
            FROM tblChargeHours 
            WHERE tblChargeHours.NameCode=35 
            AND tblChargeHours.WeekEnding=1) B -- use you real query here

Match multiline text using regular expression

str.matches(regex) behaves like Pattern.matches(regex, str) which attempts to match the entire input sequence against the pattern and returns

true if, and only if, the entire input sequence matches this matcher's pattern

Whereas matcher.find() attempts to find the next subsequence of the input sequence that matches the pattern and returns

true if, and only if, a subsequence of the input sequence matches this matcher's pattern

Thus the problem is with the regex. Try the following.

String test = "User Comments: This is \t a\ta \ntest\n\n message \n";

String pattern1 = "User Comments: [\\s\\S]*^test$[\\s\\S]*";
Pattern p = Pattern.compile(pattern1, Pattern.MULTILINE);
System.out.println(p.matcher(test).find());  //true

String pattern2 = "(?m)User Comments: [\\s\\S]*^test$[\\s\\S]*";
System.out.println(test.matches(pattern2));  //true

Thus in short, the (\\W)*(\\S)* portion in your first regex matches an empty string as * means zero or more occurrences and the real matched string is User Comments: and not the whole string as you'd expect. The second one fails as it tries to match the whole string but it can't as \\W matches a non word character, ie [^a-zA-Z0-9_] and the first character is T, a word character.

I got error "The DELETE statement conflicted with the REFERENCE constraint"

Have you considered applying ON DELETE CASCADE where relevant?

Jquery resizing image

Modifying Aleksandar's answer to make it as jquery plugin and accepts maxwidth and maxheight as arguments, suggested by Nathan.

$.fn.resize = function(maxWidth,maxHeight) {
return this.each(function() {
    var ratio = 0;
    var width = $(this).width();
    var height = $(this).height();
    if(width > maxWidth){
        ratio = maxWidth / width;
        $(this).css("width", maxWidth);
        $(this).css("height", height * ratio);
        height = height * ratio;
    }
    var width = $(this).width();
    var height = $(this).height();
    if(height > maxHeight){
        ratio = maxHeight / height;
        $(this).css("height", maxHeight);
        $(this).css("width", width * ratio);
        width = width * ratio;
    }
});
};

Used as $('.imgClass').resize(300,50);

Working with time DURATION, not time of day

What I wound up doing was: Put time duration in by hand, e.g. 1 min, 03 sec. Simple but effective. It seems Excel overwrote everything else, even when I used the 'custom format' given in some answers.

How can I time a code segment for testing performance with Pythons timeit?

Focus on one specific thing. Disk I/O is slow, so I'd take that out of the test if all you are going to tweak is the database query.

And if you need to time your database execution, look for database tools instead, like asking for the query plan, and note that performance varies not only with the exact query and what indexes you have, but also with the data load (how much data you have stored).

That said, you can simply put your code in a function and run that function with timeit.timeit():

def function_to_repeat():
    # ...

duration = timeit.timeit(function_to_repeat, number=1000)

This would disable the garbage collection, repeatedly call the function_to_repeat() function, and time the total duration of those calls using timeit.default_timer(), which is the most accurate available clock for your specific platform.

You should move setup code out of the repeated function; for example, you should connect to the database first, then time only the queries. Use the setup argument to either import or create those dependencies, and pass them into your function:

def function_to_repeat(var1, var2):
    # ...

duration = timeit.timeit(
    'function_to_repeat(var1, var2)',
    'from __main__ import function_to_repeat, var1, var2', 
    number=1000)

would grab the globals function_to_repeat, var1 and var2 from your script and pass those to the function each repetition.

Add legend to ggplot2 line plot

I tend to find that if I'm specifying individual colours in multiple geom's, I'm doing it wrong. Here's how I would plot your data:

##Subset the necessary columns
dd_sub = datos[,c(20, 2,3,5)]
##Then rearrange your data frame
library(reshape2)
dd = melt(dd_sub, id=c("fecha"))

All that's left is a simple ggplot command:

ggplot(dd) + geom_line(aes(x=fecha, y=value, colour=variable)) +
  scale_colour_manual(values=c("red","green","blue"))

Example plot

enter image description here

How to use su command over adb shell?

The su command does not execute anything, it just raise your privileges.

Try adb shell su -c YOUR_COMMAND.

JavaScript private methods

ES2021 / ES12 - Private Methods

Private method names start with a hash # prefix and can be accessed only inside the class where it is defined.

class Restaurant {

  // private method
  #private_stuff() {
    console.log("private stuff");
  }

  // public method
  buy_food() {
    this.#private_stuff();
  }

};

const restaurant = new Restaurant();
restaurant.buy_food(); // "private stuff";
restaurant.private_stuff(); // Uncaught TypeError: restaurant.private_stuff is not a function

This is an experimental proposal. ECMAScript 2021 version is expected to be released in June 2021.

Copy a table from one database to another in Postgres

You have to use DbLink to copy one table data into another table at different database. You have to install and configure DbLink extension to execute cross database query.

I have already created detailed post on this topic. Please visit this link

How to check the differences between local and github before the pull

And another useful command to do this (after git fetch) is:

git log origin/master ^master

This shows the commits that are in origin/master but not in master. You can also do it in opposite when doing git pull, to check what commits will be submitted to remote.

How to configure Visual Studio to use Beyond Compare

I'm using VS 2017 with projects hosted with Git on visualstudio.com hosting (msdn)

The link above worked for me with the "GITHUB FOR WINDOWS" instructions.

http://www.scootersoftware.com/support.php?zz=kb_vcs#githubwindows

The config file was located where it indicated at "c:\users\username\.gitconfig" and I just changed the BC4's to BC3's for my situation and used the appropriate path:

C:/Program Files (x86)/Beyond Compare 3/bcomp.exe

Input length must be multiple of 16 when decrypting with padded cipher

Had a similar issue. But it is important to understand the root cause and it may vary for different use cases.

Scenario 1
You are trying to decrypt a value which was not encoded correctly in the first place.

byte[] encryptedBytes = Base64.decodeBase64(encryptedBase64String);

If the String is misconfigured for certain reason or has not been encoded correctly, you would see the error " Input length must be multiple of 16 when decrypting with padded cipher"

Scenario 2
Now if by any chance you are using this encoded string in url (trying to pass in the base64Encoded value in url, it will fail. You should do URLEncoding and then pass in the token, it will work.

Scenario 3
When integrating with one of the vendors, we found that we had to do encryption of Base64 using URLEncoder but then we need not decode it because it was done internally by the Vendor

Is there a difference between "==" and "is"?

Your answer is correct. The is operator compares the identity of two objects. The == operator compares the values of two objects.

An object's identity never changes once it has been created; you may think of it as the object's address in memory.

You can control comparison behaviour of object values by defining a __cmp__ method or a rich comparison method like __eq__.

Using PowerShell to remove lines from a text file if it contains a string

The pipe character | has a special meaning in regular expressions. a|b means "match either a or b". If you want to match a literal | character, you need to escape it:

... | Select-String -Pattern 'H\|159' -NotMatch | ...

How to fix nginx throws 400 bad request headers on any header testing tools?

normally, Maxim Donnie's method can find the reason. But I encountered one 400 bad request will not log to err_log. I found the reason with the help with tcpdump

Facebook Open Graph not clearing cache

I've found out that if your image is 72dpi it will give you the image size error. Use 96dpi instead. Hope this helps.

What properties does @Column columnDefinition make redundant?

columnDefinition will override the sql DDL generated by hibernate for this particular column, it is non portable and depends on what database you are using. You can use it to specify nullable, length, precision, scale... ect.

Twitter Bootstrap 3: how to use media queries?

Based on bisio's answer and the Bootstrap 3 code, I was able to come up with a more accurate answer for anyone just looking to copy and paste the complete media query set into their stylesheet:

/* Large desktops and laptops */
@media (min-width: 1200px) {

}

/* Landscape tablets and medium desktops */
@media (min-width: 992px) and (max-width: 1199px) {

}

/* Portrait tablets and small desktops */
@media (min-width: 768px) and (max-width: 991px) {

}

/* Landscape phones and portrait tablets */
@media (max-width: 767px) {

}

/* Portrait phones and smaller */
@media (max-width: 480px) {

}

How do I use 'git reset --hard HEAD' to revert to a previous commit?

First, it's always worth noting that git reset --hard is a potentially dangerous command, since it throws away all your uncommitted changes. For safety, you should always check that the output of git status is clean (that is, empty) before using it.

Initially you say the following:

So I know that Git tracks changes I make to my application, and it holds on to them until I commit the changes, but here's where I'm hung up:

That's incorrect. Git only records the state of the files when you stage them (with git add) or when you create a commit. Once you've created a commit which has your project files in a particular state, they're very safe, but until then Git's not really "tracking changes" to your files. (for example, even if you do git add to stage a new version of the file, that overwrites the previously staged version of that file in the staging area.)

In your question you then go on to ask the following:

When I want to revert to a previous commit I use: git reset --hard HEAD And git returns: HEAD is now at 820f417 micro

How do I then revert the files on my hard drive back to that previous commit?

If you do git reset --hard <SOME-COMMIT> then Git will:

  • Make your current branch (typically master) back to point at <SOME-COMMIT>.
  • Then make the files in your working tree and the index ("staging area") the same as the versions committed in <SOME-COMMIT>.

HEAD points to your current branch (or current commit), so all that git reset --hard HEAD will do is to throw away any uncommitted changes you have.

So, suppose the good commit that you want to go back to is f414f31. (You can find that via git log or any history browser.) You then have a few different options depending on exactly what you want to do:

  • Change your current branch to point to the older commit instead. You could do that with git reset --hard f414f31. However, this is rewriting the history of your branch, so you should avoid it if you've shared this branch with anyone. Also, the commits you did after f414f31 will no longer be in the history of your master branch.
  • Create a new commit that represents exactly the same state of the project as f414f31, but just adds that on to the history, so you don't lose any history. You can do that using the steps suggested in this answer - something like:

    git reset --hard f414f31
    git reset --soft HEAD@{1}
    git commit -m "Reverting to the state of the project at f414f31"
    

Set a default font for whole iOS app?

Am using like this type of font class in swift. Using font extension class.

enum FontName: String {

  case regular      = "Roboto-Regular"

}

//MARK: - Set Font Size
enum FontSize: CGFloat {
    case size = 10

}
extension UIFont {

    //MARK: - Bold Font
  class var regularFont10: UIFont {
        return UIFont(name: FontName.regular.rawValue, size:FontSize.size.rawValue )!
    }
}

How do you rename a Git tag?

As an add on to the other answers, I added an alias to do it all in one step, with a more familiar *nix move command feel. Argument 1 is the old tag name, argument 2 is the new tag name.

[alias]
    renameTag = "!sh -c 'set -e;git tag $2 $1; git tag -d $1;git push origin :refs/tags/$1;git push --tags' -"

Usage:

git renametag old new

Eclipse count lines of code

I created a Eclipse plugin, which can count the lines of source code. It support Kotlin, Java, Java Script, JSP, XML, C/C++, C#, and many other file types.

Please take a look at it. Any feedback would be appreciated!

the git-hub repository is here

Add / remove input field dynamically with jQuery

Another solution could be:

<script>
$(document)
        .ready(
                function() {
                    var wrapper = $(".myFields");
                    $(add_button)
                            .click(
                                    function(e) {
                                        e.preventDefault();
                                        $(wrapper)
                                                .append(
                                                        '.....'); //add fields here
                                    });
                    $(wrapper).on("click", ".delFld", function(e) {
                        e.preventDefault();
                        $(this).parent('div').remove();
                    })
                }); 
</script>

Source: Here

Using ChildActionOnly in MVC

You would use it if you are using RenderAction in any of your views, usually to render a partial view.

The reason for marking it with [ChildActionOnly] is that you need the controller method to be public so you can call it with RenderAction but you don't want someone to be able to navigate to a URL (e.g. /Controller/SomeChildAction) and see the results of that action directly.

Groovy - How to compare the string?

This line:

if(str2==${str}){

Should be:

if( str2 == str ) {

The ${ and } will give you a parse error, as they should only be used inside Groovy Strings for templating

How to put attributes via XElement

Add XAttribute in the constructor of the XElement, like

new XElement("Conn", new XAttribute("Server", comboBox1.Text));

You can also add multiple attributes or elements via the constructor

new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));

or you can use the Add-Method of the XElement to add attributes

XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);

Executing "SELECT ... WHERE ... IN ..." using MySQLdb

this works for me:

myTuple= tuple(myList)
sql="select fooid from foo where bar in "+str(myTuple)
cursor.execute(sql)

How can I sort a List alphabetically?

In one line, using Java 8:

list.sort(Comparator.naturalOrder());

Open file dialog box in JavaScript

Actually, you don't need all that stuff with opacity, visibility, <input> styling, etc. Just take a look:

<a href="#">Just click me.</a>
<script type="text/javascript">
    $("a").click(function() {
        // creating input on-the-fly
        var input = $(document.createElement("input"));
        input.attr("type", "file");
        // add onchange handler if you wish to get the file :)
        input.trigger("click"); // opening dialog
        return false; // avoiding navigation
    });
</script>

Demo on jsFiddle. Tested in Chrome 30.0 and Firefox 24.0. Didn't work in Opera 12.16, however.

Learning Ruby on Rails

I program with RoR on the Mac OS with textmate, and it's awesome.

I would suggest "Programming Ruby 1.9" (The Pickaxe Book) for Ruby and Agile Web Development with Rails" to learn Rails, both published by the Pragmatic Bookshelf.

Good luck!

String formatting: % vs. .format vs. string literal

Something that the modulo operator ( % ) can't do, afaik:

tu = (12,45,22222,103,6)
print '{0} {2} {1} {2} {3} {2} {4} {2}'.format(*tu)

result

12 22222 45 22222 103 22222 6 22222

Very useful.

Another point: format(), being a function, can be used as an argument in other functions:

li = [12,45,78,784,2,69,1254,4785,984]
print map('the number is {}'.format,li)   

print

from datetime import datetime,timedelta

once_upon_a_time = datetime(2010, 7, 1, 12, 0, 0)
delta = timedelta(days=13, hours=8,  minutes=20)

gen =(once_upon_a_time +x*delta for x in xrange(20))

print '\n'.join(map('{:%Y-%m-%d %H:%M:%S}'.format, gen))

Results in:

['the number is 12', 'the number is 45', 'the number is 78', 'the number is 784', 'the number is 2', 'the number is 69', 'the number is 1254', 'the number is 4785', 'the number is 984']

2010-07-01 12:00:00
2010-07-14 20:20:00
2010-07-28 04:40:00
2010-08-10 13:00:00
2010-08-23 21:20:00
2010-09-06 05:40:00
2010-09-19 14:00:00
2010-10-02 22:20:00
2010-10-16 06:40:00
2010-10-29 15:00:00
2010-11-11 23:20:00
2010-11-25 07:40:00
2010-12-08 16:00:00
2010-12-22 00:20:00
2011-01-04 08:40:00
2011-01-17 17:00:00
2011-01-31 01:20:00
2011-02-13 09:40:00
2011-02-26 18:00:00
2011-03-12 02:20:00

How to use private Github repo as npm dependency

I wasn't able to make the accepted answer work in a Docker container.

What worked for me was to set the Personal Access Token from github in a file .nextrc

ARG GITHUB_READ_TOKEN
RUN echo -e "machine github.com\n  login $GITHUB_READ_TOKEN" > ~/.netrc 
RUN npm install --only=production --force \
  && npm cache clean --force
RUN rm ~/.netrc

in package.json

"my-lib": "github:username/repo",

Pandas dataframe get first row of each group

>>> df.groupby('id').first()
     value
id        
1    first
2    first
3    first
4   second
5    first
6    first
7   fourth

If you need id as column:

>>> df.groupby('id').first().reset_index()
   id   value
0   1   first
1   2   first
2   3   first
3   4  second
4   5   first
5   6   first
6   7  fourth

To get n first records, you can use head():

>>> df.groupby('id').head(2).reset_index(drop=True)
    id   value
0    1   first
1    1  second
2    2   first
3    2  second
4    3   first
5    3   third
6    4  second
7    4   fifth
8    5   first
9    6   first
10   6  second
11   7  fourth
12   7   fifth

How to output numbers with leading zeros in JavaScript?

You could extend the Number object:

Number.prototype.pad = function(size) {
    var s = String(this);
    while (s.length < (size || 2)) {s = "0" + s;}
    return s;
}

Examples:

(9).pad();  //returns "09"

(7).pad(3);  //returns "007"

CSS to select/style first word

Pure CSS solution:

Use the :first-line pseudo-class.

display:block;
Width:40-100px; /* just enough for one word, depends on font size */
Overflow:visible; /* so longer words don't get clipped.*/
float:left; /* so it will flow with the paragraph. */
position:relative; /* for typeset adjustments. */

Didn't test that. Pretty sure it will work fine for you tho. I've applied block rules to pseudo-classes before. You might be stuck with a fixed width for every first word, so text-align:center; and give it a nice background or something to deal with the negative space.

Hope that works for you. :)

-Motekye

Secure FTP using Windows batch script

    ftps -a -z -e:on -pfxfile:"S-PID.p12" -pfxpwfile:"S-PID.p12.pwd" -user:<S-PID number> -s:script <RemoteServerName> 2121

S-PID.p12 => certificate file name ;
S-PID.p12.pwd => certificate password file name ; 
RemoteServerName =>  abcd123 ; 
2121 => port number ; 
ftps => command is part of ftps client software ; 

Python speed testing - Time Difference - milliseconds

start = datetime.now() 

#code for which response time need to be measured.

end = datetime.now()
dif = end - start
dif_micro = dif.microseconds # time in microseconds
dif_millis = dif.microseconds / 1000 # time in millisseconds

creating Hashmap from a JSON String

This is simple operation no need to use any external library.

You can use this class instead :) (handles even lists , nested lists and json)

public class Utility {

    public static Map<String, Object> jsonToMap(Object json) throws JSONException {

        if(json instanceof JSONObject)
            return _jsonToMap_((JSONObject)json) ;

        else if (json instanceof String)
        {
            JSONObject jsonObject = new JSONObject((String)json) ;
            return _jsonToMap_(jsonObject) ;
        }
        return null ;
    }


   private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
        Map<String, Object> retMap = new HashMap<String, Object>();

        if(json != JSONObject.NULL) {
            retMap = toMap(json);
        }
        return retMap;
    }


    private static Map<String, Object> toMap(JSONObject object) throws JSONException {
        Map<String, Object> map = new HashMap<String, Object>();

        Iterator<String> keysItr = object.keys();
        while(keysItr.hasNext()) {
            String key = keysItr.next();
            Object value = object.get(key);

            if(value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }

            else if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            map.put(key, value);
        }
        return map;
    }


    public static List<Object> toList(JSONArray array) throws JSONException {
        List<Object> list = new ArrayList<Object>();
        for(int i = 0; i < array.length(); i++) {
            Object value = array.get(i);
            if(value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }

            else if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            list.add(value);
        }
        return list;
    }
}

To convert your JSON string to hashmap use this :

HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(response)) ;

MySQL: Curdate() vs Now()

For questions like this, it is always worth taking a look in the manual first. Date and time functions in the mySQL manual

CURDATE() returns the DATE part of the current time. Manual on CURDATE()

NOW() returns the date and time portions as a timestamp in various formats, depending on how it was requested. Manual on NOW().

Cloning a private Github repo

As everyone aware about the process of cloning, I would like to add few more things here. Don't worry about special character or writing "@" as "%40" see character encoding

$ git clone https://username:[email protected]/user/repo   

This line can do the job

  1. Suppose if I have a password containing special character ( I don't know what to replace for '@' in my password)
  2. What if I want to use other temporary password other than my original password

To solve this issue I encourage to use GitHub Developer option to generate Access token. I believe Access token is secure and you wont find any special character.

creating-a-personal-access-token

Now I will write the below code to access my repository.

$ git clone https://username:[email protected]/user/repo

I am just replacing my original password with Access-token, Now I am not worried if some one see my access credential , I can regenerate the token when ever I feel.

Make sure you have checked repo Full control of private repositories here is the snap short

Protecting cells in Excel but allow these to be modified by VBA script

As a workaround, you can create a hidden worksheet, which would hold the changed value. The cell on the visible, protected worksheet should display the value from the hidden worksheet using a simple formula.

You will be able to change the displayed value through the hidden worksheet, while your users won't be able to edit it.

Determine the path of the executing BASH script

Vlad's code is overquoted. Should be:

MY_PATH=`dirname "$0"`
MY_PATH=`( cd "$MY_PATH" && pwd )`

How can I prevent the TypeError: list indices must be integers, not tuple when copying a python list to a numpy array?

Seriously this took my much valuable time but not found solution. Basically if you are taking data from sql then you are converting then you can follow these steps.

rows = cursor.fetchall()---- only tried on single column
dataset=[]
for x in rows:
    dataset.append(float(x[0]))

How can I format a number into a string with leading zeros?

For interpolated strings:

$"Int value: {someInt:D4} or {someInt:0000}. Float: {someFloat: 00.00}"

How to check identical array in most efficient way?

So, what's wrong with checking each element iteratively?

function arraysEqual(arr1, arr2) {
    if(arr1.length !== arr2.length)
        return false;
    for(var i = arr1.length; i--;) {
        if(arr1[i] !== arr2[i])
            return false;
    }

    return true;
}

How to redirect docker container logs to a single file?

Bash script to copy all container logs to a specified directory:

#!/usr/bin/env bash

TARGET_DIR=~/logs/docker_logs
mkdir -p "$TARGET_DIR"
for name in `sudo docker ps --format '{{.Names}}'`;
do
    path=$(sudo docker inspect --format='{{.LogPath}}' $name)
    sudo cp -rf "$path" "$TARGET_DIR"/$name.log
done

Put Excel-VBA code in module or sheet?

In my experience it's best to put as much code as you can into well-named modules, and only put as much code as you need to into the actual worksheet objects.

Example: Any code that uses worksheet events like Worksheet_SelectionChange or Worksheet_Calculate.

Sorting table rows according to table header column using javascript or jquery

I think this might help you:
Here is the JSFiddle demo:

And here is the code:

_x000D_
_x000D_
var stIsIE = /*@cc_on!@*/ false;_x000D_
sorttable = {_x000D_
  init: function() {_x000D_
    if (arguments.callee.done) return;_x000D_
    arguments.callee.done = true;_x000D_
    if (_timer) clearInterval(_timer);_x000D_
    if (!document.createElement || !document.getElementsByTagName) return;_x000D_
    sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;_x000D_
    forEach(document.getElementsByTagName('table'), function(table) {_x000D_
      if (table.className.search(/\bsortable\b/) != -1) {_x000D_
        sorttable.makeSortable(table);_x000D_
      }_x000D_
    });_x000D_
  },_x000D_
  makeSortable: function(table) {_x000D_
    if (table.getElementsByTagName('thead').length == 0) {_x000D_
      the = document.createElement('thead');_x000D_
      the.appendChild(table.rows[0]);_x000D_
      table.insertBefore(the, table.firstChild);_x000D_
    }_x000D_
    if (table.tHead == null) table.tHead = table.getElementsByTagName('thead')[0];_x000D_
    if (table.tHead.rows.length != 1) return;_x000D_
    sortbottomrows = [];_x000D_
    for (var i = 0; i < table.rows.length; i++) {_x000D_
      if (table.rows[i].className.search(/\bsortbottom\b/) != -1) {_x000D_
        sortbottomrows[sortbottomrows.length] = table.rows[i];_x000D_
      }_x000D_
    }_x000D_
    if (sortbottomrows) {_x000D_
      if (table.tFoot == null) {_x000D_
        tfo = document.createElement('tfoot');_x000D_
        table.appendChild(tfo);_x000D_
      }_x000D_
      for (var i = 0; i < sortbottomrows.length; i++) {_x000D_
        tfo.appendChild(sortbottomrows[i]);_x000D_
      }_x000D_
      delete sortbottomrows;_x000D_
    }_x000D_
    headrow = table.tHead.rows[0].cells;_x000D_
    for (var i = 0; i < headrow.length; i++) {_x000D_
      if (!headrow[i].className.match(/\bsorttable_nosort\b/)) {_x000D_
        mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);_x000D_
        if (mtch) {_x000D_
          override = mtch[1];_x000D_
        }_x000D_
        if (mtch && typeof sorttable["sort_" + override] == 'function') {_x000D_
          headrow[i].sorttable_sortfunction = sorttable["sort_" + override];_x000D_
        } else {_x000D_
          headrow[i].sorttable_sortfunction = sorttable.guessType(table, i);_x000D_
        }_x000D_
        headrow[i].sorttable_columnindex = i;_x000D_
        headrow[i].sorttable_tbody = table.tBodies[0];_x000D_
        dean_addEvent(headrow[i], "click", sorttable.innerSortFunction = function(e) {_x000D_
_x000D_
          if (this.className.search(/\bsorttable_sorted\b/) != -1) {_x000D_
            sorttable.reverse(this.sorttable_tbody);_x000D_
            this.className = this.className.replace('sorttable_sorted',_x000D_
              'sorttable_sorted_reverse');_x000D_
            this.removeChild(document.getElementById('sorttable_sortfwdind'));_x000D_
            sortrevind = document.createElement('span');_x000D_
            sortrevind.id = "sorttable_sortrevind";_x000D_
            sortrevind.innerHTML = stIsIE ? '&nbsp<font face="webdings">5</font>' : '&nbsp;&#x25B4;';_x000D_
            this.appendChild(sortrevind);_x000D_
            return;_x000D_
          }_x000D_
          if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {_x000D_
            sorttable.reverse(this.sorttable_tbody);_x000D_
            this.className = this.className.replace('sorttable_sorted_reverse',_x000D_
              'sorttable_sorted');_x000D_
            this.removeChild(document.getElementById('sorttable_sortrevind'));_x000D_
            sortfwdind = document.createElement('span');_x000D_
            sortfwdind.id = "sorttable_sortfwdind";_x000D_
            sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';_x000D_
            this.appendChild(sortfwdind);_x000D_
            return;_x000D_
          }_x000D_
          theadrow = this.parentNode;_x000D_
          forEach(theadrow.childNodes, function(cell) {_x000D_
            if (cell.nodeType == 1) {_x000D_
              cell.className = cell.className.replace('sorttable_sorted_reverse', '');_x000D_
              cell.className = cell.className.replace('sorttable_sorted', '');_x000D_
            }_x000D_
          });_x000D_
          sortfwdind = document.getElementById('sorttable_sortfwdind');_x000D_
          if (sortfwdind) {_x000D_
            sortfwdind.parentNode.removeChild(sortfwdind);_x000D_
          }_x000D_
          sortrevind = document.getElementById('sorttable_sortrevind');_x000D_
          if (sortrevind) {_x000D_
            sortrevind.parentNode.removeChild(sortrevind);_x000D_
          }_x000D_
_x000D_
          this.className += ' sorttable_sorted';_x000D_
          sortfwdind = document.createElement('span');_x000D_
          sortfwdind.id = "sorttable_sortfwdind";_x000D_
          sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';_x000D_
          this.appendChild(sortfwdind);_x000D_
          row_array = [];_x000D_
          col = this.sorttable_columnindex;_x000D_
          rows = this.sorttable_tbody.rows;_x000D_
          for (var j = 0; j < rows.length; j++) {_x000D_
            row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]];_x000D_
          }_x000D_
          row_array.sort(this.sorttable_sortfunction);_x000D_
          tb = this.sorttable_tbody;_x000D_
          for (var j = 0; j < row_array.length; j++) {_x000D_
            tb.appendChild(row_array[j][1]);_x000D_
          }_x000D_
          delete row_array;_x000D_
        });_x000D_
      }_x000D_
    }_x000D_
  },_x000D_
_x000D_
  guessType: function(table, column) {_x000D_
    sortfn = sorttable.sort_alpha;_x000D_
    for (var i = 0; i < table.tBodies[0].rows.length; i++) {_x000D_
      text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]);_x000D_
      if (text != '') {_x000D_
        if (text.match(/^-?[£$¤]?[\d,.]+%?$/)) {_x000D_
          return sorttable.sort_numeric;_x000D_
        }_x000D_
        possdate = text.match(sorttable.DATE_RE)_x000D_
        if (possdate) {_x000D_
          first = parseInt(possdate[1]);_x000D_
          second = parseInt(possdate[2]);_x000D_
          if (first > 12) {_x000D_
            return sorttable.sort_ddmm;_x000D_
          } else if (second > 12) {_x000D_
            return sorttable.sort_mmdd;_x000D_
          } else {_x000D_
            sortfn = sorttable.sort_ddmm;_x000D_
          }_x000D_
        }_x000D_
      }_x000D_
    }_x000D_
    return sortfn;_x000D_
  },_x000D_
  getInnerText: function(node) {_x000D_
    if (!node) return "";_x000D_
    hasInputs = (typeof node.getElementsByTagName == 'function') &&_x000D_
      node.getElementsByTagName('input').length;_x000D_
    if (node.getAttribute("sorttable_customkey") != null) {_x000D_
      return node.getAttribute("sorttable_customkey");_x000D_
    } else if (typeof node.textContent != 'undefined' && !hasInputs) {_x000D_
      return node.textContent.replace(/^\s+|\s+$/g, '');_x000D_
    } else if (typeof node.innerText != 'undefined' && !hasInputs) {_x000D_
      return node.innerText.replace(/^\s+|\s+$/g, '');_x000D_
    } else if (typeof node.text != 'undefined' && !hasInputs) {_x000D_
      return node.text.replace(/^\s+|\s+$/g, '');_x000D_
    } else {_x000D_
      switch (node.nodeType) {_x000D_
        case 3:_x000D_
          if (node.nodeName.toLowerCase() == 'input') {_x000D_
            return node.value.replace(/^\s+|\s+$/g, '');_x000D_
          }_x000D_
        case 4:_x000D_
          return node.nodeValue.replace(/^\s+|\s+$/g, '');_x000D_
          break;_x000D_
        case 1:_x000D_
        case 11:_x000D_
          var innerText = '';_x000D_
          for (var i = 0; i < node.childNodes.length; i++) {_x000D_
            innerText += sorttable.getInnerText(node.childNodes[i]);_x000D_
          }_x000D_
          return innerText.replace(/^\s+|\s+$/g, '');_x000D_
          break;_x000D_
        default:_x000D_
          return '';_x000D_
      }_x000D_
    }_x000D_
  },_x000D_
  reverse: function(tbody) {_x000D_
    // reverse the rows in a tbody_x000D_
    newrows = [];_x000D_
    for (var i = 0; i < tbody.rows.length; i++) {_x000D_
      newrows[newrows.length] = tbody.rows[i];_x000D_
    }_x000D_
    for (var i = newrows.length - 1; i >= 0; i--) {_x000D_
      tbody.appendChild(newrows[i]);_x000D_
    }_x000D_
    delete newrows;_x000D_
  },_x000D_
  sort_numeric: function(a, b) {_x000D_
    aa = parseFloat(a[0].replace(/[^0-9.-]/g, ''));_x000D_
    if (isNaN(aa)) aa = 0;_x000D_
    bb = parseFloat(b[0].replace(/[^0-9.-]/g, ''));_x000D_
    if (isNaN(bb)) bb = 0;_x000D_
    return aa - bb;_x000D_
  },_x000D_
  sort_alpha: function(a, b) {_x000D_
    if (a[0] == b[0]) return 0;_x000D_
    if (a[0] < b[0]) return -1;_x000D_
    return 1;_x000D_
  },_x000D_
  sort_ddmm: function(a, b) {_x000D_
    mtch = a[0].match(sorttable.DATE_RE);_x000D_
    y = mtch[3];_x000D_
    m = mtch[2];_x000D_
    d = mtch[1];_x000D_
    if (m.length == 1) m = '0' + m;_x000D_
    if (d.length == 1) d = '0' + d;_x000D_
    dt1 = y + m + d;_x000D_
    mtch = b[0].match(sorttable.DATE_RE);_x000D_
    y = mtch[3];_x000D_
    m = mtch[2];_x000D_
    d = mtch[1];_x000D_
    if (m.length == 1) m = '0' + m;_x000D_
    if (d.length == 1) d = '0' + d;_x000D_
    dt2 = y + m + d;_x000D_
    if (dt1 == dt2) return 0;_x000D_
    if (dt1 < dt2) return -1;_x000D_
    return 1;_x000D_
  },_x000D_
  sort_mmdd: function(a, b) {_x000D_
    mtch = a[0].match(sorttable.DATE_RE);_x000D_
    y = mtch[3];_x000D_
    d = mtch[2];_x000D_
    m = mtch[1];_x000D_
    if (m.length == 1) m = '0' + m;_x000D_
    if (d.length == 1) d = '0' + d;_x000D_
    dt1 = y + m + d;_x000D_
    mtch = b[0].match(sorttable.DATE_RE);_x000D_
    y = mtch[3];_x000D_
    d = mtch[2];_x000D_
    m = mtch[1];_x000D_
    if (m.length == 1) m = '0' + m;_x000D_
    if (d.length == 1) d = '0' + d;_x000D_
    dt2 = y + m + d;_x000D_
    if (dt1 == dt2) return 0;_x000D_
    if (dt1 < dt2) return -1;_x000D_
    return 1;_x000D_
  },_x000D_
  shaker_sort: function(list, comp_func) {_x000D_
    var b = 0;_x000D_
    var t = list.length - 1;_x000D_
    var swap = true;_x000D_
    while (swap) {_x000D_
      swap = false;_x000D_
      for (var i = b; i < t; ++i) {_x000D_
        if (comp_func(list[i], list[i + 1]) > 0) {_x000D_
          var q = list[i];_x000D_
          list[i] = list[i + 1];_x000D_
          list[i + 1] = q;_x000D_
          swap = true;_x000D_
        }_x000D_
      }_x000D_
      t--;_x000D_
_x000D_
      if (!swap) break;_x000D_
_x000D_
      for (var i = t; i > b; --i) {_x000D_
        if (comp_func(list[i], list[i - 1]) < 0) {_x000D_
          var q = list[i];_x000D_
          list[i] = list[i - 1];_x000D_
          list[i - 1] = q;_x000D_
          swap = true;_x000D_
        }_x000D_
      }_x000D_
      b++;_x000D_
_x000D_
    }_x000D_
  }_x000D_
}_x000D_
if (document.addEventListener) {_x000D_
  document.addEventListener("DOMContentLoaded", sorttable.init, false);_x000D_
}_x000D_
/* for Internet Explorer */_x000D_
/*@cc_on @*/_x000D_
/*@if (@_win32)_x000D_
    document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");_x000D_
    var script = document.getElementById("__ie_onload");_x000D_
    script.onreadystatechange = function() {_x000D_
        if (this.readyState == "complete") {_x000D_
            sorttable.init(); // call the onload handler_x000D_
        }_x000D_
    };_x000D_
/*@end @*/_x000D_
/* for Safari */_x000D_
if (/WebKit/i.test(navigator.userAgent)) { // sniff_x000D_
  var _timer = setInterval(function() {_x000D_
    if (/loaded|complete/.test(document.readyState)) {_x000D_
      sorttable.init(); // call the onload handler_x000D_
    }_x000D_
  }, 10);_x000D_
}_x000D_
/* for other browsers */_x000D_
window.onload = sorttable.init;_x000D_
_x000D_
function dean_addEvent(element, type, handler) {_x000D_
  if (element.addEventListener) {_x000D_
    element.addEventListener(type, handler, false);_x000D_
  } else {_x000D_
    if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++;_x000D_
    if (!element.events) element.events = {};_x000D_
    var handlers = element.events[type];_x000D_
    if (!handlers) {_x000D_
      handlers = element.events[type] = {};_x000D_
      if (element["on" + type]) {_x000D_
        handlers[0] = element["on" + type];_x000D_
      }_x000D_
    }_x000D_
    handlers[handler.$$guid] = handler;_x000D_
    element["on" + type] = handleEvent;_x000D_
  }_x000D_
};_x000D_
dean_addEvent.guid = 1;_x000D_
_x000D_
function removeEvent(element, type, handler) {_x000D_
  if (element.removeEventListener) {_x000D_
    element.removeEventListener(type, handler, false);_x000D_
  } else {_x000D_
    if (element.events && element.events[type]) {_x000D_
      delete element.events[type][handler.$$guid];_x000D_
    }_x000D_
  }_x000D_
};_x000D_
_x000D_
function handleEvent(event) {_x000D_
  var returnValue = true;_x000D_
  event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);_x000D_
  var handlers = this.events[event.type];_x000D_
  for (var i in handlers) {_x000D_
    this.$$handleEvent = handlers[i];_x000D_
    if (this.$$handleEvent(event) === false) {_x000D_
      returnValue = false;_x000D_
    }_x000D_
  }_x000D_
  return returnValue;_x000D_
};_x000D_
_x000D_
function fixEvent(event) {_x000D_
  event.preventDefault = fixEvent.preventDefault;_x000D_
  event.stopPropagation = fixEvent.stopPropagation;_x000D_
  return event;_x000D_
};_x000D_
fixEvent.preventDefault = function() {_x000D_
  this.returnValue = false;_x000D_
};_x000D_
fixEvent.stopPropagation = function() {_x000D_
  this.cancelBubble = true;_x000D_
}_x000D_
if (!Array.forEach) {_x000D_
  Array.forEach = function(array, block, context) {_x000D_
    for (var i = 0; i < array.length; i++) {_x000D_
      block.call(context, array[i], i, array);_x000D_
    }_x000D_
  };_x000D_
}_x000D_
Function.prototype.forEach = function(object, block, context) {_x000D_
  for (var key in object) {_x000D_
    if (typeof this.prototype[key] == "undefined") {_x000D_
      block.call(context, object[key], key, object);_x000D_
    }_x000D_
  }_x000D_
};_x000D_
String.forEach = function(string, block, context) {_x000D_
  Array.forEach(string.split(""), function(chr, index) {_x000D_
    block.call(context, chr, index, string);_x000D_
  });_x000D_
};_x000D_
var forEach = function(object, block, context) {_x000D_
  if (object) {_x000D_
    var resolve = Object;_x000D_
    if (object instanceof Function) {_x000D_
      resolve = Function;_x000D_
    } else if (object.forEach instanceof Function) {_x000D_
      object.forEach(block, context);_x000D_
      return;_x000D_
    } else if (typeof object == "string") {_x000D_
      resolve = String;_x000D_
    } else if (typeof object.length == "number") {_x000D_
      resolve = Array;_x000D_
    }_x000D_
    resolve.forEach(object, block, context);_x000D_
  }_x000D_
}
_x000D_
table.sortable thead {_x000D_
  background-color: #eee;_x000D_
  color: #666666;_x000D_
  font-weight: bold;_x000D_
  cursor: default;_x000D_
}
_x000D_
<table class="sortable">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>S.L.</th>_x000D_
      <th>name</th>_x000D_
      <th>Goal</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>1</td>_x000D_
      <td>Ronaldo</td>_x000D_
      <td>120</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>2</td>_x000D_
      <td>Messi</td>_x000D_
      <td>66</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>3</td>_x000D_
      <td>Ribery</td>_x000D_
      <td>10</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>4</td>_x000D_
      <td>Bale</td>_x000D_
      <td>22</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

JS is used here without any other JQuery Plugin.

libaio.so.1: cannot open shared object file

I had the same problem, and it turned out I hadn't installed the library.

this link was super usefull.

http://help.directadmin.com/item.php?id=368

Start an Activity with a parameter

Just add extra data to the Intent you use to call your activity.

In the caller activity :

Intent i = new Intent(this, TheNextActivity.class);
i.putExtra("id", id);
startActivity(i);

Inside the onCreate() of the activity you call :

Bundle b = getIntent().getExtras();
int id = b.getInt("id");

What is __future__ in Python used for and how/when to use it, and how it works

Or is it like saying "Since this is python v2.7, use that different 'print' function that has also been added to python v2.7, after it was added in python 3. So my 'print' will no longer be statements (eg print "message" ) but functions (eg, print("message", options). That way when my code is run in python 3, 'print' will not break."

In

from __future__ import print_function

print_function is the module containing the new implementation of 'print' as per how it is behaving in python v3.

This has more explanation: http://python3porting.com/noconv.html

How to pass parameters on onChange of html select

This is helped for me.

For select:

$('select_tags').on('change', function() {
    alert( $(this).find(":selected").val() );
});

For radio/checkbox:

$('radio_tags').on('change', function() {
    alert( $(this).find(":checked").val() );
});

Violation Long running JavaScript task took xx ms

In order to identify the source of the problem, run your application, and record it in Chrome's Performance tab.

There you can check various functions that took a long time to run. In my case, the one that correlated with warnings in console was from a file which was loaded by the AdBlock extension, but this could be something else in your case.

Check these files and try to identify if this is some extension's code or yours. (If it is yours, then you have found the source of your problem.)

How can I create a border around an Android LinearLayout?

Try this:

For example, let's define res/drawable/my_custom_background.xml as:

(create this layout in your drawable folder) layout_border.xml

  <?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <stroke android:width="2dp" android:height="2dp"
                android:color="#FF0000" />
            <solid android:color="#000000" />
            <padding android:left="1dp" android:top="1dp" android:right="1dp"
                android:bottom="1dp" />

            <corners android:radius="1dp" android:bottomRightRadius="5dp"
                android:bottomLeftRadius="0dp" android:topLeftRadius="5dp"
                android:topRightRadius="0dp" />
        </shape>
    </item>

</layer-list>

main.xml

<LinearLayout 
    android:layout_gravity="center"
    android:layout_width="200dp" 
    android:layout_height="200dp"   
    android:background="@drawable/layout_border" />
</LinearLayout>

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

Using display: inline-flex

_x000D_
_x000D_
#menu ul {_x000D_
  list-style: none;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  display: inline-flex_x000D_
}
_x000D_
<div id="menu">_x000D_
  <ul>_x000D_
    <li>1 menu item</li>_x000D_
    <li>2 menu item</li>_x000D_
    <li>3 menu item</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using display: inline-block

_x000D_
_x000D_
#menu ul {_x000D_
  list-style: none;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
#menu li {_x000D_
  display: inline-block;_x000D_
}
_x000D_
<div id="menu">_x000D_
  <ul>_x000D_
    <li>1 menu item</li>_x000D_
    <li>2 menu item</li>_x000D_
    <li>3 menu item</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Select rows from a data frame based on values in a vector

Similar to above, using filter from dplyr:

filter(df, fct %in% vc)

Iterating through a List Object in JSP

Before teaching yourself Spring and Struts, you should probably learn Java. Output like this

org.classes.database.Employee@d9b02

is the result of the Object#toString() method which all objects inherit from the Object class, the superclass of all classes in Java.

The List sub classes implement this by iterating over all the elements and calling toString() on those. It seems, however, that you haven't implemented (overriden) the method in your Employee class.

Your JSTL here

<c:forEach items="${eList}" var="employee">
    <tr>
        <td>Employee ID: <c:out value="${employee.eid}"/></td>
        <td>Employee Pass: <c:out value="${employee.ename}"/></td>  
    </tr>
</c:forEach>

is fine except for the fact that you don't have a page, request, session, or application scoped attribute named eList.

You need to add it

<% List eList = (List)session.getAttribute("empList");
   request.setAttribute("eList", eList);
%>

Or use the attribute empList in the forEach.

<c:forEach items="${empList}" var="employee">
    <tr>
        <td>Employee ID: <c:out value="${employee.eid}"/></td>
        <td>Employee Pass: <c:out value="${employee.ename}"/></td>  
    </tr>
</c:forEach>

How to create a DB link between two oracle instances

If you want to access the data in instance B from the instance A. Then this is the query, you can edit your respective credential.

CREATE DATABASE LINK dblink_passport
CONNECT TO xxusernamexx IDENTIFIED BY xxpasswordxx
USING
'(DESCRIPTION=
(ADDRESS=
(PROTOCOL=TCP)
(HOST=xxipaddrxx / xxhostxx )
(PORT=xxportxx))
(CONNECT_DATA=
(SID=xxsidxx)))';

After executing this query access table

SELECT * FROM tablename@dblink_passport;

You can perform any operation DML, DDL, DQL

Matplotlib: Specify format of floats for tick labels

The answer above is probably the correct way to do it, but didn't work for me.

The hacky way that solved it for me was the following:

ax = <whatever your plot is> 
# get the current labels 
labels = [item.get_text() for item in ax.get_xticklabels()]
# Beat them into submission and set them back again
ax.set_xticklabels([str(round(float(label), 2)) for label in labels])
# Show the plot, and go home to family 
plt.show()

How to distinguish mouse "click" and "drag"

I think the difference is that there is a mousemove between mousedown and mouseup in a drag, but not in a click.

You can do something like this:

const element = document.createElement('div')
element.innerHTML = 'test'
document.body.appendChild(element)
let moved
let downListener = () => {
    moved = false
}
element.addEventListener('mousedown', downListener)
let moveListener = () => {
    moved = true
}
element.addEventListener('mousemove', moveListener)
let upListener = () => {
    if (moved) {
        console.log('moved')
    } else {
        console.log('not moved')
    }
}
element.addEventListener('mouseup', upListener)

// release memory
element.removeEventListener('mousedown', downListener)
element.removeEventListener('mousemove', moveListener)
element.removeEventListener('mouseup', upListener)

How find out which process is using a file in Linux?

$ lsof | tree MyFold

As shown in the image attached:

enter image description here

Server cannot set status after HTTP headers have been sent IIS7.5

Just to add to the responses above. I had this same issue when i first started using ASP.Net MVC and i was doing a Response.Redirect during a controller action:

Response.Redirect("/blah", true);

Instead of returning a Response.Redirect action i should have been returning a RedirectAction:

return Redirect("/blah");

Excel add one hour

This may help you as well. This is a conditional statement that will fill the cell with a default date if it is empty but will subtract one hour if it is a valid date/time and put it into the cell.

=IF((Sheet1!C4)="",DATE(1999,1,1),Sheet1!C4-TIME(1,0,0))

You can also substitute TIME with DATE to add or subtract a date or time.

How to open this .DB file?

You can use a tool like the TrIDNet - File Identifier to look for the Magic Number and other telltales, if the file format is in it's database it may tell you what it is for.

However searching the definitions did not turn up anything for the string "FLDB", but it checks more than magic numbers so it is worth a try.

If you are using Linux File is a command that will do a similar task.

The other thing to try is if you have access to the program that generated this file, there may be DLL's or EXE's from the database software that may contain meta information about the dll's creator which could give you a starting point for looking for software that can read the file outside of the program that originally created the .db file.

What is a 'NoneType' object?

Your error's occurring due to something like this:
>>> None + "hello world"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
>>>

Python's None object is roughly equivalent to null, nil, etc. in other languages.

Relay access denied on sending mail, Other domain outside of network

Set your SMTP auth to true if using the PHPmailer class:

$mail->SMTPAuth = true;

How to close IPython Notebook properly?

These commands worked for me:

jupyter notebook list # shows the running notebooks and their port-numbers
                      # (for instance: 8080)
lsof -n -i4TCP:[port-number] # shows PID.
kill -9 [PID] # kill the process.

This answer was adapted from here.

Using Alert in Response.Write Function in ASP.NET

Try using RegisterScriptBlock. Example from the link:

public void Page_Load(Object sender, EventArgs e)
{
    // Define the name and type of the client scripts on the page.
    String csname1 = "PopupScript";
    String csname2 = "ButtonClickScript";
    Type cstype = this.GetType();

    // Get a ClientScriptManager reference from the Page class.
    ClientScriptManager cs = Page.ClientScript;

    // Check to see if the startup script is already registered.
    if (!cs.IsStartupScriptRegistered(cstype, csname1))
    {
      String cstext1 = "alert('Hello World');";
      cs.RegisterStartupScript(cstype, csname1, cstext1, true);
    }

    // Check to see if the client script is already registered.
    if (!cs.IsClientScriptBlockRegistered(cstype, csname2))
    {
      StringBuilder cstext2 = new StringBuilder();
      cstext2.Append("<script type=\"text/javascript\"> function DoClick() {");
      cstext2.Append("Form1.Message.value='Text from client script.'} </");
      cstext2.Append("script>");
      cs.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), false);
    }
}

How to parse date string to Date?

A parse exception is a checked exception, so you must catch it with a try-catch when working with parsing Strings to Dates, as @miku suggested...

npm start error with create-react-app

Yes you should not install react-scripts globally, it will not work.

I think i didn't use the --save when i first created the project (on another machine), so for me this fixed the problem :

npm install --save react react-dom react-scripts

How to serialize a JObject without the formatting?

Call JObject's ToString(Formatting.None) method.

Alternatively if you pass the object to the JsonConvert.SerializeObject method it will return the JSON without formatting.

Documentation: Write JSON text with JToken.ToString

Opening a SQL Server .bak file (Not restoring!)

There is no standard way to do this. You need to use 3rd party tools such as ApexSQL Restore or SQL Virtual Restore. These tools don’t really read the backup file directly. They get SQL Server to “think” of backup files as if these were live databases.

How to determine tables size in Oracle

If you don't have DBA rights then you can use user_segments table:

select bytes/1024/1024 MB from user_segments where segment_name='Table_name'

PHP check if url parameter exists

I know this is an old question, but since php7.0 you can use the null coalescing operator (another resource).

It similar to the ternary operator, but will behave like isset on the lefthand operand instead of just using its boolean value.

$slide = $_GET["id"] ?? 'fallback';

So if $_GET["id"] is set, it returns the value. If not, it returns the fallback. I found this very helpful for $_POST, $_GET, or any passed parameters, etc

$slide = $_GET["id"] ?? '';

if (trim($slide) == 'link1') ...

How to check that Request.QueryString has a specific value or not in ASP.NET?

To check for an empty QueryString you should use Request.QueryString.HasKeys property.

To check if the key is present: Request.QueryString.AllKeys.Contains()

Then you can get ist's Value and do any other check you want, such as isNullOrEmpty, etc.

Double precision - decimal places

It is actually 53 binary places, which translates to 15 stable decimal places, meaning that if you round a start out with a number with 15 decimal places, convert it to a double, and then round the double back to 15 decimal places you'll get the same number. To uniquely represent a double you need 17 decimal places (meaning that for every number with 17 decimal places, there's a unique closest double) which is why 17 places are showing up, but not all 17-decimal numbers map to different double values (like in the examples in the other answers).

Javascript to sort contents of select element

Working with the answers provided by Marco Lazzeri and Terre Porter (vote them up if this answer is useful), I came up with a slightly different solution that preserves the selected value (probably doesn't preserve event handlers or attached data, though) using jQuery.

// save the selected value for sorting
var v = jQuery("#id").val();

// sort the options and select the value that was saved
j$("#id")
    .html(j$("#id option").sort(function(a,b){
        return a.text == b.text ? 0 : a.text < b.text ? -1 : 1;}))
    .val(v);

How to get data from observable in angular2

this.myService.getConfig().subscribe(
  (res) => console.log(res),
  (err) => console.log(err),
  () => console.log('done!')
);

How to export a MySQL database to JSON?

I know this is old, but for the sake of somebody looking for an answer...

There's a JSON library for MYSQL that can be found here You need to have root access to your server and be comfortable installing plugins (it's simple).

1) upload the lib_mysqludf_json.so into the plugins directory of your mysql installation

2) run the lib_mysqludf_json.sql file (it pretty much does all of the work for you. If you run into trouble just delete anything that starts with 'DROP FUNCTION...')

3) encode your query in something like this:

SELECT json_array(
         group_concat(json_object( name, email))
FROM ....
WHERE ...

and it will return something like

[ 
   { 
     "name": "something",
     "email": "[email protected]"
    }, 
   { 
     "name": "someone",
     "email": "[email protected]"
    }

]

How to affect other elements when one element is hovered

If the cube is directly inside the container:

#container:hover > #cube { background-color: yellow; }

If cube is next to (after containers closing tag) the container:

#container:hover + #cube { background-color: yellow; }

If the cube is somewhere inside the container:

#container:hover #cube { background-color: yellow; }

If the cube is a sibling of the container:

#container:hover ~ #cube { background-color: yellow; }

Smart cast to 'Type' is impossible, because 'variable' is a mutable property that could have been changed by this time

The practical reason why this doesn't work is not related to threads. The point is that node.left is effectively translated into node.getLeft().

This property getter might be defined as:

val left get() = if (Math.random() < 0.5) null else leftPtr

Therefore two calls might not return the same result.

How to create two columns on a web page?

Basically you need 3 divs. First as wrapper, second as left and third as right.

.wrapper {
 width:500px;
 overflow:hidden;
}

.left {
 width:250px;
 float:left;
}

.right {
 width:250px;
 float:right;
}

Example how to make 2 columns http://jsfiddle.net/huhu/HDGvN/


CSS Cheat Sheet for reference

How to configure slf4j-simple

This is a sample simplelogger.properties which you can place on the classpath (uncomment the properties you wish to use):

# SLF4J's SimpleLogger configuration file
# Simple implementation of Logger that sends all enabled log messages, for all defined loggers, to System.err.

# Default logging detail level for all instances of SimpleLogger.
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, defaults to "info".
#org.slf4j.simpleLogger.defaultLogLevel=info

# Logging detail level for a SimpleLogger instance named "xxxxx".
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, the default logging detail level is used.
#org.slf4j.simpleLogger.log.xxxxx=

# Set to true if you want the current date and time to be included in output messages.
# Default is false, and will output the number of milliseconds elapsed since startup.
#org.slf4j.simpleLogger.showDateTime=false

# The date and time format to be used in the output messages.
# The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat.
# If the format is not specified or is invalid, the default format is used.
# The default format is yyyy-MM-dd HH:mm:ss:SSS Z.
#org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss:SSS Z

# Set to true if you want to output the current thread name.
# Defaults to true.
#org.slf4j.simpleLogger.showThreadName=true

# Set to true if you want the Logger instance name to be included in output messages.
# Defaults to true.
#org.slf4j.simpleLogger.showLogName=true

# Set to true if you want the last component of the name to be included in output messages.
# Defaults to false.
#org.slf4j.simpleLogger.showShortLogName=false

Swift Alamofire: How to get the HTTP response status code

    Alamofire
        .request(.GET, "REQUEST_URL", parameters: parms, headers: headers)
        .validate(statusCode: 200..<300)
        .responseJSON{ response in

            switch response.result{
            case .Success:
                if let JSON = response.result.value
                {
                }
            case .Failure(let error):
    }

How to extract or unpack an .ab file (Android Backup file)

As per https://android.stackexchange.com/a/78183/239063 you can run a one line command in Linux to add in an appropriate tar header to extract it.

( printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" ; tail -c +25 backup.ab ) | tar xfvz -

Replace backup.ab with the path to your file.

What is the difference between ELF files and bin files?

I just want to correct a point here. ELF file is produced by the Linker, not the compiler.

The Compiler mission ends after producing the object files (*.o) out of the source code files. Linker links all .o files together and produces the ELF.

Illegal access: this web application instance has been stopped already

Problem solved after restarting the tomcat and apache, the tomcat was caching older version of the app.

Reload browser window after POST without prompting user to resend POST data

I had the same problem as you.

Here's what I did (dynamically generated GET form with action set to location.href, hidden input with fresh value), and it seems to work in all browsers:

var elForm=document.createElement("form");
elForm.setAttribute("method", "get");
elForm.setAttribute("action", window.location.href);

var elInputHidden=document.createElement("input");
elInputHidden.setAttribute("type", "hidden");
elInputHidden.setAttribute("name", "r");
elInputHidden.setAttribute("value", new Date().getTime());
elForm.appendChild(elInputHidden);

if(window.location.href.indexOf("?")>=0)
{
    var _arrNameValue;
    var strRequestVars=window.location.href.substr(window.location.href.indexOf("?")+1);
    var _arrRequestVariablePairs=strRequestVars.split("&");
    for(var i=0; i<_arrRequestVariablePairs.length; i++)
    {
        _arrNameValue=_arrRequestVariablePairs[i].split("=");

        elInputHidden=document.createElement("input");
        elInputHidden.setAttribute("type", "hidden");
        elInputHidden.setAttribute("name", decodeURIComponent(_arrNameValue.shift()));
        elInputHidden.setAttribute("value", decodeURIComponent(_arrNameValue.join("=")));
        elForm.appendChild(elInputHidden);
    }
}

document.body.appendChild(elForm);
elForm.submit();

Javascript ES6 export const vs export let

I think that once you've imported it, the behaviour is the same (in the place your variable will be used outside source file).

The only difference would be if you try to reassign it before the end of this very file.

Swift convert unix time to date and time

For managing dates in Swift 3 I ended up with this helper function:

extension Double {
    func getDateStringFromUTC() -> String {
        let date = Date(timeIntervalSince1970: self)

        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "en_US")
        dateFormatter.dateStyle = .medium

        return dateFormatter.string(from: date)
    }
}

This way it easy to use whenever you need it - in my case it was converting a string:

("1481721300" as! Double).getDateStringFromUTC() // "Dec 14, 2016"

Reference the DateFormatter docs for more details on formatting (Note that some of the examples are out of date)

I found this article to be very helpful as well

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

A DateTime in C# is a value type, not a reference type, and therefore cannot be null. It can however be the constant DateTime.MinValue which is outside the range of Sql Servers DATETIME data type.

Value types are guaranteed to always have a (default) value (of zero) without always needing to be explicitly set (in this case DateTime.MinValue).

Conclusion is you probably have an unset DateTime value that you are trying to pass to the database.

DateTime.MinValue = 1/1/0001 12:00:00 AM
DateTime.MaxValue = 23:59:59.9999999, December 31, 9999, 
                    exactly one 100-nanosecond tick 
                    before 00:00:00, January 1, 10000

MSDN: DateTime.MinValue


Regarding Sql Server

datetime
Date and time data from January 1, 1753 through December 31, 9999, to an accuracy of one three-hundredth of a second (equivalent to 3.33 milliseconds or 0.00333 seconds). Values are rounded to increments of .000, .003, or .007 seconds

smalldatetime
Date and time data from January 1, 1900, through June 6, 2079, with accuracy to the minute. smalldatetime values with 29.998 seconds or lower are rounded down to the nearest minute; values with 29.999 seconds or higher are rounded up to the nearest minute.

MSDN: Sql Server DateTime and SmallDateTime


Lastly, if you find yourself passing a C# DateTime as a string to sql, you need to format it as follows to retain maximum precision and to prevent sql server from throwing a similar error.

string sqlTimeAsString = myDateTime.ToString("yyyy-MM-ddTHH:mm:ss.fff");

Update (8 years later)

Consider using the sql DateTime2 datatype which aligns better with the .net DateTime with date range 0001-01-01 through 9999-12-31 and time range 00:00:00 through 23:59:59.9999999

string dateTime2String = myDateTime.ToString("yyyy-MM-ddTHH:mm:ss.fffffff");

MSDN datetime2 (Transact-SQL)