Programs & Examples On #Stopwatch

The System.Diagnostics.Stopwatch class in .Net, used to accurately measure elapsed time.

Converting Milliseconds to Minutes and Seconds?

package com.v3mobi.userpersistdatetime;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import java.util.Date;
import java.util.concurrent.TimeUnit;

public class UserActivity extends AppCompatActivity {

    Date startDate;
    Date endDate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user);
        startDate = java.util.Calendar.getInstance().getTime(); //set your start time
    }

    @Override
    protected void onStop() {
        super.onStop();
        endDate = java.util.Calendar.getInstance().getTime(); // set  your end time

        chekUserPersistence();

    }

    private void chekUserPersistence()
    {
        long duration = endDate.getTime() - startDate.getTime();
//        long duration = 301000;

        long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);         // minutes ok
        long secs = (duration/1000) % 60;         // minutes ok


        Toast.makeText(UserActivity.this, "Diff  "
                +  diffInMinutes + " : "+ secs , Toast.LENGTH_SHORT).show();

        System.out.println("Diff  " + diffInMinutes +" : "+ secs );

        Log.e("keshav","diffInMinutes -->" +diffInMinutes);
        Log.e("keshav","secs -->" +secs);
        finish();
    }
}

Calculate the execution time of a method

From personal experience, the System.Diagnostics.Stopwatch class can be used to measure the execution time of a method, however, BEWARE: It is not entirely accurate!

Consider the following example:

Stopwatch sw;

for(int index = 0; index < 10; index++)
{
    sw = Stopwatch.StartNew();
    DoSomething();
    Console.WriteLine(sw.ElapsedMilliseconds);
}

sw.Stop();

Example results

132ms
4ms
3ms
3ms
2ms
3ms
34ms
2ms
1ms
1ms

Now you're wondering; "well why did it take 132ms the first time, and significantly less the rest of the time?"

The answer is that Stopwatch does not compensate for "background noise" activity in .NET, such as JITing. Therefore the first time you run your method, .NET JIT's it first. The time it takes to do this is added to the time of the execution. Equally, other factors will also cause the execution time to vary.

What you should really be looking for absolute accuracy is Performance Profiling!

Take a look at the following:

RedGate ANTS Performance Profiler is a commercial product, but produces very accurate results. - Boost the performance of your applications with .NET profiling

Here is a StackOverflow article on profiling: - What Are Some Good .NET Profilers?

I have also written an article on Performance Profiling using Stopwatch that you may want to look at - Performance profiling in .NET

Is there a stopwatch in Java?

You can find a convenient one here:

https://github.com/varra4u/utils4j/blob/master/src/main/java/com/varra/util/StopWatch.java

Usage:

final StopWatch timer = new StopWatch();
System.out.println("Timer: " + timer);
System.out.println("ElapsedTime: " + timer.getElapsedTime());

How do I get the path of the Python script I am running in?

os.path.realpath(__file__) will give you the path of the current file, resolving any symlinks in the path. This works fine on my mac.

"Javac" doesn't work correctly on Windows 10

I had the same issue on Windows 10 - the java -version command was working but javac -version was not. There are three things I did:

(1) I downloaded the latest jdk (not the jre) and installed it. Then, I added the jdk/bin path tan o environment variable. In my case, it was C:\Program Files\Java\jdk-10\bin. I did not need to add the ; for Windows 10.

(2) Move this path to the top of all the other paths.

(3) Delete any other Java paths that might exist.

Test the java -version and javac -version commands again. Voila!

Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling

The best answer is not the correct way to do this :(. You actually bound indexPath with model, which is not always good. Imagine that some rows has been added during loading image. Now cell for given indexPath exists on screen, but the image is no longer correct! The situation is kinda unlikely and hard to replicate but it's possible.

It's better to use MVVM approach, bind cell with viewModel in controller and load image in viewModel (assigning ReactiveCocoa signal with switchToLatest method), then subscribe this signal and assign image to cell! ;)

You have to remember to not abuse MVVM. Views have to be dead simple! Whereas ViewModels should be reusable! It's why it's very important to bind View (UITableViewCell) and ViewModel in controller.

Postgres "psql not recognized as an internal or external command"

Always better to install a previous version or in the installation make sure you specify the '/data' in a separate directory folder "C:\data"

When to use pthread_exit() and when to use pthread_join() in Linux?

Using pthread_exit in the main thread(in place of pthread_join), will leave the main thread in defunct(zombie) state. Since not using pthread_join, other joinable threads which are terminated will also remain in the zombie state and cause resource leakage.

Failure to join with a thread that is joinable (i.e., one that is not detached), produces a "zombie thread". Avoid doing this, since each zombie thread consumes some system resources, and when enough zombie threads have accumulated, it will no longer be possible to create new threads (or processes).

Another point is keeping the main thread in the defunct state, while other threads are running may cause implementation dependent issues in various conditions like if resources are allocated in main thread or variables which are local to the main thread are used in other threads.

Also, all the shared resources are released only when the process exits, it's not saving any resources. So, I think using pthread_exit in place of pthread_join should be avoided.

Best timestamp format for CSV/Excel?

Go to the language settings in the Control Panel, then Format Options, select a locale and see the actual date format for the chosen locale used by Windows by default. Yes, that timestamp format is locale-sensitive. Excel uses those formats when parsing CSV.

Even further, if the locale uses characters beyond ASCII, you'll have to emit CSV in the corresponding pre-Unicode Windows "ANSI" codepage, e.g. CP1251. Excel won't accept UTF-8.

How can I round down a number in Javascript?

Math.floor() will work, but it's very slow compared to using a bitwise OR operation:

var rounded = 34.923 | 0;
alert( rounded );
//alerts "34"

EDIT Math.floor() is not slower than using the | operator. Thanks to Jason S for checking my work.

Here's the code I used to test:

var a = [];
var time = new Date().getTime();
for( i = 0; i < 100000; i++ ) {
    //a.push( Math.random() * 100000  | 0 );
    a.push( Math.floor( Math.random() * 100000 ) );
}
var elapsed = new Date().getTime() - time;
alert( "elapsed time: " + elapsed );

Setting up and using environment variables in IntelliJ Idea

It is possible to reference an intellij 'Path Variable' in an intellij 'Run Configuration'.

In 'Path Variables' create a variable for example ANALYTICS_VERSION.

In a 'Run Configuration' under 'Environment Variables' add for example the following:

ANALYTICS_LOAD_LOCATION=$MAVEN_REPOSITORY$\com\my\company\analytics\$ANALYTICS_VERSION$\bin

To answer the original question you would need to add an APP_HOME environment variable to your run configuration which references the path variable:

APP_HOME=$APP_HOME$

src absolute path problem

I think because C would be seen the C drive on the client pc, it wont let you. And if it could do this, it would be a big security hole.

Setting font on NSAttributedString on UITextView disregards line spacing

You can use this example and change it's implementation like this:

[self enumerateAttribute:NSParagraphStyleAttributeName
                 inRange:NSMakeRange(0, self.length)
                 options:0
              usingBlock:^(id  _Nullable value, NSRange range, BOOL * _Nonnull stop) {
                  NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];

                  //add your specific settings for paragraph
                  //...
                  //...

                  [self removeAttribute:NSParagraphStyleAttributeName range:range];
                  [self addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];
              }];

Request UAC elevation from within a Python script?

A variation on Jorenko's work above allows the elevated process to use the same console (but see my comment below):

def spawn_as_administrator():
    """ Spawn ourself with administrator rights and wait for new process to exit
        Make the new process use the same console as the old one.
          Raise Exception() if we could not get a handle for the new re-run the process
          Raise pywintypes.error() if we could not re-spawn
        Return the exit code of the new process,
          or return None if already running the second admin process. """
    #pylint: disable=no-name-in-module,import-error
    import win32event, win32api, win32process
    import win32com.shell.shell as shell
    if '--admin' in sys.argv:
        return None
    script = os.path.abspath(sys.argv[0])
    params = ' '.join([script] + sys.argv[1:] + ['--admin'])
    SEE_MASK_NO_CONSOLE = 0x00008000
    SEE_MASK_NOCLOSE_PROCESS = 0x00000040
    process = shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params, fMask=SEE_MASK_NO_CONSOLE|SEE_MASK_NOCLOSE_PROCESS)
    hProcess = process['hProcess']
    if not hProcess:
        raise Exception("Could not identify administrator process to install drivers")
    # It is necessary to wait for the elevated process or else
    #  stdin lines are shared between 2 processes: they get one line each
    INFINITE = -1
    win32event.WaitForSingleObject(hProcess, INFINITE)
    exitcode = win32process.GetExitCodeProcess(hProcess)
    win32api.CloseHandle(hProcess)
    return exitcode

Shuffle DataFrame rows

You can simply use sklearn for this

from sklearn.utils import shuffle
df = shuffle(df)

How to use C++ in Go

Funny how many broader issues this announcement has dredged up. Dan Lyke had a very entertaining and thoughtful discussion on his website, Flutterby, about developing Interprocess Standards as a way of bootstrapping new languages (and other ramifications, but that's the one that is germane here).

How to display binary data as image - extjs 4

In ExtJs, you can use

xtype: 'image'

to render a image.

Here is a fiddle showing rendering of binary data with extjs.

atob -- > converts ascii to binary

btoa -- > converts binary to ascii

Ext.application({
    name: 'Fiddle',

    launch: function () {
        var srcBase64 = "data:image/jpeg;base64," + btoa(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8H8hYDwAFegHS8+X7mgAAAABJRU5ErkJggg=="));

        Ext.create("Ext.panel.Panel", {
            title: "Test",
            renderTo: Ext.getBody(),
            height: 400,
            items: [{
                xtype: 'image',
                width: 100,
                height: 100,
                src: srcBase64
            }]
        })
    }
});

https://fiddle.sencha.com/#view/editor&fiddle/28h0

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

Unfortunately this error is not descriptive for a range of different problems related to the same issue - a binding error. It also does not specify where the error is, and so your problem is not necessarily in the execution, but the sql statement that was already 'prepared'.

These are the possible errors and their solutions:

  1. There is a parameter mismatch - the number of fields does not match the parameters that have been bound. Watch out for arrays in arrays. To double check - use var_dump($var). "print_r" doesn't necessarily show you if the index in an array is another array (if the array has one value in it), whereas var_dump will.

  2. You have tried to bind using the same binding value, for example: ":hash" and ":hash". Every index has to be unique, even if logically it makes sense to use the same for two different parts, even if it's the same value. (it's similar to a constant but more like a placeholder)

  3. If you're binding more than one value in a statement (as is often the case with an "INSERT"), you need to bindParam and then bindValue to the parameters. The process here is to bind the parameters to the fields, and then bind the values to the parameters.

    // Code snippet
    $column_names = array();
    $stmt->bindParam(':'.$i, $column_names[$i], $param_type);
    $stmt->bindValue(':'.$i, $values[$i], $param_type);
    $i++;
    //.....
    
  4. When binding values to column_names or table_names you can use `` but its not necessary, but make sure to be consistent.

  5. Any value in '' single quotes is always treated as a string and will not be read as a column/table name or placeholder to bind to.

get all keys set in memcached

Bash

To get list of keys in Bash, follow the these steps.

First, define the following wrapper function to make it simple to use (copy and paste into shell):

function memcmd() {
  exec {memcache}<>/dev/tcp/localhost/11211
  printf "%s\n%s\n" "$*" quit >&${memcache}
  cat <&${memcache}
}

Memcached 1.4.31 and above

You can use lru_crawler metadump all command to dump (most of) the metadata for (all of) the items in the cache.

As opposed to cachedump, it does not cause severe performance problems and has no limits on the amount of keys that can be dumped.

Example command by using the previously defined function:

memcmd lru_crawler metadump all

See: ReleaseNotes1431.


Memcached 1.4.30 and below

Get list of slabs by using items statistics command, e.g.:

memcmd stats items

For each slub class, you can get list of items by specifying slub id along with limit number (0 - unlimited):

memcmd stats cachedump 1 0
memcmd stats cachedump 2 0
memcmd stats cachedump 3 0
memcmd stats cachedump 4 0
...

Note: You need to do this for each memcached server.

To list all the keys from all stubs, here is the one-liner (per one server):

for id in $(memcmd stats items | grep -o ":[0-9]\+:" | tr -d : | sort -nu); do
    memcmd stats cachedump $id 0
done

Note: The above command could cause severe performance problems while accessing the items, so it's not advised to run on live.


Notes:

stats cachedump only dumps the HOT_LRU (IIRC?), which is managed by a background thread as activity happens. This means under a new enough version which the 2Q algo enabled, you'll get snapshot views of what's in just one of the LRU's.

If you want to view everything, lru_crawler metadump 1 (or lru_crawler metadump all) is the new mostly-officially-supported method that will asynchronously dump as many keys as you want. you'll get them out of order but it hits all LRU's, and unless you're deleting/replacing items multiple runs should yield the same results.

Source: GH-405.


Related:

C++ - Hold the console window open?

If your problem is retaining the Console Window within Visual Studio without modifying your application (c-code) and are running it with Ctrl+F5 (when running Ctrl+F5) but the window is still closing the principal hint is to set the /SUBSYSTEM:CONSOLE linker option in your Visual Studio project.

as explained by DJMooreTX in http://social.msdn.microsoft.com/Forums/en-US/vcprerelease/thread/21073093-516c-49d2-81c7-d960f6dc2ac6

1) Open up your project, and go to the Solution Explorer. If you're following along with me in K&R, your "Solution" will be 'hello' with 1 project under it, also 'hello' in bold.

  1. Right click on the 'hello" (or whatever your project name is.)

  2. Choose "Properties" from the context menu.

  3. Choose Configuration Properties>Linker>System.

  4. For the "Subsystem" property in the right-hand pane, click the drop-down box in the right hand column.

  5. Choose "Console (/SUBSYSTEM:CONSOLE)"

  6. Click Apply, wait for it to finish doing whatever it does, then click OK. (If "Apply" is grayed out, choose some other subsystem option, click Apply, then go back and apply the console option. My experience is that OK by itself won't work.)

Now do Boris' CTRL-F5, wait for your program to compile and link, find the console window under all the other junk on your desktop, and read your program's output, followed by the beloved "Press any key to continue...." prompt.

Again, CTRL-F5 and the subsystem hints work together; they are not separate options.

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

Something that is now available in maven as well is

mvn goal --no-snapshot-updates

or in short

mvn goal -nsu

What is a "static" function in C?

Minor nit: static functions are visible to a translation unit, which for most practical cases is the file the function is defined in. The error you are getting is commonly referred to as violation of the One Definition Rule.

The standard probably says something like:

"Every program shall contain exactly one definition of every noninline function or object that is used in that program; no diagnostic required."

That is the C way of looking at static functions. This is deprecated in C++ however.

In C++, additionally, you can declare member functions static. These are mostly metafunctions i.e. they do not describe/modify a particular object's behavior/state but act on the whole class itself. Also, this means that you do not need to create an object to call a static member function. Further, this also means, you only get access to static member variables from within such a function.

I'd add to Parrot's example the Singleton pattern which is based on this sort of a static member function to get/use a single object throughout the lifetime of a program.

Replace multiple strings with multiple other strings

user regular function to define the pattern to replace and then use replace function to work on input string,

var i = new RegExp('"{','g'),
    j = new RegExp('}"','g'),
    k = data.replace(i,'{').replace(j,'}');

git ignore vim temporary files

This is something that should only be done on a per-user basis, not per-repository. If Joe uses emacs, he will want to have emacs backup files ignored, but Betty (who uses vi) will want vi backup files ignored (in many cases, they are similar, but there are about 24,893 common editors in existence and it is pretty ridiculous to try to ignore all of the various backup extensions.)

In other words, do not put anything in .gitignore or in core.excludes in $GIT_DIR/config. Put the info in $HOME/.gitconfig instead (as nunopolonia suggests with --global.) Note that "global" means per-user, not per-system.

If you want configuration across the system for all users (which you don't), you'll need a different mechanism. (Possibly with templates setup prior to initialization of the repository.)

Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

Solution 1:

Extract P12 from jks

keytool -importkeystore -srckeystore MyRootCA.jks -destkeystore MyRootCA.p12 -deststoretype PKCS12

Extract PEM from P12 and Edit file and pem from crt file

openssl pkcs12 -in MyRootCA.p12 -clcerts -nokeys -out MyRootCA.crt

Extract key from jks

openssl pkcs12 -in MyRootCA.p12 -nocerts -out encryptedPrivateKey.pem
openssl rsa -in encryptedPrivateKey.pem -out decryptedPrivateKey.key

Solution 2:

Extract PEM and encryptedPrivateKey to txt file```

openssl pkcs12 -in MyRootCA.p12 -out keys_out.txt

Decrypt privateKey

openssl rsa -in encryptedPrivateKey.key [-outform PEM] -out decryptedPrivateKey.key

How can I force WebKit to redraw/repaint to propagate style changes?

Since the display + offset trigger didn't work for me, I found a solution here:

http://mir.aculo.us/2009/09/25/force-redraw-dom-technique-for-webkit-based-browsers/

i.e.

element.style.webkitTransform = 'scale(1)';

What's the difference between an element and a node in XML?

A Node is a part of the DOM tree, an Element is a particular type of Node

e.g. <foo> This is Text </foo>

You have a foo Element, (which is also a Node, as Element inherits from Node) and a Text Node 'This is Text', that is a child of the foo Element/Node

Is an entity body allowed for an HTTP DELETE request?

One reason to use the body in a delete request is for optimistic concurrency control.

You read version 1 of a record.

GET /some-resource/1
200 OK { id:1, status:"unimportant", version:1 }

Your colleague reads version 1 of the record.

GET /some-resource/1
200 OK { id:1, status:"unimportant", version:1 }

Your colleague changes the record and updates the database, which updates the version to 2:

PUT /some-resource/1 { id:1, status:"important", version:1 }
200 OK { id:1, status:"important", version:2 }

You try to delete the record:

DELETE /some-resource/1 { id:1, version:1 }
409 Conflict

You should get an optimistic lock exception. Re-read the record, see that it's important, and maybe not delete it.

Another reason to use it is to delete multiple records at a time (for example, a grid with row-selection check-boxes).

DELETE /messages
[{id:1, version:2},
{id:99, version:3}]
204 No Content

Notice that each message has its own version. Maybe you can specify multiple versions using multiple headers, but by George, this is simpler and much more convenient.

This works in Tomcat (7.0.52) and Spring MVC (4.05), possibly w earlier versions too:

@RestController
public class TestController {

    @RequestMapping(value="/echo-delete", method = RequestMethod.DELETE)
    SomeBean echoDelete(@RequestBody SomeBean someBean) {
        return someBean;
    }
}

Import numpy on pycharm

In PyCharm go to

  1. File ? Settings, or use Ctrl + Alt + S
  2. < project name > ? Project Interpreter ? gear symbol ? Add Local
  3. navigate to C:\Miniconda3\envs\my_env\python.exe, where my_env is the environment you want to use

Alternatively, in step 3 use C:\Miniconda3\python.exe if you did not create any further environments (if you never invoked conda create -n my_env python=3).

You can get a list of your current environments with conda info -e and switch to one of them using activate my_env.

How to install bcmath module?

To enable bcmath in Arch Linux or Manjaro

Edit php.ini

nano /etc/php/php.ini

Uncomment bcmath (remove semicolon)

extension=bcmath

If you are using Apache server reload the server by

sudo systemctl reload apache.server

Or

sudo systemctl realod httpd

If you don't use Apache

sudo systemctl reload php-fpm.service

To see the activated modules

php -m

To make sure the php-fpm is installed and activated, search for it

php -m | grep bcmath

How to install SQL Server Management Studio 2008 component only

For any of you still having problems as of Sept. 2012, go here: http://support.microsoft.com/kb/2527041 ...and grab the SQLManagementStudio_x(32|64)_ENU.exe (if you've already installed SQL Server 2008 Express R2), or SQL Server 2008 Express R2 with Tools, i.e. SQLEXPRWT_x64_ENU.exe or SQLEXPRWT_x32_ENU.exe (if you haven't).

From there, follow similar instructions as above (i.e. use the "Perform new installation and add shared features" selection, as "Management Tools - Basic" is considered a "shared feature"), if you've already installed SQL Server Express 2008 R2 (as I had). And if you haven't done that yet, then of course you're going to follow this way as you need to install the new instance anyway.

This solved things for me, and hopefully it will for you, too!

Is it possible to set async:false to $.getJSON call

Roll your own e.g.

function syncJSON(i_url, callback) {
  $.ajax({
    type: "POST",
    async: false,
    url: i_url,
    contentType: "application/json",
    dataType: "json",
    success: function (msg) { callback(msg) },
    error: function (msg) { alert('error : ' + msg.d); }
  });
}

syncJSON("/pathToYourResouce", function (msg) {
   console.log(msg);
})

Appending a line to a file only if it does not already exist

The answers using grep are wrong. You need to add an -x option to match the entire line otherwise lines like #text to add will still match when looking to add exactly text to add.

So the correct solution is something like:

grep -qxF 'include "/configs/projectname.conf"' foo.bar || echo 'include "/configs/projectname.conf"' >> foo.bar

Clear text in EditText when entered

i don't know what mistakes i did while implementing the above solutions, bt they were unsuccessful for me

txtDeck.setOnFocusChangeListener(new OnFocusChangeListener() {
    @Override       
    public void onFocusChange(View v, boolean hasFocus) {
        txtDeck.setText("");
    }
});

This works for me,

Are there bookmarks in Visual Studio Code?

The bookmarks extension mentioned in the accepted answer conflicts with toggling breakpoints via the margin.

You could do the same with breakpoints and select the debug tab on the left to see them listed. Better yet, use File, Preferences, Keyboard Shortcuts and set (Shift+)Ctrl+F9 to navigate between them, even across files: enter image description here

String was not recognized as a valid DateTime " format dd/MM/yyyy"

Just like someone above said you can send it as a string parameter but it must have this format: '20130121' for example and you can convert it to that format taking it directly from the control. So you'll get it for example from a textbox like:

date = datetextbox.text; // date is going to be something like: "2013-01-21 12:00:00am"

to convert it to: '20130121' you use:

date = date.Substring(6, 4) + date.Substring(3, 2) + date.Substring(0, 2);

so that SQL can convert it and put it into your database.

Can You Get A Users Local LAN IP Address Via JavaScript?

Update

This solution would not longer work because browsers are fixing webrtc leak: for more info on that read this other question: RTCIceCandidate no longer returning IP


In addition to afourney's answer this code works in browsers that support WebRTC (Chrome and Firefox). I heard there is a movement going on to implement a feature that makes sites request the IP (like in case of user's geo-location or user-media) though it has yet to be implemented in either of those browsers.

Here is a modified version of the source code, reduced the lines, not making any stun requests since you only want Local IP not the Public IP:

window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;//compatibility for Firefox and chrome
var pc = new RTCPeerConnection({iceServers:[]}), noop = function(){};      
pc.createDataChannel('');//create a bogus data channel
pc.createOffer(pc.setLocalDescription.bind(pc), noop);// create offer and set local description
pc.onicecandidate = function(ice)
{
 if (ice && ice.candidate && ice.candidate.candidate)
 {
  var myIP = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(ice.candidate.candidate)[1];
  console.log('my IP: ', myIP);   
  pc.onicecandidate = noop;
 }
};

We are creating a dummy peer connection for the remote peer to contact us. We generally exchange ice candidates with each other and reading the ice candidates we can tell the ip of the user.

You can find a demo at --> Demo

HTML5 form required attribute. Set custom validation message?

Here is the code to handle custom error message in HTML5:

<input type="text" id="username" required placeholder="Enter Name"
  oninvalid="this.setCustomValidity('Enter User Name Here')"
  oninput="this.setCustomValidity('')"/>

This part is important because it hides the error message when the user inputs new data:

oninput="this.setCustomValidity('')"

AngularJS - Multiple ng-view in single template

You cant have multiple ng-view. Below is my use case where I solved my requirement. I wanted to have tabbed behavior in my model dialog. I was facing issue as click on tabs having hyperlink which will invoke router links. I solved this using button and css for tabs. When user clicks on tab, it actually will not call any hyperlink which will always invoke the ng-router. When user click on tab it will call a method, where I dynamcilly load html. Below is the function on click of tab

self.submit = function(form) {
                $templateRequest('resources/items/employee/test_template.html').then(function(template){
                var compiledeHTML = $compile(template)($scope);
                $("#d").replaceWith(compiledeHTML);
});

User $templateRequest. In test_template.html page add your html content. This html content will be bind to your controller.

How to move up a directory with Terminal in OS X

To move up a directory, the quickest way would be to add an alias to ~/.bash_profile

alias ..='cd ..'

and then one would need only to type '..[return]'.

Get the _id of inserted document in Mongo database in NodeJS

A shorter way than using second parameter for the callback of collection.insert would be using objectToInsert._id that returns the _id (inside of the callback function, supposing it was a successful operation).

The Mongo driver for NodeJS appends the _id field to the original object reference, so it's easy to get the inserted id using the original object:

collection.insert(objectToInsert, function(err){
   if (err) return;
   // Object inserted successfully.
   var objectId = objectToInsert._id; // this will return the id of object inserted
});

Hide vertical scrollbar in <select> element

Like Guffa said, you cannot reliably get that much control over native controls. The best way is probably to make a box of elements with radio buttons beside each item, then use labels and JavaScript to make the 'rows' interactive, so clicking on a radio button or label will color the selected row.

AngularJS - add HTML element to dom in directive without jQuery

Why not to try simple (but powerful) html() method:

iElement.html('<svg width="600" height="100" class="svg"></svg>');

Or append as an alternative:

iElement.append('<svg width="600" height="100" class="svg"></svg>');

And , of course , more cleaner way:

 var svg = angular.element('<svg width="600" height="100" class="svg"></svg>');
 iElement.append(svg);

Fiddle: http://jsfiddle.net/cherniv/AgGwK/

Check if year is leap year in javascript

You can try using JavaScript's Date Object

new Date(year,month).getFullYear()%4==0

This will return true or false.

Redefining the Index in a Pandas DataFrame object

Why don't you simply use set_index method?

In : col = ['a','b','c']

In : data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)

In : data
Out:
    a   b   c
0   1   2   3
1  10  11  12
2  20  21  22

In : data2 = data.set_index('a')

In : data2
Out:
     b   c
a
1    2   3
10  11  12
20  21  22

Python: Removing spaces from list objects

result = map(str.strip, hello)

Creating a new dictionary in Python

So there 2 ways to create a dict :

  1. my_dict = dict()

  2. my_dict = {}

But out of these two options {} is more efficient than dict() plus its readable. CHECK HERE

Replace Default Null Values Returned From Left Outer Join

MySQL

COALESCE(field, 'default')

For example:

  SELECT
    t.id,
    COALESCE(d.field, 'default')
  FROM
     test t
  LEFT JOIN
     detail d ON t.id = d.item

Also, you can use multiple columns to check their NULL by COALESCE function. For example:

mysql> SELECT COALESCE(NULL, 1, NULL);
        -> 1
mysql> SELECT COALESCE(0, 1, NULL);
        -> 0
mysql> SELECT COALESCE(NULL, NULL, NULL);
        -> NULL

Failed to run sdkmanager --list with Java 9

As we read in the previous comments this error is occurring because the current SDK version is incompatible with the newest Java versions: 9 and 10.

So, to solve it, you can downgrade your java version to Java 8, or as a workaround, you can export the following option on your terminal:

Linux:

export JAVA_OPTS='-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee'

Windows:

set JAVA_OPTS=-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee'

If this does not work try to exports the java.xml.bind instead.

Linux:

export JAVA_OPTS='-XX:+IgnoreUnrecognizedVMOptions --add-modules java.xml.bind'

Windows:

set JAVA_OPTS=-XX:+IgnoreUnrecognizedVMOptions --add-modules java.xml.bind'

This will solve this error for the sdkmanager

And to make it saved permanently you can export the JAVA_OPTS in your profile file on Linux (.zshrc, .bashrc and etc.) or add it as an environment variable permanently on Windows.


ps. This doesn't work for Java 11/11+, which doesn't have Java EE modules. For this option is a good idea, downgrade your Java version or wait for a Flutter update.

Ref: JDK 11: End of the road for Java EE modules

Git merge reports "Already up-to-date" though there is a difference

I had the same problem. I had changes in the remote and it was still showing "Already up to date". Recloning the repository fixed the problem for me.

Excel formula to get ranking position

Try this in your forth column

=COUNTIF(B:B; ">" & B2) + 1

Replace B2 with B3 for next row and so on.

What this does is it counts how many records have more points then current one and then this adds current record position (+1 part).

How do I simulate placeholder functionality on input date field?

As i mentioned here

initially set the field type to text.

on focus change it to type date

JavaScript for handling Tab Key press

try this

 <body>
   <div class="linkCollection">
             <a tabindex=1 href="www.demo1.com">link</a>    
             <a tabindex=2 href="www.demo2.com">link</a>    
             <a tabindex=3 href="www.demo3.com">link</a>    
             <a tabindex=4 href="www.demo4.com">link</a>    
             <a tabindex=5 href="www.demo5.com">link</a>    
             <a tabindex=6 href="www.demo6.com">link</a>    
             <a tabindex=7 href="www.demo7.com">link</a>    
             <a tabindex=8 href="www.demo8.com">link</a>    
             <a tabindex=9 href="www.demo9.com">link</a>    
             <a tabindex=10 href="www.demo10.com">link</a>   
        </div>

</body>

<script>
$(document).ready(function(){
  $(".linkCollection a").focus(function(){
    var href=$(this).attr('href');
    console.log(href);
    // href variable holds the active selected link.
  });
});
</script>

don't forgot to add jQuery library

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

Typescript: difference between String and string

Here is an example that shows the differences, which will help with the explanation.

var s1 = new String("Avoid newing things where possible");
var s2 = "A string, in TypeScript of type 'string'";
var s3: string;

String is the JavaScript String type, which you could use to create new strings. Nobody does this as in JavaScript the literals are considered better, so s2 in the example above creates a new string without the use of the new keyword and without explicitly using the String object.

string is the TypeScript string type, which you can use to type variables, parameters and return values.

Additional notes...

Currently (Feb 2013) Both s1 and s2 are valid JavaScript. s3 is valid TypeScript.

Use of String. You probably never need to use it, string literals are universally accepted as being the correct way to initialise a string. In JavaScript, it is also considered better to use object literals and array literals too:

var arr = []; // not var arr = new Array();
var obj = {}; // not var obj = new Object();

If you really had a penchant for the string, you could use it in TypeScript in one of two ways...

var str: String = new String("Hello world"); // Uses the JavaScript String object
var str: string = String("Hello World"); // Uses the TypeScript string type

RestSharp simple complete example

Pawel Sawicz .NET blog has a real good explanation and example code, explaining how to call the library;

GET:

var client = new RestClient("192.168.0.1");
var request = new RestRequest("api/item/", Method.GET);
var queryResult = client.Execute<List<Items>>(request).Data;

POST:

var client = new RestClient("http://192.168.0.1");
var request = new RestRequest("api/item/", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(new Item
{
   ItemName = someName,
   Price = 19.99
});
client.Execute(request);

DELETE:

var item = new Item(){//body};
var client = new RestClient("http://192.168.0.1");
var request = new RestRequest("api/item/{id}", Method.DELETE);
request.AddParameter("id", idItem);
 
client.Execute(request)

The RestSharp GitHub page has quite an exhaustive sample halfway down the page. To get started install the RestSharp NuGet package in your project, then include the necessary namespace references in your code, then above code should work (possibly negating your need for a full example application).

NuGet RestSharp

How to measure time elapsed on Javascript?

var seconds = 0;
setInterval(function () {
  seconds++;
}, 1000);

There you go, now you have a variable counting seconds elapsed. Since I don't know the context, you'll have to decide whether you want to attach that variable to an object or make it global.

Set interval is simply a function that takes a function as it's first parameter and a number of milliseconds to repeat the function as it's second parameter.

You could also solve this by saving and comparing times.

EDIT: This answer will provide very inconsistent results due to things such as the event loop and the way browsers may choose to pause or delay processing when a page is in a background tab. I strongly recommend using the accepted answer.

How to set image on QPushButton?

You can do this in QtDesigner. Just click on your button then go to icon property and then choose your image file.

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

2014 answer: classList.toggle() is the standard and supported by most browsers.

Older browsers can use use classlist.js for classList.toggle():

var menu = document.querySelector('.menu') // Using a class instead, see note below.
menu.classList.toggle('hidden-phone');

As an aside, you shouldn't be using IDs (they leak globals into the JS window object).

Convert an ISO date to the date format yyyy-mm-dd in JavaScript

_x000D_
_x000D_
    var d = new Date("Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)");_x000D_
    alert(d.toLocaleDateString());
_x000D_
_x000D_
_x000D_

UIImageView aspect fit and center

For people looking for UIImage resizing,

@implementation UIImage (Resize)

- (UIImage *)scaledToSize:(CGSize)size
{
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
    [self drawInRect:CGRectMake(0.0f, 0.0f, size.width, size.height)];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (UIImage *)aspectFitToSize:(CGSize)size
{
    CGFloat aspect = self.size.width / self.size.height;
    if (size.width / aspect <= size.height)
    {
        return [self scaledToSize:CGSizeMake(size.width, size.width / aspect)];
    } else {
        return [self scaledToSize:CGSizeMake(size.height * aspect, size.height)];
    }
}

- (UIImage *)aspectFillToSize:(CGSize)size
{
    CGFloat imgAspect = self.size.width / self.size.height;
    CGFloat sizeAspect = size.width/size.height;

    CGSize scaledSize;

        if (sizeAspect > imgAspect) { // increase width, crop height
            scaledSize = CGSizeMake(size.width, size.width / imgAspect);
        } else { // increase height, crop width
            scaledSize = CGSizeMake(size.height * imgAspect, size.height);
        }
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClipToRect(context, CGRectMake(0, 0, size.width, size.height));
    [self drawInRect:CGRectMake(0.0f, 0.0f, scaledSize.width, scaledSize.height)];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

@end

Select all DIV text with single mouse click

The answer of Neuroxik was really helpful. I had only a trouble with Chrome, because when I clicked on an external div, It did not work. I could solve it removing the old ranges before add the new range:

function selectText(containerid) {
    if (document.selection) {
        var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(containerid));
        range.select();
    } else if (window.getSelection()) {
        var range = document.createRange();
        range.selectNode(document.getElementById(containerid));
        window.getSelection().removeAllRanges();
        window.getSelection().addRange(range);
    }
}
<div id="selectable" onclick="selectText('selectable')">http://example.com/page.htm</div>

Sort Pandas Dataframe by Date

@JAB's answer is fast and concise. But it changes the DataFrame you are trying to sort, which you may or may not want.

(Note: You almost certainly will want it, because your date columns should be dates, not strings!)

In the unlikely event that you don't want to change the dates into dates, you can also do it a different way.

First, get the index from your sorted Date column:

In [25]: pd.to_datetime(df.Date).order().index
Out[25]: Int64Index([0, 2, 1], dtype='int64')

Then use it to index your original DataFrame, leaving it untouched:

In [26]: df.ix[pd.to_datetime(df.Date).order().index]
Out[26]: 
        Date Symbol
0 2015-02-20      A
2 2015-08-21      A
1 2016-01-15      A

Magic!

Note: for Pandas versions 0.20.0 and later, use loc instead of ix, which is now deprecated.

How to get Django and ReactJS to work together?

The accepted answer lead me to believe that decoupling Django backend and React Frontend is the right way to go no matter what. In fact there are approaches in which React and Django are coupled, which may be better suited in particular situations.

This tutorial well explains this. In particular:

I see the following patterns (which are common to almost every web framework):

-React in its own “frontend” Django app: load a single HTML template and let React manage the frontend (difficulty: medium)

-Django REST as a standalone API + React as a standalone SPA (difficulty: hard, it involves JWT for authentication)

-Mix and match: mini React apps inside Django templates (difficulty: simple)

What's the difference between Unicode and UTF-8?

The development of Unicode was aimed at creating a new standard for mapping the characters in a great majority of languages that are being used today, along with other characters that are not that essential but might be necessary for creating the text. UTF-8 is only one of the many ways that you can encode the files because there are many ways you can encode the characters inside a file into Unicode.

Source:

http://www.differencebetween.net/technology/difference-between-unicode-and-utf-8/

What is initial scale, user-scalable, minimum-scale, maximum-scale attribute in meta tag?

user-scalable:

user-scalable=yes (default) to allow the user to zoom in or out on the web page;

user-scalable=no to prevent the user from zooming in or out.

You can get more detailed information by reading the following articles.

Demo Code (recommended)

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="UTF-8">_x000D_
    <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=0.5, maximum-scale=3.0">_x000D_
</head>_x000D_
<body>_x000D_
    <header>_x000D_
    </header>_x000D_
    <main>_x000D_
        <section>_x000D_
            <h1>do not using <mark>user-scalable=no</mark></h1>_x000D_
        </section>_x000D_
    </main>_x000D_
    <footer>_x000D_
    </footer>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Reading Email using Pop3 in C#

downloading the email via the POP3 protocol is the easy part of the task. The protocol is quite simple and the only hard part could be advanced authentication methods if you don't want to send a clear text password over the network (and cannot use the SSL encrypted communication channel). See RFC 1939: Post Office Protocol - Version 3 and RFC 1734: POP3 AUTHentication command for details.

The hard part comes when you have to parse the received email, which means parsing MIME format in most cases. You can write quick&dirty MIME parser in a few hours or days and it will handle 95+% of all incoming messages. Improving the parser so it can parse almost any email means:

  • getting email samples sent from the most popular mail clients and improve the parser in order to fix errors and RFC misinterpretations generated by them.
  • Making sure that messages violating RFC for message headers and content will not crash your parser and that you will be able to read every readable or guessable value from the mangled email
  • correct handling of internationalization issues (e.g. languages written from righ to left, correct encoding for specific language etc)
  • UNICODE
  • Attachments and hierarchical message item tree as seen in "Mime torture email sample"
  • S/MIME (signed and encrypted emails).
  • and so on

Debugging a robust MIME parser takes months of work. I know, because I was watching my friend writing one such parser for the component mentioned below and was writing a few unit tests for it too ;-)

Back to the original question.

Following code taken from our POP3 Tutorial page and links would help you:

// 
// create client, connect and log in 
Pop3 client = new Pop3();
client.Connect("pop3.example.org");
client.Login("username", "password");

// get message list 
Pop3MessageCollection list = client.GetMessageList();

if (list.Count == 0)
{
    Console.WriteLine("There are no messages in the mailbox.");
}
else 
{
    // download the first message 
    MailMessage message = client.GetMailMessage(list[0].SequenceNumber);
    ...
}

client.Disconnect();

Selecting element by data attribute with jQuery

The construction like this: $('[data-XXX=111]') isn't working in Safari 8.0.

If you set data attribute this way: $('div').data('XXX', 111), it only works if you set data attribute directly in DOM like this: $('div').attr('data-XXX', 111).

I think it's because jQuery team optimized garbage collector to prevent memory leaks and heavy operations on DOM rebuilding on each change data attribute.

Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

Neither if you ask me;

If your "link" has the sole purpose of running some JavaScript code it doesn't qualify as a link; rather a piece of text with a JavaScript function coupled to it. I would recommend to use a <span> tag with an onclick handler attached to it and some basic CSS to immitate a link. Links are made for navigation, and if your JavaScript code isn't for navigation it should not be an <a> tag.

Example:

_x000D_
_x000D_
function callFunction() { console.log("function called"); }
_x000D_
.jsAction {_x000D_
    cursor: pointer;_x000D_
    color: #00f;_x000D_
    text-decoration: underline;_x000D_
}
_x000D_
<p>I want to call a JavaScript function <span class="jsAction" onclick="callFunction();">here</span>.</p>
_x000D_
_x000D_
_x000D_

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

Convert NSDate to NSString

#ios #swift #convertDateinString

Simply just do like this to "convert date into string" as per format you passed:

let formatter = DateFormatter()

formatter.dateFormat = "dd-MM-YYYY" // pass formate here
        
let myString = formatter.string(from: date) // this will convert Date in String

Note: You can specify different formats such like "yyyy-MM-dd", "yyyy", "MM" etc...

Calculating a 2D Vector's Cross Product

Implementation 1 returns the magnitude of the vector that would result from a regular 3D cross product of the input vectors, taking their Z values implicitly as 0 (i.e. treating the 2D space as a plane in the 3D space). The 3D cross product will be perpendicular to that plane, and thus have 0 X & Y components (thus the scalar returned is the Z value of the 3D cross product vector).

Note that the magnitude of the vector resulting from 3D cross product is also equal to the area of the parallelogram between the two vectors, which gives Implementation 1 another purpose. In addition, this area is signed and can be used to determine whether rotating from V1 to V2 moves in an counter clockwise or clockwise direction. It should also be noted that implementation 1 is the determinant of the 2x2 matrix built from these two vectors.

Implementation 2 returns a vector perpendicular to the input vector still in the same 2D plane. Not a cross product in the classical sense but consistent in the "give me a perpendicular vector" sense.

Note that 3D euclidean space is closed under the cross product operation--that is, a cross product of two 3D vectors returns another 3D vector. Both of the above 2D implementations are inconsistent with that in one way or another.

Hope this helps...

what is the difference between ajax and jquery and which one is better?

AJAX is a technique to do an XMLHttpRequest (out of band Http request) from a web page to the server and send/retrieve data to be used on the web page. AJAX stands for Asynchronous Javascript And XML. It uses javascript to construct an XMLHttpRequest, typically using different techniques on various browsers.

jQuery (website) is a javascript framework that makes working with the DOM easier by building lots of high level functionality that can be used to search and interact with the DOM. Part of the functionality of jQuery implements a high-level interface to do AJAX requests. jQuery implements this interface abstractly, shielding the developer from the complexity of multi-browser support in making the request.

How to retrieve current workspace using Jenkins Pipeline Groovy script?

A quick note for anyone who is using bat in the job and needs to access Workspace:

It won't work.

$WORKSPACE https://issues.jenkins-ci.org/browse/JENKINS-33511 as mentioned here only works with PowerShell. So your code should have powershell for execution

 stage('Verifying Workspace') {
  powershell label: '', script: 'dir $WORKSPACE'
}

How do you overcome the svn 'out of date' error?

I sometimes get this with TortoiseSVN on windows. The solution for me is to svn update the directory, even though there are no revisions to download or update. It does something to the metadata, which magically fixes it.

Python `if x is not None` or `if not x is None`?

Both Google and Python's style guide is the best practice:

if x is not None:
    # Do something about x

Using not x can cause unwanted results.

See below:

>>> x = 1
>>> not x
False
>>> x = [1]
>>> not x
False
>>> x = 0
>>> not x
True
>>> x = [0]         # You don't want to fall in this one.
>>> not x
False

You may be interested to see what literals are evaluated to True or False in Python:


Edit for comment below:

I just did some more testing. not x is None doesn't negate x first and then compared to None. In fact, it seems the is operator has a higher precedence when used that way:

>>> x
[0]
>>> not x is None
True
>>> not (x is None)
True
>>> (not x) is None
False

Therefore, not x is None is just, in my honest opinion, best avoided.


More edit:

I just did more testing and can confirm that bukzor's comment is correct. (At least, I wasn't able to prove it otherwise.)

This means if x is not None has the exact result as if not x is None. I stand corrected. Thanks bukzor.

However, my answer still stands: Use the conventional if x is not None. :]

How do I get countifs to select all non-blank cells in Excel?

In Excel 2010, You have the countifS function.

I was having issues if I was trying to count the number of cells in a range that have a non0 value.

e.g. If you had a worksheet that in the range A1:A10 had values 1, 0, 2, 3, 0 and you wanted the answer 3.

The normal function =COUNTIF(A1:A10,"<>0") would give you 8 as it is counting the blank cells as 0s.

My solution to this is to use the COUNTIFS function with the same range but multiple criteria e.g.

=COUNTIFS(A1:A10,"<>0",A1:A10,"<>")

This effectively checks if the range is non 0 and is non blank.

Javascript Equivalent to C# LINQ Select

Take a peek at underscore.js which provides many linq like functions. In the example you give you would use the map function.

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-6: invalid data

Temporary workaround: unicode(urllib2.urlopen(url).read(), 'utf8') - this should work if what is returned is UTF-8.

urlopen().read() return bytes and you have to decode them to unicode strings. Also it would be helpful to check the patch from http://bugs.python.org/issue4733

How to identify platform/compiler from preprocessor macros?

Here's what I use:

#ifdef _WIN32 // note the underscore: without it, it's not msdn official!
    // Windows (x64 and x86)
#elif __unix__ // all unices, not all compilers
    // Unix
#elif __linux__
    // linux
#elif __APPLE__
    // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though...
#endif

EDIT: Although the above might work for the basics, remember to verify what macro you want to check for by looking at the Boost.Predef reference pages. Or just use Boost.Predef directly.

Passing multiple argument through CommandArgument of Button in Asp.net

If you want to pass two values, you can use this approach

<asp:LinkButton ID="RemoveFroRole" Text="Remove From Role" runat="server"
CommandName='<%# Eval("UserName") %>' CommandArgument='<%# Eval("RoleName") %>'
 OnClick="RemoveFromRole_Click" />

Basically I am treating {CommmandName,CommandArgument} as key value. Set both from database field. You will have to use OnClick event and use OnCommand event in this case, which I think is more clean code.

How can I play sound in Java?

This thread is rather old but I have determined an option that could prove useful.

Instead of using the Java AudioStream library you could use an external program like Windows Media Player or VLC and run it with a console command through Java.

String command = "\"C:/Program Files (x86)/Windows Media Player/wmplayer.exe\" \"C:/song.mp3\"";
try {
    Process p = Runtime.getRuntime().exec(command);
catch (IOException e) {
    e.printStackTrace();
}

This will also create a separate process that can be controlled it the program.

p.destroy();

Of course this will take longer to execute than using an internal library but there may be programs that can start up faster and possibly without a GUI given certain console commands.

If time is not of the essence then this is useful.

How to programmatically move, copy and delete files and directories on SD?

Xamarin Android

public static bool MoveFile(string CurrentFilePath, string NewFilePath)
{
    try
    {
        using (var f = new File(CurrentFilePath))
        using (var i = new FileInputStream(f))
        using (var o = new FileOutputStream(NewFilePath))
        {
            i.Channel.TransferTo(0, i.Channel.Size(), o.Channel);
            f.Delete();
        }

        return true;
    }
    catch { return false; }
}

public static bool CopyFile(string CurrentFilePath, string NewFilePath)
{
    try
    {
        using (var i = new FileInputStream(CurrentFilePath))
        using (var o = new FileOutputStream(NewFilePath))
            i.Channel.TransferTo(0, i.Channel.Size(), o.Channel);

        return true;
    }
    catch { return false; }
}

public static bool DeleteFile(string FilePath)
{
    try
    {
        using (var file = new File(FilePath))
            file.Delete();

        return true;
    }
    catch { return false; }
}

How do you fix a MySQL "Incorrect key file" error when you can't repair the table?

Simple "REPAIR the table" from PHPMYADMIN solved this problem for me.

  1. go to phpmyadmin
  2. open problematic table
  3. go to Operations tab (in my version of PMA)
  4. at the bottom you will find "Repair table" link

how to refresh Select2 dropdown menu after ajax loading different content?

select2 has the placeholder parameter. Use that one

$("#state").select2({
   placeholder: "Choose a Country"
 });

Python + Django page redirect

It's simple:

from django.http import HttpResponseRedirect

def myview(request):
    ...
    return HttpResponseRedirect("/path/")

More info in the official Django docs

Update: Django 1.0

There is apparently a better way of doing this in Django now using generic views.

Example -

from django.views.generic.simple import redirect_to

urlpatterns = patterns('',   
    (r'^one/$', redirect_to, {'url': '/another/'}),

    #etc...
)

There is more in the generic views documentation. Credit - Carles Barrobés.

Update #2: Django 1.3+

In Django 1.5 redirect_to no longer exists and has been replaced by RedirectView. Credit to Yonatan

from django.views.generic import RedirectView

urlpatterns = patterns('',
    (r'^one/$', RedirectView.as_view(url='/another/')),
)

How to use Macro argument as string literal?

Use the preprocessor # operator:

#define CALL_DO_SOMETHING(VAR) do_something(#VAR, VAR);

MySQL joins and COUNT(*) from another table

MySQL use HAVING statement for this tasks.

Your query would look like this:

SELECT g.group_id, COUNT(m.member_id) AS members
FROM groups AS g
LEFT JOIN group_members AS m USING(group_id)
GROUP BY g.group_id
HAVING members > 4

example when references have different names

SELECT g.id, COUNT(m.member_id) AS members
FROM groups AS g
LEFT JOIN group_members AS m ON g.id = m.group_id
GROUP BY g.id
HAVING members > 4

Also, make sure that you set indexes inside your database schema for keys you are using in JOINS as it can affect your site performance.

Do I need to compile the header files in a C program?

In some systems, attempts to speed up the assembly of fully resolved '.c' files call the pre-assembly of include files "compiling header files". However, it is an optimization technique that is not necessary for actual C development.

Such a technique basically computed the include statements and kept a cache of the flattened includes. Normally the C toolchain will cut-and-paste in the included files recursively, and then pass the entire item off to the compiler. With a pre-compiled header cache, the tool chain will check to see if any of the inputs (defines, headers, etc) have changed. If not, then it will provide the already flattened text file snippets to the compiler.

Such systems were intended to speed up development; however, many such systems were quite brittle. As computers sped up, and source code management techniques changed, fewer of the header pre-compilers are actually used in the common project.

Until you actually need compilation optimization, I highly recommend you avoid pre-compiling headers.

Android Studio - debug keystore

It is at the same location: ~/.android/debug.keystore

A general tree implementation?

I've published a Python [3] tree implementation on my site: http://www.quesucede.com/page/show/id/python_3_tree_implementation.

Hope it is of use,

Ok, here's the code:

import uuid

def sanitize_id(id):
    return id.strip().replace(" ", "")

(_ADD, _DELETE, _INSERT) = range(3)
(_ROOT, _DEPTH, _WIDTH) = range(3)

class Node:

    def __init__(self, name, identifier=None, expanded=True):
        self.__identifier = (str(uuid.uuid1()) if identifier is None else
                sanitize_id(str(identifier)))
        self.name = name
        self.expanded = expanded
        self.__bpointer = None
        self.__fpointer = []

    @property
    def identifier(self):
        return self.__identifier

    @property
    def bpointer(self):
        return self.__bpointer

    @bpointer.setter
    def bpointer(self, value):
        if value is not None:
            self.__bpointer = sanitize_id(value)

    @property
    def fpointer(self):
        return self.__fpointer

    def update_fpointer(self, identifier, mode=_ADD):
        if mode is _ADD:
            self.__fpointer.append(sanitize_id(identifier))
        elif mode is _DELETE:
            self.__fpointer.remove(sanitize_id(identifier))
        elif mode is _INSERT:
            self.__fpointer = [sanitize_id(identifier)]

class Tree:

    def __init__(self):
        self.nodes = []

    def get_index(self, position):
        for index, node in enumerate(self.nodes):
            if node.identifier == position:
                break
        return index

    def create_node(self, name, identifier=None, parent=None):

        node = Node(name, identifier)
        self.nodes.append(node)
        self.__update_fpointer(parent, node.identifier, _ADD)
        node.bpointer = parent
        return node

    def show(self, position, level=_ROOT):
        queue = self[position].fpointer
        if level == _ROOT:
            print("{0} [{1}]".format(self[position].name, self[position].identifier))
        else:
            print("\t"*level, "{0} [{1}]".format(self[position].name, self[position].identifier))
        if self[position].expanded:
            level += 1
            for element in queue:
                self.show(element, level)  # recursive call

    def expand_tree(self, position, mode=_DEPTH):
        # Python generator. Loosly based on an algorithm from 'Essential LISP' by
        # John R. Anderson, Albert T. Corbett, and Brian J. Reiser, page 239-241
        yield position
        queue = self[position].fpointer
        while queue:
            yield queue[0]
            expansion = self[queue[0]].fpointer
            if mode is _DEPTH:
                queue = expansion + queue[1:]  # depth-first
            elif mode is _WIDTH:
                queue = queue[1:] + expansion  # width-first

    def is_branch(self, position):
        return self[position].fpointer

    def __update_fpointer(self, position, identifier, mode):
        if position is None:
            return
        else:
            self[position].update_fpointer(identifier, mode)

    def __update_bpointer(self, position, identifier):
        self[position].bpointer = identifier

    def __getitem__(self, key):
        return self.nodes[self.get_index(key)]

    def __setitem__(self, key, item):
        self.nodes[self.get_index(key)] = item

    def __len__(self):
        return len(self.nodes)

    def __contains__(self, identifier):
        return [node.identifier for node in self.nodes if node.identifier is identifier]

if __name__ == "__main__":

    tree = Tree()
    tree.create_node("Harry", "harry")  # root node
    tree.create_node("Jane", "jane", parent = "harry")
    tree.create_node("Bill", "bill", parent = "harry")
    tree.create_node("Joe", "joe", parent = "jane")
    tree.create_node("Diane", "diane", parent = "jane")
    tree.create_node("George", "george", parent = "diane")
    tree.create_node("Mary", "mary", parent = "diane")
    tree.create_node("Jill", "jill", parent = "george")
    tree.create_node("Carol", "carol", parent = "jill")
    tree.create_node("Grace", "grace", parent = "bill")
    tree.create_node("Mark", "mark", parent = "jane")

    print("="*80)
    tree.show("harry")
    print("="*80)
    for node in tree.expand_tree("harry", mode=_WIDTH):
        print(node)
    print("="*80)

copy from one database to another using oracle sql developer - connection failed

The copy command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.

Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).

I tried a variation of your command as follows in SQL*Plus (with no errors):

copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;

After I executed the above statement, I also truncate the new_emp table and executed this command:

copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;

With SQL Developer, you could do the following to perform a similar approach to copying objects:

  1. On the tool bar, select Tools>Database copy.

  2. Identify source and destination connections with the copy options you would like. enter image description here

  3. For object type, select table(s). enter image description here

  4. Specify the specific table(s) (e.g. table1). enter image description here

The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).

SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable

In my case I was using linux and putting double quote around the path inside local.properties like

sdk.dir = "/root/Android/Sdk/"
export ANDROID_SDK_ROOT = "/root/Android/Sdk/"

So it should be

sdk.dir = /root/Android/Sdk/
export ANDROID_SDK_ROOT = /root/Android/Sdk/

and .bash_profile

enter image description here

How to get list of dates between two dates in mysql select query

Try:

select * from 
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'

-for date ranges up to nearly 300 years in the future.

[Corrected following a suggested edit by UrvishAtSynapse.]

How to import a module in Python with importlib.import_module

And don't forget to create a __init__.py with each folder/subfolder (even if they are empty)

Programmatically change input type of the EditText from PASSWORD to NORMAL & vice versa

some dynamic situation holder.edit_pin.setInputType(InputType.TYPE_CLASS_NUMBER); will not work so better use both like that

holder.edit_pin.setInputType(InputType.TYPE_CLASS_NUMBER);
holder.edit_pin.setTransformationMethod(PasswordTransformationMethod.getInstance());

Note : this is suitable for when you are using dynamic controls like using arrayaapter

Combining two expressions (Expression<Func<T, bool>>)

I suggest one more improvement to PredicateBuilder and ExpressionVisitor solutions. I called it UnifyParametersByName and you can find it in MIT library of mine: LinqExprHelper. It allows for combining arbitary lambda expressions. Usually the questions are asked about predicate expression, but this idea extends to projection expressions as well.

The following code employs a method ExprAdres which creates a complicated parametrized expression, using inline lambda. This complicated expression is coded only once, and then reused, thanks to the LinqExprHelper mini-library.

public IQueryable<UbezpExt> UbezpFull
{
    get
    {
        System.Linq.Expressions.Expression<
            Func<UBEZPIECZONY, UBEZP_ADRES, UBEZP_ADRES, UbezpExt>> expr =
            (u, parAdrM, parAdrZ) => new UbezpExt
            {
                Ub = u,
                AdrM = parAdrM,
                AdrZ = parAdrZ,
            };

        // From here an expression builder ExprAdres is called.
        var expr2 = expr
            .ReplacePar("parAdrM", ExprAdres("M").Body)
            .ReplacePar("parAdrZ", ExprAdres("Z").Body);
        return UBEZPIECZONY.Select((Expression<Func<UBEZPIECZONY, UbezpExt>>)expr2);
    }
}

And this is the subexpression building code:

public static Expression<Func<UBEZPIECZONY, UBEZP_ADRES>> ExprAdres(string sTyp)
{
    return u => u.UBEZP_ADRES.Where(a => a.TYP_ADRESU == sTyp)
        .OrderByDescending(a => a.DATAOD).FirstOrDefault();
}

What I tried to achieve was to perform parametrized queries without need to copy-paste and with ability to use inline lambdas, which are so pretty. Without all these helper-expression stuff, I would be forced to create whole query in one go.

"SDK Platform Tools component is missing!"

I have been faced with a similar problem with SDK 24.0.2, and ADT 23.0, on windows 7 and Eclipse Luna (4.4.0). The android SDK Manager comes with default Proxy IP of 127.0.0.1 (localhost) and port 8081. So as you try to run the SDK Managers as advised by earlier solutions, it will try to connect through the default proxy settings, which keep on failing(...at least on my system). Therefore, if you do not need proxy settings, simply clear default proxy settings (i.e. remove proxy server IP and Port, leaving the fields empty). Otherwise set them as necessary. To access these settings in eclipse, go Window-> Android SDK Manager->Tools->Options.

Hope this helps someone.

C compile error: "Variable-sized object may not be initialized"

The array is not initialized with the memory specified anf throws an error variable sized array may not be initialised I prefer usual way of initialization,

for (i = 0; i <= bins; i++)
        arr[i] = 0;

Access to ES6 array element index inside for-of loop

in html/js context, on modern browsers, with other iterable objects than Arrays we could also use [Iterable].entries():

for(let [index, element] of document.querySelectorAll('div').entries()) {

    element.innerHTML = '#' + index

}

How to change max_allowed_packet size

For anyone running MySQL on Amazon RDS service, this change is done via parameter groups. You need to create a new PG or use an existing one (other than the default, which is read-only).

You should search for the max_allowed_packet parameter, change its value, and then hit save.

Back in your MySQL instance, if you created a new PG, you should attach the PG to your instance (you may need a reboot). If you changed a PG that was already attached to your instance, changes will be applied without reboot, to all your instances that have that PG attached.

HTML Form: Select-Option vs Datalist-Option

Datalist includes autocomplete and suggestions natively, it can also allow a user to enter a value that is not defined in the suggestions.

Select only gives you pre-defined options the user has to select from

What does $ mean before a string?

It signifies string interpolation.

It will protect you because it is adding compilation time protection on the string evaluation.

You will no longer get an exception with string.Format("{0}{1}",secondParamIsMissing)

How to Diff between local uncommitted changes and origin

If you want to compare files visually you can use:

git difftool

It will start your diff app automatically for each changed file.

PS: If you did not set a diff app, you can do it like in the example below(I use Winmerge):

git config --global merge.tool winmerge
git config --replace --global mergetool.winmerge.cmd "\"C:\Program Files (x86)\WinMerge\WinMergeU.exe\" -e -u -dl \"Base\" -dr \"Mine\" \"$LOCAL\" \"$REMOTE\" \"$MERGED\""
git config --global mergetool.prompt false

How can I find the dimensions of a matrix in Python?

You may use as following to get Height and Weight of an Numpy array:

int height = arr.shape[0]
int weight = arr.shape[1]

If your array has multiple dimensions, you can increase the index to access them.

Filtering by Multiple Specific Model Properties in AngularJS (in OR relationship)

Here's simple solution for those who want a quick filter against an object:

<select>
  <option ng-repeat="card in deck.Cards | filter: {Type: 'Face'}">{{card.Name}}</option>
</select>

The array filter lets you mimic the object you are trying to filter. In the above case, the following classes would work just fine:

var card = function(name, type) {
  var _name = name;
  var _type = type;

  return {
    Name: _name,
    Type: _type
  };
};

And where the deck might look like:

var deck = function() {
  var _cards = [new card('Jack', 'Face'),
                new card('7', 'Numeral')];

  return {
    Cards: _cards
  };
};

And if you want to filter multiple properties of the object just separate field names by a comma:

<select>
  <option ng-repeat="card in deck.Cards | filter: {Type: 'Face', Name: 'Jack'}">{{card.Name}}</option>
</select>

EDIT: Here's a working plnkr that provides an example of single and multiple property filters:

http://embed.plnkr.co/i0wCx6l1WPYljk57SXzV/

Rewrite all requests to index.php with nginx

1 unless file exists will rewrite to index.php

Add the following to your location ~ \.php$

try_files = $uri @missing;

this will first try to serve the file and if it's not found it will move to the @missing part. so also add the following to your config (outside the location block), this will redirect to your index page

location @missing {
    rewrite ^ $scheme://$host/index.php permanent;
}

2 on the urls you never see the file extension (.php)

to remove the php extension read the following: http://www.nullis.net/weblog/2011/05/nginx-rewrite-remove-file-extension/

and the example configuration from the link:

location / {
    set $page_to_view "/index.php";
    try_files $uri $uri/ @rewrites;
    root   /var/www/site;
    index  index.php index.html index.htm;
}

location ~ \.php$ {
    include /etc/nginx/fastcgi_params;
    fastcgi_pass  127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME /var/www/site$page_to_view;
}

# rewrites
location @rewrites {
    if ($uri ~* ^/([a-z]+)$) {
        set $page_to_view "/$1.php";
        rewrite ^/([a-z]+)$ /$1.php last;
    }
}

Spring transaction REQUIRED vs REQUIRES_NEW : Rollback Transaction

If you really need to do it in separate transaction you need to use REQUIRES_NEW and live with the performance overhead. Watch out for dead locks.

I'd rather do it the other way:

  • Validate data on Java side.
  • Run everyting in one transaction.
  • If anything goes wrong on DB side -> it's a major error of DB or validation design. Rollback everything and throw critical top level error.
  • Write good unit tests.

Is there any advantage of using map over unordered_map in case of trivial keys?

Small addition to all of above:

Better use map, when you need to get elements by range, as they are sorted and you can just iterate over them from one boundary to another.

Hashcode and Equals for Hashset

  1. There's no need to call equals if hashCode differs.
  2. There's no need to call hashCode if (obj1 == obj2).
  3. There's no need for hashCode and/or equals just to iterate - you're not comparing objects
  4. When needed to distinguish in between objects.

SSL Error When installing rubygems, Unable to pull data from 'https://rubygems.org/

For windows users

Goto link http://rubygems.org/pages/download

  1. Download the latest zip file (In my case 2.4.5)
  2. Unzip it
  3. run "ruby setup.rb" in unzipped folder
  4. now run gem install command

event Action<> vs event EventHandler<>

The advantage of a wordier approach comes when your code is inside a 300,000 line project.

Using the action, as you have, there is no way to tell me what bool, int, and Blah are. If your action passed an object that defined the parameters then ok.

Using an EventHandler that wanted an EventArgs and if you would complete your DiagnosticsArgs example with getters for the properties that commented their purpose then you application would be more understandable. Also, please comment or fully name the arguments in the DiagnosticsArgs constructor.

How do I create a unique ID in Java?

Create a UUID.

String uniqueID = UUID.randomUUID().toString();

git push to specific branch

git push origin amd_qlp_tester will work for you. If you just type git push, then the remote of the current branch is the default value.

Syntax of push looks like this - git push <remote> <branch>. If you look at your remote in .git/config file, you will see an entry [remote "origin"] which specifies url of the repository. So, in the first part of command you will tell Git where to find repository for this project, and then you just specify a branch.

How to round the minute of a datetime object

A straightforward approach:

def round_time(dt, round_to_seconds=60):
    """Round a datetime object to any number of seconds
    dt: datetime.datetime object
    round_to_seconds: closest number of seconds for rounding, Default 1 minute.
    """
    rounded_epoch = round(dt.timestamp() / round_to_seconds) * round_to_seconds
    rounded_dt = datetime.datetime.fromtimestamp(rounded_epoch).astimezone(dt.tzinfo)
    return rounded_dt

Failed to resolve: com.android.support:appcompat-v7:28.0

my problem was just network connection. using VPN solved the issue.

List of <p:ajax> events

You might want to look at "JavaScript HTML DOM Events" for a general overview of events:

http://www.w3schools.com/jsref/dom_obj_event.asp

PrimeFaces is built on jQuery, so here's jQuery's "Events" documentation:

http://api.jquery.com/category/events/

http://api.jquery.com/category/events/form-events/

http://api.jquery.com/category/events/keyboard-events/

http://api.jquery.com/category/events/mouse-events/

http://api.jquery.com/category/events/browser-events/

Below, I've listed some of the more common events, with comments about where they can be used (taken from jQuery documentation).

Mouse Events

(Any HTML element can receive these events.)

click

dblclick

mousedown

mousemove

mouseover

mouseout

mouseup

Keyboard Events

(These events can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for these event types.)

keydown

keypress

keyup

Form Events

blur (In recent browsers, the domain of the event has been extended to include all element types.)

change (This event is limited to <input> elements, <textarea> boxes and <select> elements.)

focus (This event is implicitly applicable to a limited set of elements, such as form elements (<input>, <select>, etc.) and links (<a href>). In recent browser versions, the event can be extended to include all element types by explicitly setting the element's tabindex property. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.)

select (This event is limited to <input type="text"> fields and <textarea> boxes.)

submit (It can only be attached to <form> elements.)

getResourceAsStream() vs FileInputStream

I am here by separating both the usages by marking them as File Read(java.io) and Resource Read(ClassLoader.getResourceAsStream()).

File Read - 1. Works on local file system. 2. Tries to locate the file requested from current JVM launched directory as root 3. Ideally good when using files for processing in a pre-determined location like,/dev/files or C:\Data.

Resource Read - 1. Works on class path 2. Tries to locate the file/resource in current or parent classloader classpath. 3. Ideally good when trying to load files from packaged files like war or jar.

How I can print to stderr in C?

The syntax is almost the same as printf. With printf you give the string format and its contents ie:

printf("my %s has %d chars\n", "string format", 30);

With fprintf it is the same, except now you are also specifying the place to print to:

File *myFile;
...
fprintf( myFile, "my %s has %d chars\n", "string format", 30);

Or in your case:

fprintf( stderr, "my %s has %d chars\n", "string format", 30);

open read and close a file in 1 line of code

I think the most natural way for achieving this is to define a function.

def read(filename):
    f = open(filename, 'r')
    output = f.read()
    f.close()
    return output

Then you can do the following:

output = read('pagehead.section.htm')

How to install older version of node.js on Windows?

You can use Nodist for this purpose. Download it from here.

Usage:

nodist                         List all installed node versions.
nodist list
nodist ls

nodist <version>               Use the specified node version globally (downloads the executable, if necessary).
nodist latest                  Use the latest available node version globally (downloads the executable, if necessary).

nodist add <version>           Download the specified node version.

More Nodist commands here

Submit form and stay on same page?

The HTTP/CGI way to do this would be for your program to return an HTTP status code of 204 (No Content).

The split() method in Java does not work on a dot (.)

Try:

String words[]=temp.split("\\.");

The method is:

String[] split(String regex) 

"." is a reserved char in regex

HTML: Select multiple as dropdown

Because you're using multiple. Despite it still technically being a dropdown, it doesn't look or act like a standard dropdown. Rather, it populates a list box and lets them select multiple options.

Size determines how many options appear before they have to click down or up to see the other options.

I have a feeling what you want to achieve is only going to be possible with a JavaScript plugin.

Some examples:

jQuery multiselect drop down menu

http://labs.abeautifulsite.net/archived/jquery-multiSelect/demo/

Selecting multiple columns in a Pandas dataframe

In [39]: df
Out[39]: 
   index  a  b  c
0      1  2  3  4
1      2  3  4  5

In [40]: df1 = df[['b', 'c']]

In [41]: df1
Out[41]: 
   b  c
0  3  4
1  4  5

Git, fatal: The remote end hung up unexpectedly

Seems almost pointless to add an answer, but I was fighting this for ages when I finally discovered it was Visual Studio Online that was suffering a sporadic outage. That became apparent when VS kept prompting for creds and the VSO website sometimes gave a 500.

Counting objects: 138816, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (38049/38049), done.
error: unable to rewind rpc post data - try increasing http.postBuffer
error: RPC failed; curl 56 SSL read: error:00000000:lib(0):func(0):reason(0), errno 10054
The remote end hung up unexpectedly/138816), 33.30 MiB | 3.00 KiB/s
Writing objects: 100% (138816/138816), 50.21 MiB | 3.00 KiB/s, done.
Total 138816 (delta 100197), reused 134574 (delta 96515)
fatal: The remote end hung up unexpectedly
Everything up-to-date

I set my HTTP post buffer back to 2 MB afterwards, since I actually think it works better with many smaller posts.

How to configure SMTP settings in web.config

Web.Config file:

<configuration>
 <system.net>
        <mailSettings>
            <smtp from="[email protected]">
                <network host="smtp.gmail.com" 
                 port="587" 
                 userName="[email protected]" 
                 password="yourpassword" 
                 enableSsl="true"/>
            </smtp>
        </mailSettings>
</system.net>
</configuration>

Matplotlib connect scatterplot points with line - Python

I think @Evert has the right answer:

plt.scatter(dates,values)
plt.plot(dates, values)
plt.show()

Which is pretty much the same as

plt.plot(dates, values, '-o')
plt.show()

or whatever linestyle you prefer.

Zoom to fit: PDF Embedded in HTML

For me this worked(I wanted to zoom in since the container of my pdf was small):

    <embed src="filename.pdf#page=1&zoom=300" width="575" height="500">

How do I calculate the date six months from the current date using the datetime Python module?

import datetime


'''
Created on 2011-03-09

@author: tonydiep
'''

def add_business_months(start_date, months_to_add):
    """
    Add months in the way business people think of months. 
    Jan 31, 2011 + 1 month = Feb 28, 2011 to business people
    Method: Add the number of months, roll back the date until it becomes a valid date
    """
    # determine year
    years_change = months_to_add / 12

    # determine if there is carryover from adding months
    if (start_date.month + (months_to_add % 12) > 12 ):
        years_change = years_change + 1

    new_year = start_date.year + years_change

    # determine month
    work = months_to_add % 12
    if 0 == work:
        new_month = start_date.month
    else:
        new_month = (start_date.month + (work % 12)) % 12

    if 0 == new_month:
        new_month = 12 

    # determine day of the month
    new_day = start_date.day
    if(new_day in [31, 30, 29, 28]):
        #user means end of the month
        new_day = 31


    new_date = None
    while (None == new_date and 27 < new_day):
        try:
            new_date = start_date.replace(year=new_year, month=new_month, day=new_day)
        except:
            new_day = new_day - 1   #wind down until we get to a valid date

    return new_date


if __name__ == '__main__':
    #tests
    dates = [datetime.date(2011, 1, 31),
             datetime.date(2011, 2, 28),
             datetime.date(2011, 3, 28),
             datetime.date(2011, 4, 28),
             datetime.date(2011, 5, 28),
             datetime.date(2011, 6, 28),
             datetime.date(2011, 7, 28),
             datetime.date(2011, 8, 28),
             datetime.date(2011, 9, 28),
             datetime.date(2011, 10, 28),
             datetime.date(2011, 11, 28),
             datetime.date(2011, 12, 28),
             ]
    months = range(1, 24)
    for start_date in dates:
        for m in months:
            end_date = add_business_months(start_date, m)
            print("%s\t%s\t%s" %(start_date, end_date, m))

How can I split a delimited string into an array in PHP?

Use explode() or preg_split() function to split the string in php with given delimiter

// Use preg_split() function 
$string = "123,456,78,000";  
$str_arr = preg_split ("/\,/", $string);  
print_r($str_arr); 
  
// use of explode 
$string = "123,46,78,000"; 
$str_arr = explode (",", $string);  
print_r($str_arr); 

Why can't I define a default constructor for a struct in .NET?

A struct is a value type and a value type must have a default value as soon as it is declared.

MyClass m;
MyStruct m2;

If you declare two fields as above without instantiating either, then break the debugger, m will be null but m2 will not. Given this, a parameterless constructor would make no sense, in fact all any constructor on a struct does is assign values, the thing itself already exists just by declaring it. Indeed m2 could quite happily be used in the above example and have its methods called, if any, and its fields and properties manipulated!

Initialise a list to a specific length in Python

If the "default value" you want is immutable, @eduffy's suggestion, e.g. [0]*10, is good enough.

But if you want, say, a list of ten dicts, do not use [{}]*10 -- that would give you a list with the same initially-empty dict ten times, not ten distinct ones. Rather, use [{} for i in range(10)] or similar constructs, to construct ten separate dicts to make up your list.

number_format() with MySQL

FORMAT(X,D) Formats the number X to a format like '#,###,###.##', rounded to D decimal places, and returns the result as a string. If D is 0, the result has no decimal point or fractional part.

 SELECT FORMAT(12332.123456, 4);
        -> '12,332.1235'

Set QLineEdit to accept only numbers

QLineEdit::setValidator(), for example:

myLineEdit->setValidator( new QIntValidator(0, 100, this) );

or

myLineEdit->setValidator( new QDoubleValidator(0, 100, 2, this) );

See: QIntValidator, QDoubleValidator, QLineEdit::setValidator

ImportError: No module named mysql.connector using Python2

In my case i already installed the package

pip install mysql-connector
pip install mysql-connector-python

It giving me the same error so, i uninstall the both package by using

pip uninstall mysql-connector
pip uninstall mysql-connector-python

and then again install the second package only

pip install mysql-connector-python

This solution worked for me.

How do I debug a stand-alone VBScript script?

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

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

Moq, SetupGet, Mocking a property

ColumnNames is a property of type List<String> so when you are setting up you need to pass a List<String> in the Returns call as an argument (or a func which return a List<String>)

But with this line you are trying to return just a string

input.SetupGet(x => x.ColumnNames).Returns(temp[0]);

which is causing the exception.

Change it to return whole list:

input.SetupGet(x => x.ColumnNames).Returns(temp);

How to allow user to pick the image with Swift?

@IBAction func ImportImage(_ sender: Any)
{
    let image = UIImagePickerController()
    image.delegate = self

    image.sourceType = UIImagePickerController.SourceType.photoLibrary

    image.allowsEditing = false

    self.present(image, animated: true)
    {
        //After it is complete
    }


}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
    {
        myimage.image = image
    }
    else{
        //
    }
    self.dismiss(animated: true, completion: nil)

    do {
        try context.save()
    } catch {
        print("Could not save. \(error), \(error.localizedDescription)")
    }

}

Add UINavigationControllerDelegate, UIImagePickerControllerDelegate delegates in the class definition

How do you performance test JavaScript code?

Performance testing became something of a buzzword as of late but that’s not to say that performance testing is not an important process in QA or even after the product has shipped. And while I develop the app I use many different tools, some of them mentioned above like the chrome Profiler I usually look at a SaaS or something opensource that I can get going and forget about it until I get that alert saying that something went belly up.

There are lots of awesome tools that will help you keep an eye on performance without having you jump through hoops just to get some basics alerts set up. Here are a few that I think are worth checking out for yourself.

  1. Sematext.com
  2. Datadog.com
  3. Uptime.com
  4. Smartbear.com
  5. Solarwinds.com

To try and paint a clearer picture, here is a little tutorial on how to set up monitoring for a react application.

Disabling right click on images using jquery

Would it be possible to leave the ability to right click and download just when done a separate watermark is placed on the image. Of course this won't prevent screen shots but thought it may be a good middle ground.

Count Rows in Doctrine QueryBuilder

Example working with grouping, union and stuff.

Problem:

 $qb = $em->createQueryBuilder()
     ->select('m.id', 'rm.id')
     ->from('Model', 'm')
     ->join('m.relatedModels', 'rm')
     ->groupBy('m.id');

For this to work possible solution is to use custom hydrator and this weird thing called 'CUSTOM OUTPUT WALKER HINT':

class CountHydrator extends AbstractHydrator
{
    const NAME = 'count_hydrator';
    const FIELD = 'count';

    /**
     * {@inheritDoc}
     */
    protected function hydrateAllData()
    {
        return (int)$this->_stmt->fetchColumn(0);
    }
}
class CountSqlWalker extends SqlWalker
{
    /**
     * {@inheritDoc}
     */
    public function walkSelectStatement(AST\SelectStatement $AST)
    {
        return sprintf("SELECT COUNT(*) AS %s FROM (%s) AS t", CountHydrator::FIELD, parent::walkSelectStatement($AST));
    }
}

$doctrineConfig->addCustomHydrationMode(CountHydrator::NAME, CountHydrator::class);
// $qb from example above
$countQuery = clone $qb->getQuery();
// Doctrine bug ? Doesn't make a deep copy... (as of "doctrine/orm": "2.4.6")
$countQuery->setParameters($this->getQuery()->getParameters());
// set custom 'hint' stuff
$countQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, CountSqlWalker::class);

$count = $countQuery->getResult(CountHydrator::NAME);

WARNING: sanitizing unsafe style value url

In my case, I got the image URL before getting to the display component and want to use it as the background image so to use that URL I have to tell Angular that it's safe and can be used.

In .ts file

userImage: SafeStyle;
ngOnInit(){
    this.userImage = this.sanitizer.bypassSecurityTrustStyle('url(' + sessionStorage.getItem("IMAGE") + ')');
}

In .html file

<div mat-card-avatar class="nav-header-image" [style.background-image]="userImage"></div>

80-characters / right margin line in Sublime Text 3

Yes, it is possible both in Sublime Text 2 and 3 (which you should really upgrade to if you haven't already). Select View ? Ruler ? 80 (there are several other options there as well). If you like to actually wrap your text at 80 columns, select View ? Word Wrap Column ? 80. Make sure that View ? Word Wrap is selected.

To make your selections permanent (the default for all opened files or views), open Preferences ? Settings—User and use any of the following rules:

{
    // set vertical rulers in specified columns.
    // Use "rulers": [80] for just one ruler
    // default value is []
    "rulers": [80, 100, 120],

    // turn on word wrap for source and text
    // default value is "auto", which means off for source and on for text
    "word_wrap": true,

    // set word wrapping at this column
    // default value is 0, meaning wrapping occurs at window width
    "wrap_width": 80
}

These settings can also be used in a .sublime-project file to set defaults on a per-project basis, or in a syntax-specific .sublime-settings file if you only want them to apply to files written in a certain language (Python.sublime-settings vs. JavaScript.sublime-settings, for example). Access these settings files by opening a file with the desired syntax, then selecting Preferences ? Settings—More ? Syntax Specific—User.

As always, if you have multiple entries in your settings file, separate them with commas , except for after the last one. The entire content should be enclosed in curly braces { }. Basically, make sure it's valid JSON.

If you'd like a key combo to automatically set the ruler at 80 for a particular view/file, or you are interested in learning how to set the value without using the mouse, please see my answer here.

Finally, as mentioned in another answer, you really should be using a monospace font in order for your code to line up correctly. Other types of fonts have variable-width letters, which means one 80-character line may not appear to be the same length as another 80-character line with different content, and your indentations will look all messed up. Sublime has monospace fonts set by default, but you can of course choose any one you want. Personally, I really like Liberation Mono. It has glyphs to support many different languages and Unicode characters, looks good at a variety of different sizes, and (most importantly for a programming font) clearly differentiates between 0 and O (digit zero and capital letter oh) and 1 and l (digit one and lowercase letter ell), which not all monospace fonts do, unfortunately. Version 2.0 and later of the font are licensed under the open-source SIL Open Font License 1.1 (here is the FAQ).

WARNING in budgets, maximum exceeded for initial

Open angular.json file and find budgets keyword.

It should look like:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "2mb",
          "maximumError": "5mb"
       }
    ]

As you’ve probably guessed you can increase the maximumWarning value to prevent this warning, i.e.:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "4mb", <===
          "maximumError": "5mb"
       }
    ]

What does budgets mean?

A performance budget is a group of limits to certain values that affect site performance, that may not be exceeded in the design and development of any web project.

In our case budget is the limit for bundle sizes.

See also:

python: unhashable type error

I don't think converting to a tuple is the right answer. You need go and look at where you are calling the function and make sure that c is a list of list of strings, or whatever you designed this function to work with

For example you might get this error if you passed [c] to the function instead of c

Checking whether the pip is installed?

In CMD, type:

pip freeze

And it will show you a list of all the modules installed including the version number.

Output:

aiohttp==1.1.4
async-timeout==1.1.0
cx-Freeze==4.3.4
Django==1.9.2
django-allauth==0.24.1
django-cors-headers==1.2.2
django-crispy-forms==1.6.0
django-robots==2.0
djangorestframework==3.3.2
easygui==0.98.0
future==0.16.0
httpie==0.9.6
matplotlib==1.5.3
multidict==2.1.2
numpy==1.11.2
oauthlib==1.0.3
pandas==0.19.1
pefile==2016.3.28
pygame==1.9.2b1
Pygments==2.1.3
PyInstaller==3.2
pyparsing==2.1.10
pypiwin32==219
PyQt5==5.7
pytz==2016.7
requests==2.9.1
requests-oauthlib==0.6
six==1.10.0
sympy==1.0
virtualenv==15.0.3
xlrd==1.0.0
yarl==0.7.0

Create a SQL query to retrieve most recent records

The derived table would work, but if this is SQL 2005, a CTE and ROW_NUMBER might be cleaner:

WITH UserStatus (User, Date, Status, Notes, Ord)
as
(
SELECT Date, User, Status, Notes, 
     ROW_NUMBER() OVER (PARTITION BY User ORDER BY Date DESC)
FROM [SOMETABLE]
)

SELECT User, Date, Status, Notes from UserStatus where Ord = 1

This would also facilitate the display of the most recent x statuses from each user.

T-SQL How to create tables dynamically in stored procedures?

First up, you seem to be mixing table variables and tables.

Either way, You can't pass in the table's name like that. You would have to use dynamic TSQL to do that.

If you just want to declare a table variable:

CREATE PROC sp_createATable 
  @name        VARCHAR(10), 
  @properties  VARCHAR(500) 
AS 
  declare @tablename TABLE
  ( 
    id  CHAR(10)  PRIMARY KEY 
  ); 

The fact that you want to create a stored procedure to dynamically create tables might suggest your design is wrong.

LINQ-to-SQL vs stored procedures?

For basic data retrieval I would be going for Linq without hesitation.

Since moving to Linq I've found the following advantages:

  1. Debugging my DAL has never been easier.
  2. Compile time safety when your schema changes is priceless.
  3. Deployment is easier because everything is compiled into DLL's. No more managing deployment scripts.
  4. Because Linq can support querying anything that implements the IQueryable interface, you will be able to use the same syntax to query XML, Objects and any other datasource without having to learn a new syntax

Optimal way to concatenate/aggregate strings

SOLUTION

The definition of optimal can vary, but here's how to concatenate strings from different rows using regular Transact SQL, which should work fine in Azure.

;WITH Partitioned AS
(
    SELECT 
        ID,
        Name,
        ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Name) AS NameNumber,
        COUNT(*) OVER (PARTITION BY ID) AS NameCount
    FROM dbo.SourceTable
),
Concatenated AS
(
    SELECT 
        ID, 
        CAST(Name AS nvarchar) AS FullName, 
        Name, 
        NameNumber, 
        NameCount 
    FROM Partitioned 
    WHERE NameNumber = 1

    UNION ALL

    SELECT 
        P.ID, 
        CAST(C.FullName + ', ' + P.Name AS nvarchar), 
        P.Name, 
        P.NameNumber, 
        P.NameCount
    FROM Partitioned AS P
        INNER JOIN Concatenated AS C 
                ON P.ID = C.ID 
                AND P.NameNumber = C.NameNumber + 1
)
SELECT 
    ID,
    FullName
FROM Concatenated
WHERE NameNumber = NameCount

EXPLANATION

The approach boils down to three steps:

  1. Number the rows using OVER and PARTITION grouping and ordering them as needed for the concatenation. The result is Partitioned CTE. We keep counts of rows in each partition to filter the results later.

  2. Using recursive CTE (Concatenated) iterate through the row numbers (NameNumber column) adding Name values to FullName column.

  3. Filter out all results but the ones with the highest NameNumber.

Please keep in mind that in order to make this query predictable one has to define both grouping (for example, in your scenario rows with the same ID are concatenated) and sorting (I assumed that you simply sort the string alphabetically before concatenation).

I've quickly tested the solution on SQL Server 2012 with the following data:

INSERT dbo.SourceTable (ID, Name)
VALUES 
(1, 'Matt'),
(1, 'Rocks'),
(2, 'Stylus'),
(3, 'Foo'),
(3, 'Bar'),
(3, 'Baz')

The query result:

ID          FullName
----------- ------------------------------
2           Stylus
3           Bar, Baz, Foo
1           Matt, Rocks

How to show PIL Image in ipython notebook

case python3

from PIL import Image
from IPython.display import HTML
from io import BytesIO
from base64 import b64encode

pil_im = Image.open('data/empire.jpg')
b = BytesIO()  
pil_im.save(b, format='png')
HTML("<img src='data:image/png;base64,{0}'/>".format(b64encode(b.getvalue()).decode('utf-8')))

React "after render" code?

I am not going to pretend I know why this particular function works, however window.getComputedStyle works 100% of the time for me whenever I need to access DOM elements with a Ref in a useEffect — I can only presume it will work with componentDidMount as well.

I put it at the top of the code in a useEffect and it appears as if it forces the effect to wait for the elements to be painted before it continues with the next line of code, but without any noticeable delay such as using a setTimeout or an async sleep function. Without this, the Ref element returns as undefined when I try to access it.

const ref = useRef(null);

useEffect(()=>{
    window.getComputedStyle(ref.current);
    // Next lines of code to get element and do something after getComputedStyle().
});

return(<div ref={ref}></div>);

Generating random numbers in C

int *generate_randomnumbers(int start, int end){
    int *res = malloc(sizeof(int)*(end-start));
    srand(time(NULL));
    for (int i= 0; i < (end -start)+1; i++){
        int r = rand()%end + start;
        int dup = 0;
        for (int j = 0; j < (end -start)+1; j++){
            if (res[j] == r){
                i--;
                dup = 1;
                break;
            }
        }
        if (!dup)
            res[i] = r;
    }
    return res;
}

"A referral was returned from the server" exception when accessing AD from C#

A referral is sent by an AD server when it doesn't have the information requested itself, but know that another server have the info. It usually appears in trust environment where a DC can refer to a DC in trusted domain.

In your case you are only specifying a domain, relying on automatic lookup of what domain controller to use. I think that you should try to find out what domain controller is used for the query and look if that one really holds the requested information.

If you provide more information on your AD setup, including any trusts/subdomains, global catalogues and the DNS resource records for the domain controllers it will be easier to help you.

toggle show/hide div with button?

Try with opacity

_x000D_
_x000D_
div { transition: all 0.4s ease }_x000D_
.hide { opacity: 0; }
_x000D_
<input onclick="newpost.classList.toggle('hide')" type="button" value="toggle">_x000D_
_x000D_
<div id="newpost">Hello</div>
_x000D_
_x000D_
_x000D_

Use of the MANIFEST.MF file in Java

The content of the Manifest file in a JAR file created with version 1.0 of the Java Development Kit is the following.

Manifest-Version: 1.0

All the entries are as name-value pairs. The name of a header is separated from its value by a colon. The default manifest shows that it conforms to version 1.0 of the manifest specification. The manifest can also contain information about the other files that are packaged in the archive. Exactly what file information is recorded in the manifest will depend on the intended use for the JAR file. The default manifest file makes no assumptions about what information it should record about other files, so its single line contains data only about itself. Special-Purpose Manifest Headers

Depending on the intended role of the JAR file, the default manifest may have to be modified. If the JAR file is created only for the purpose of archival, then the MANIFEST.MF file is of no purpose. Most uses of JAR files go beyond simple archiving and compression and require special information to be in the manifest file. Summarized below are brief descriptions of the headers that are required for some special-purpose JAR-file functions

Applications Bundled as JAR Files: If an application is bundled in a JAR file, the Java Virtual Machine needs to be told what the entry point to the application is. An entry point is any class with a public static void main(String[] args) method. This information is provided in the Main-Class header, which has the general form:

Main-Class: classname

The value classname is to be replaced with the application's entry point.

Download Extensions: Download extensions are JAR files that are referenced by the manifest files of other JAR files. In a typical situation, an applet will be bundled in a JAR file whose manifest references a JAR file (or several JAR files) that will serve as an extension for the purposes of that applet. Extensions may reference each other in the same way. Download extensions are specified in the Class-Path header field in the manifest file of an applet, application, or another extension. A Class-Path header might look like this, for example:

Class-Path: servlet.jar infobus.jar acme/beans.jar

With this header, the classes in the files servlet.jar, infobus.jar, and acme/beans.jar will serve as extensions for purposes of the applet or application. The URLs in the Class-Path header are given relative to the URL of the JAR file of the applet or application.

Package Sealing: A package within a JAR file can be optionally sealed, which means that all classes defined in that package must be archived in the same JAR file. A package might be sealed to ensure version consistency among the classes in your software or as a security measure. To seal a package, a Name header needs to be added for the package, followed by a Sealed header, similar to this:

Name: myCompany/myPackage/
Sealed: true

The Name header's value is the package's relative pathname. Note that it ends with a '/' to distinguish it from a filename. Any headers following a Name header, without any intervening blank lines, apply to the file or package specified in the Name header. In the above example, because the Sealed header occurs after the Name: myCompany/myPackage header, with no blank lines between, the Sealed header will be interpreted as applying (only) to the package myCompany/myPackage.

Package Versioning: The Package Versioning specification defines several manifest headers to hold versioning information. One set of such headers can be assigned to each package. The versioning headers should appear directly beneath the Name header for the package. This example shows all the versioning headers:

Name: java/util/
Specification-Title: "Java Utility Classes" 
Specification-Version: "1.2"
Specification-Vendor: "Sun Microsystems, Inc.".
Implementation-Title: "java.util" 
Implementation-Version: "build57"
Implementation-Vendor: "Sun Microsystems, Inc."

html 5 audio tag width

Set it the same way you'd set the width of any other HTML element, with CSS:

audio { width: 200px; }

Note that audio is an inline element by default in Firefox, so you might also want to set it to display: block. Here's an example.

Is it possible to set a number to NaN or infinity?

When using Python 2.4, try

inf = float("9e999")
nan = inf - inf

I am facing the issue when I was porting the simplejson to an embedded device which running the Python 2.4, float("9e999") fixed it. Don't use inf = 9e999, you need convert it from string. -inf gives the -Infinity.

Create a Cumulative Sum Column in MySQL

Sample query

SET @runtot:=0;
SELECT
   q1.d,
   q1.c,
   (@runtot := @runtot + q1.c) AS rt
FROM
   (SELECT
       DAYOFYEAR(date) AS d,
       COUNT(*) AS c
    FROM  orders
    WHERE  hasPaid > 0
    GROUP  BY d
    ORDER  BY d) AS q1

How to install Python package from GitHub?

You need to use the proper git URL:

pip install git+https://github.com/jkbr/httpie.git#egg=httpie

Also see the VCS Support section of the pip documentation.

Don’t forget to include the egg=<projectname> part to explicitly name the project; this way pip can track metadata for it without having to have run the setup.py script.

Pass request headers in a jQuery AJAX GET call

_x000D_
_x000D_
$.ajax({_x000D_
            url: URL,_x000D_
            type: 'GET',_x000D_
            dataType: 'json',_x000D_
            headers: {_x000D_
                'header1': 'value1',_x000D_
                'header2': 'value2'_x000D_
            },_x000D_
            contentType: 'application/json; charset=utf-8',_x000D_
            success: function (result) {_x000D_
               // CallBack(result);_x000D_
            },_x000D_
            error: function (error) {_x000D_
                _x000D_
            }_x000D_
        });
_x000D_
_x000D_
_x000D_

how to calculate binary search complexity

A binary search works by dividing the problem in half repeatedly, something like this (details omitted):

Example looking for 3 in [4,1,3,8,5]

  1. Order your list of items [1,3,4,5,8]
  2. Look at the middle item (4),
    • If it is what you are looking for, stop
    • If it is greater, look at the first half
    • If it is less, look at the second half
  3. Repeat step 2 with the new list [1, 3], find 3 and stop

It is a bi-nary search when you divide the problem in 2.

The search only requires log2(n) steps to find the correct value.

I would recommend Introduction to Algorithms if you want to learn about algorithmic complexity.

How to make div go behind another div?

http://jsfiddle.net/f2znvn4f/


HTML

<div class="box-left-mini">
    <div class="front"><span>this is in front</span></div>
    <div class="behind_container">
        <div class="behind">behind</div>        
    </div>
</div>

CSS

.box-left-mini{
    float:left;
    background-image:url(website-content/hotcampaign.png);
    width:292px;
    height:141px;
}

.box-left-mini .front {
    display: block;
    z-index: 5;
    position: relative;
}
.box-left-mini .front span {
    background: #fff
}

.box-left-mini .behind_container {
    background-color: #ff0;
    position: relative;
    top: -18px;
}
.box-left-mini .behind {
    display: block;
    z-index: 3;
}

The reason you're getting so many different answers is because you've not explained what you want to do exactly. All the answers you get with code will be programmatically correct, but it's all down to what you want to achieve

What are these attributes: `aria-labelledby` and `aria-hidden`

The primary consumers of these properties are user agents such as screen readers for blind people. So in the case with a Bootstrap modal, the modal's div has role="dialog". When the screen reader notices that a div becomes visible which has this role, it'll speak the label for that div.

There are lots of ways to label things (and a few new ones with ARIA), but in some cases it is appropriate to use an existing element as a label (semantic) without using the <label> HTML tag. With HTML modals the label is usually a <h> header. So in the Bootstrap modal case, you add aria-labelledby=[IDofModalHeader], and the screen reader will speak that header when the modal appears.

Generally speaking a screen reader is going to notice whenever DOM elements become visible or invisible, so the aria-hidden property is frequently redundant and can probably be skipped in most cases.

Spring - @Transactional - What happens in background?

As a visual person, I like to weigh in with a sequence diagram of the proxy pattern. If you don't know how to read the arrows, I read the first one like this: Client executes Proxy.method().

  1. The client calls a method on the target from his perspective, and is silently intercepted by the proxy
  2. If a before aspect is defined, the proxy will execute it
  3. Then, the actual method (target) is executed
  4. After-returning and after-throwing are optional aspects that are executed after the method returns and/or if the method throws an exception
  5. After that, the proxy executes the after aspect (if defined)
  6. Finally the proxy returns to the calling client

Proxy Pattern Sequence Diagram (I was allowed to post the photo on condition that I mentioned its origins. Author: Noel Vaes, website: www.noelvaes.eu)

How do I convert a long to a string in C++?

The way I typically do it is with sprintf. So for a long you could do the following assuming that you are on a 32 bit architecture:

char buf[5] = {0}; // one extra byte for null    
sprintf(buf, "%l", var_for_long);

Best practices when running Node.js with port 80 (Ubuntu / Linode)

Drop root privileges after you bind to port 80 (or 443).

This allows port 80/443 to remain protected, while still preventing you from serving requests as root:

function drop_root() {
    process.setgid('nobody');
    process.setuid('nobody');
}

A full working example using the above function:

var process = require('process');
var http = require('http');
var server = http.createServer(function(req, res) {
    res.write("Success!");
    res.end();
});

server.listen(80, null, null, function() {
    console.log('User ID:',process.getuid()+', Group ID:',process.getgid());
    drop_root();
    console.log('User ID:',process.getuid()+', Group ID:',process.getgid());
});

See more details at this full reference.

What is the maximum value for an int32?

2GB

(is there a minimum length for answers?)

How to remove pip package after deleting it manually

packages installed using pip can be uninstalled completely using

pip uninstall <package>

refrence link

pip uninstall is likely to fail if the package is installed using python setup.py install as they do not leave behind metadata to determine what files were installed.

packages still show up in pip list if their paths(.pth file) still exist in your site-packages or dist-packages folder. You'll need to remove them as well in case you're removing using rm -rf

Executing Shell Scripts from the OS X Dock?

I think this thread may be helpful: http://forums.macosxhints.com/archive/index.php/t-70973.html

To paraphrase, you can rename it with the .command extension or create an AppleScript to run the shell.

RegEx for Javascript to allow only alphanumeric

Try this... Replace you field ID with #name... a-z(a to z), A-Z(A to Z), 0-9(0 to 9)

jQuery(document).ready(function($){
    $('#name').keypress(function (e) {
        var regex = new RegExp("^[a-zA-Z0-9\s]+$");
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (regex.test(str)) {
            return true;
        }
        e.preventDefault();
        return false;
    });
});

Getting the text that follows after the regex match

Your regex "sentence(.*)" is right. To retrieve the contents of the group in parenthesis, you would call:

Pattern p = Pattern.compile( "sentence(.*)" );
Matcher m = p.matcher( "some lame sentence that is awesome" );
if ( m.find() ) {
   String s = m.group(1); // " that is awesome"
}

Note the use of m.find() in this case (attempts to find anywhere on the string) and not m.matches() (would fail because of the prefix "some lame"; in this case the regex would need to be ".*sentence(.*)")

Update or Insert (multiple rows and columns) from subquery in PostgreSQL

UPDATE table1 SET (col1, col2) = (col2, col3) FROM othertable WHERE othertable.col1 = 123;

Way to insert text having ' (apostrophe) into a SQL table

try this

INSERT INTO exampleTbl VALUES('he doesn''t work for me')

How to get a value of an element by name instead of ID

This works fine .. here btnAddCat is button id

$('#btnAddCat').click(function(){
        var eventCategory=$("input[name=txtCategory]").val();
        alert(eventCategory);
    });

Using Composer's Autoload

Just create a symlink in your src folder for the namespace pointing to the folder containing your classes...

ln -s ../src/AppName ./src/AppName

Your autoload in composer will look the same...

"autoload": {
    "psr-0": {"AppName": "src/"}
}

And your AppName namespaced classes will start a directory up from your current working directory in a src folder now... that should work.

MySQL Foreign Key Error 1005 errno 150 primary key as foreign key

I don't have the reputation yet to up vote Steve's suggestion, but it solved my problem.

In my case, I received this error because the two table where created using different database engines--one was Innodb and the other MyISAM.

You can change the database type using : ALTER TABLE t ENGINE = MYISAM;

@see http://dev.mysql.com/doc/refman/5.1/en/storage-engine-setting.html

With MySQL, how can I generate a column containing the record index in a table?

You may want to try the following:

SELECT  l.position, 
        l.username, 
        l.score,
        @curRow := @curRow + 1 AS row_number
FROM    league_girl l
JOIN    (SELECT @curRow := 0) r;

The JOIN (SELECT @curRow := 0) part allows the variable initialization without requiring a separate SET command.

Test case:

CREATE TABLE league_girl (position int, username varchar(10), score int);
INSERT INTO league_girl VALUES (1, 'a', 10);
INSERT INTO league_girl VALUES (2, 'b', 25);
INSERT INTO league_girl VALUES (3, 'c', 75);
INSERT INTO league_girl VALUES (4, 'd', 25);
INSERT INTO league_girl VALUES (5, 'e', 55);
INSERT INTO league_girl VALUES (6, 'f', 80);
INSERT INTO league_girl VALUES (7, 'g', 15);

Test query:

SELECT  l.position, 
        l.username, 
        l.score,
        @curRow := @curRow + 1 AS row_number
FROM    league_girl l
JOIN    (SELECT @curRow := 0) r
WHERE   l.score > 50;

Result:

+----------+----------+-------+------------+
| position | username | score | row_number |
+----------+----------+-------+------------+
|        3 | c        |    75 |          1 |
|        5 | e        |    55 |          2 |
|        6 | f        |    80 |          3 |
+----------+----------+-------+------------+
3 rows in set (0.00 sec)

PostgreSQL delete with inner join

DELETE 
FROM m_productprice B  
     USING m_product C 
WHERE B.m_product_id = C.m_product_id AND
      C.upc = '7094' AND                 
      B.m_pricelist_version_id='1000020';

or

DELETE 
FROM m_productprice
WHERE m_pricelist_version_id='1000020' AND 
      m_product_id IN (SELECT m_product_id 
                       FROM m_product 
                       WHERE upc = '7094'); 

How to get the squared symbol (²) to display in a string

Not sure what kind of text box you are refering to. However, I'm not sure if you can do this in a text box on a user form.

A text box on a sheet you can though.

Sheets("Sheet1").Shapes("TextBox 1").TextFrame2.TextRange.Text = "R2=" & variable
Sheets("Sheet1").Shapes("TextBox 1").TextFrame2.TextRange.Characters(2, 1).Font.Superscript = msoTrue

And same thing for an excel cell

Sheets("Sheet1").Range("A1").Characters(2, 1).Font.Superscript = True

If this isn't what you're after you will need to provide more information in your question.

EDIT: posted this after the comment sorry

Java check if boolean is null

boolean is a primitive type, and therefore can not be null.

Its boxed type, Boolean, can be null.

The function is probably returning a Boolean as opposed to a boolean, so assigning the result to a Boolean-type variable will allow you to test for nullity.

HTML Display Current date

Here's one way. You have to get the individual components from the date object (day, month & year) and then build and format the string however you wish.

_x000D_
_x000D_
n =  new Date();_x000D_
y = n.getFullYear();_x000D_
m = n.getMonth() + 1;_x000D_
d = n.getDate();_x000D_
document.getElementById("date").innerHTML = m + "/" + d + "/" + y;
_x000D_
<p id="date"></p>
_x000D_
_x000D_
_x000D_

Good examples of python-memcache (memcached) being used in Python?

I would advise you to use pylibmc instead.

It can act as a drop-in replacement of python-memcache, but a lot faster(as it's written in C). And you can find handy documentation for it here.

And to the question, as pylibmc just acts as a drop-in replacement, you can still refer to documentations of pylibmc for your python-memcache programming.

How can I get name of element with jQuery?

var name = $('#myElement').attr('name');

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

You can use instance_of?

e.g

@some_var.instance_of?(Hash)

Save bitmap to file function

Two example works for me, for your reference.

Bitmap bitmap = Utils.decodeBase64(base64);
try {
    File file = new File(filePath);
    FileOutputStream fOut = new FileOutputStream(file);
    bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
    fOut.flush();
    fOut.close();
}
catch (Exception e) {
    e.printStackTrace();
    LOG.i(null, "Save file error!");
    return false;
}

and this one

Bitmap savePic = Utils.decodeBase64(base64);
File file = new File(filePath);
File path = new File(file.getParent());

if (savePic != null) {
    try {
        // build directory
        if (file.getParent() != null && !path.isDirectory()) {
            path.mkdirs();
        }
        // output image to file
        FileOutputStream fos = new FileOutputStream(filePath);
        savePic.compress(Bitmap.CompressFormat.PNG, 90, fos);
        fos.close();
        ret = true;
    } catch (Exception e) {
        e.printStackTrace();
    }
} else {
    LOG.i(TAG, "savePicture image parsing error");
}

How are environment variables used in Jenkins with Windows Batch Command?

I know nothing about Jenkins, but it looks like you are trying to access environment variables using some form of unix syntax - that won't work.

If the name of the variable is WORKSPACE, then the value is expanded in Windows batch using
%WORKSPACE%. That form of expansion is performed at parse time. For example, this will print to screen the value of WORKSPACE

echo %WORKSPACE%

If you need the value at execution time, then you need to use delayed expansion !WORKSPACE!. Delayed expansion is not normally enabled by default. Use SETLOCAL EnableDelayedExpansion to enable it. Delayed expansion is often needed because blocks of code within parentheses and/or multiple commands concatenated by &, &&, or || are parsed all at once, so a value assigned within the block cannot be read later within the same block unless you use delayed expansion.

setlocal enableDelayedExpansion
set WORKSPACE=BEFORE
(
  set WORKSPACE=AFTER
  echo Normal Expansion = %WORKSPACE%
  echo Delayed Expansion = !WORKSPACE!
)

The output of the above is

Normal Expansion = BEFORE
Delayed Expansion = AFTER

Use HELP SET or SET /? from the command line to get more information about Windows environment variables and the various expansion options. For example, it explains how to do search/replace and substring operations.

What is the difference between SQL Server 2012 Express versions?

Scroll down on that page and you'll see:

Express with Tools (with LocalDB) Includes the database engine and SQL Server Management Studio Express)
This package contains everything needed to install and configure SQL Server as a database server. Choose either LocalDB or Express depending on your needs above.

That's the SQLEXPRWT_x64_ENU.exe download.... (WT = with tools)


Express with Advanced Services (contains the database engine, Express Tools, Reporting Services, and Full Text Search)
This package contains all the components of SQL Express. This is a larger download than “with Tools,” as it also includes both Full Text Search and Reporting Services.

That's the SQLEXPRADV_x64_ENU.exe download ... (ADV = Advanced Services)


The SQLEXPR_x64_ENU.exe file is just the database engine - no tools, no Reporting Services, no fulltext-search - just barebones engine.

What is the difference between Numpy's array() and asarray() functions?

asarray(x) is like array(x, copy=False)

Use asarray(x) when you want to ensure that x will be an array before any other operations are done. If x is already an array then no copy would be done. It would not cause a redundant performance hit.

Here is an example of a function that ensure x is converted into an array first.

def mysum(x):
    return np.asarray(x).sum()

Check whether a string contains a substring

To find out if a string contains substring you can use the index function:

if (index($str, $substr) != -1) {
    print "$str contains $substr\n";
} 

It will return the position of the first occurrence of $substr in $str, or -1 if the substring is not found.

How do you configure an OpenFileDialog to select folders?

The Ookii.Dialogs package contains a managed wrapper around the new (Vista-style) folder browser dialog. It also degrades gracefully on older operating systems.

Update only specific fields in a models.Model

To update a subset of fields, you can use update_fields:

survey.save(update_fields=["active"]) 

The update_fields argument was added in Django 1.5. In earlier versions, you could use the update() method instead:

Survey.objects.filter(pk=survey.pk).update(active=True)

get basic SQL Server table structure information

For total columns information use below syntax : Use "DBName" go Exec SP_Columns "TableName"

For total table information use below syntax : Use "DBName" go Exec SP_help "Table Name"