Programs & Examples On #Array multisort

PHP's array_multisort — sorts multiple or multi-dimensional arrays

SQL Server table creation date query

For SQL Server 2000:

SELECT   su.name,so.name,so.crdate,* 
FROM     sysobjects so JOIN sysusers su
ON       so.uid = su.uid
WHERE    xtype='U'
ORDER BY so.name

Extract csv file specific columns to list in Python

A standard-lib version (no pandas)

This assumes that the first row of the csv is the headers

import csv

# open the file in universal line ending mode 
with open('test.csv', 'rU') as infile:
  # read the file as a dictionary for each row ({header : value})
  reader = csv.DictReader(infile)
  data = {}
  for row in reader:
    for header, value in row.items():
      try:
        data[header].append(value)
      except KeyError:
        data[header] = [value]

# extract the variables you want
names = data['name']
latitude = data['latitude']
longitude = data['longitude']

Twitter Bootstrap modal on mobile devices

OK this does fix it I tried it today Sept 5-2012 but you have to be sure to check out the demo

The solution by niftylettuce in issue 2130 seems to fix modals in all mobile platforms...

9/1/12 UPDATE: The fix has been updated here: twitter bootstrap jquery plugins

here is the link to the Demo It works great heres the code I used

            title_dialog.modal();
            title_dialog.modalResponsiveFix({})
            title_dialog.touchScroll();

What is makeinfo, and how do I get it?

In (at least) Ubuntu when using bash, it tells you what package you need to install if you type in a command and its not found in your path. My terminal says you need to install 'texinfo' package.

sudo apt-get install texinfo

How do I check that a Java String is not all whitespaces?

While personally I would be preferring !str.isBlank(), as others already suggested (or str -> !str.isBlank() as a Predicate), a more modern and efficient version of the str.trim() approach mentioned above, would be using str.strip() - considering nulls as "whitespace":

if (str != null && str.strip().length() > 0) {...}

For example as Predicate, for use with streams, e. g. in a unit test:

@Test
public void anyNonEmptyStrippedTest() {
    String[] strings = null;
    Predicate<String> isNonEmptyStripped = str -> str != null && str.strip().length() > 0;
    assertTrue(Optional.ofNullable(strings).map(arr -> Stream.of(arr).noneMatch(isNonEmptyStripped)).orElse(true));
    strings = new String[] { null, "", " ", "\\n", "\\t", "\\r" };
    assertTrue(Optional.ofNullable(strings).map(arr -> Stream.of(arr).anyMatch(isNonEmptyStripped)).orElse(true));
    strings = new String[] { null, "", " ", "\\n", "\\t", "\\r", "test" };
}

Reverse Singly Linked List Java

Node reverse_rec(Node start) {
    if (start == null || start -> next == null) {
       return start;
    }

    Node new_start = reverse(start->next);
    start->next->next = start;
    start->next = null;
    return new_start;
}


Node reverse(Node start) {
    Node cur = start;
    Node bef = null;

    while (cur != null) {
       Node nex = cur.next;
       cur.next = bef;
       bef = cur;
       cur = nex;
    }
    return bef;
}

How to check if object property exists with a variable holding the property name?

Several ways to check if an object property exists.

const dog = { name: "Spot" }

if (dog.name) console.log("Yay 1"); // Prints.
if (dog.sex) console.log("Yay 2"); // Doesn't print. 

if ("name" in dog) console.log("Yay 3"); // Prints.
if ("sex" in dog) console.log("Yay 4"); // Doesn't print.

if (dog.hasOwnProperty("name")) console.log("Yay 5"); // Prints.
if (dog.hasOwnProperty("sex")) console.log("Yay 6"); // Doesn't print, but prints undefined.

How to get PID of process I've just started within java program?

the jnr-process project provides this capability.

It is part of the java native runtime used by jruby and can be considered a prototype for a future java-FFI

Returning a boolean from a Bash function

For code readability reasons I believe returning true/false should:

  • be on one line
  • be one command
  • be easy to remember
  • mention the keyword return followed by another keyword (true or false)

My solution is return $(true) or return $(false) as shown:

is_directory()
{
    if [ -d "${1}" ]; then
        return $(true)
    else
        return $(false)
    fi
}

converting drawable resource image into bitmap

Drawable myDrawable = getResources().getDrawable(R.drawable.logo);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();

Since API 22 getResources().getDrawable() is deprecated, so we can use following solution.

Drawable vectorDrawable = VectorDrawableCompat.create(getResources(), R.drawable.logo,  getContext().getTheme());
Bitmap myLogo = ((BitmapDrawable) vectorDrawable).getBitmap();

How to know a Pod's own IP address from inside a container in the Pod?

The simplest answer is to ensure that your pod or replication controller yaml/json files add the pod IP as an environment variable by adding the config block defined below. (the block below additionally makes the name and namespace available to the pod)

env:
- name: MY_POD_NAME
  valueFrom:
    fieldRef:
      fieldPath: metadata.name
- name: MY_POD_NAMESPACE
  valueFrom:
    fieldRef:
      fieldPath: metadata.namespace
- name: MY_POD_IP
  valueFrom:
    fieldRef:
      fieldPath: status.podIP

Recreate the pod/rc and then try

echo $MY_POD_IP

also run env to see what else kubernetes provides you with.

Cheers

md-table - How to update the column width

If you have too many table column and it is not adjusted in angular table using md-table, then paste the following style in component.css file. It will work like a charm with scroll view horizontally.

.mat-table__wrapper .mat-table {
    min-width: auto !important;
    width: 100% !important; }

.mat-header-row {
    width: 100%; }

.mat-row {
    width: 100%;
}

Add this style to alter your column separately.

.mat-column-{colum-name} {
    flex: 0 0 25% !important;
    min-width: 104px !important;
}

Alternatively check this link, (where the code above came from), for more detail.

Append same text to every cell in a column in Excel

Type it in one cell, copy that cell, select all the cells you want to fill, and paste.

Alternatively, type it in one cell, select the black square in the bottom-right of that cell, and drag down.

Directory Chooser in HTML page

If you do not have too many folders then I suggest you use if statements to choose an upload folder depending on the user input details. E.g.

String user= request.getParameter("username");
if (user=="Alfred"){
//Path A;
}
if (user=="other"){
//Path B;
}

select certain columns of a data table

First store the table in a view, then select columns from that view into a new table.

// Create a table with abitrary columns for use with the example
System.Data.DataTable table = new System.Data.DataTable();
for (int i = 1; i <= 11; i++)
    table.Columns.Add("col" + i.ToString());

// Load the table with contrived data
for (int i = 0; i < 100; i++)
{
    System.Data.DataRow row = table.NewRow();
    for (int j = 0; j < 11; j++)
        row[j] = i.ToString() + ", " + j.ToString();
    table.Rows.Add(row);
}

// Create the DataView of the DataTable
System.Data.DataView view = new System.Data.DataView(table);
// Create a new DataTable from the DataView with just the columns desired - and in the order desired
System.Data.DataTable selected = view.ToTable("Selected", false, "col1", "col2", "col6", "col7", "col3");

Used the sample data to test this method I found: Create ADO.NET DataView showing only selected Columns

Why is Android Studio reporting "URI is not registered"?

Select appropriate flavour in Build Variants.

If you are viewing a particular file under Flavour1, select that flavor in BuildVariants window.

If your IDE is Android Studio (3.2.1 as of this writing), you should find Build Variants window on the lower left, aligned vertically.

How do I build a graphical user interface in C++?

Since I've already been where you are right now, I think I can "answer" you.

The fact is there is no easy way to make a GUI. GUI's are highly dependent on platform and OS specific code, that's why you should start reading your target platform/OS documentation on window management APIs. The good thing is: there are plenty of libraries that address these limitations and abstract architecture differences into a single multi-platform API. Those suggested before, GTK and Qt, are some of these libraries.

But even these are a little too complicated, since lots of new concepts, data types, namespaces and classes are introduced, all at once. For this reason, they use to come bundled with some GUI WYSIWYG editor. They pretty much make programming software with GUIs possible.

To sum it up, there are also non free "environments" for GUI development such as Visual Studio from Microsoft. For those with Delphi experience backgrounds, Visual Studio may be more familiar. There are also free alternatives to the full Visual Studio environment supplied from Microsoft: Visual Studio Express, which is more than enough for starting on GUI development.

fork() and wait() with two child processes

It looks to me as though the basic problem is that you have one wait() call rather than a loop that waits until there are no more children. You also only wait if the last fork() is successful rather than if at least one fork() is successful.

You should only use _exit() if you don't want normal cleanup operations - such as flushing open file streams including stdout. There are occasions to use _exit(); this is not one of them. (In this example, you could also, of course, simply have the children return instead of calling exit() directly because returning from main() is equivalent to exiting with the returned status. However, most often you would be doing the forking and so on in a function other than main(), and then exit() is often appropriate.)


Hacked, simplified version of your code that gives the diagnostics I'd want. Note that your for loop skipped the first element of the array (mine doesn't).

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

int main(void)
{
    pid_t child_pid, wpid;
    int status = 0;
    int i;
    int a[3] = {1, 2, 1};

    printf("parent_pid = %d\n", getpid());
    for (i = 0; i < 3; i++)
    {
        printf("i = %d\n", i);
        if ((child_pid = fork()) == 0)
        {
            printf("In child process (pid = %d)\n", getpid());
            if (a[i] < 2)
            {
                printf("Should be accept\n");
                exit(1);
            }
            else
            {
                printf("Should be reject\n");
                exit(0);
            }
            /*NOTREACHED*/
        }
    }

    while ((wpid = wait(&status)) > 0)
    {
        printf("Exit status of %d was %d (%s)\n", (int)wpid, status,
               (status > 0) ? "accept" : "reject");
    }
    return 0;
}

Example output (MacOS X 10.6.3):

parent_pid = 15820
i = 0
i = 1
In child process (pid = 15821)
Should be accept
i = 2
In child process (pid = 15822)
Should be reject
In child process (pid = 15823)
Should be accept
Exit status of 15823 was 256 (accept)
Exit status of 15822 was 0 (reject)
Exit status of 15821 was 256 (accept)

How to export library to Jar in Android Studio?

We can export a jar file for Android library project without resource files by Android studio. It is also requirement what I met recently.

1. Config your build.gradle file

    // Task to delete old jar

    task clearJar(type: Delete){
       delete 'release/lunademo.jar'
    }

    // task to export contents as jar
    task makeJar(type: Copy) {
       from ('build/intermediates/bundles/release/')
       into ('build/libs/')
       include ('classes.jar')
       rename('classes.jar', 'lunademo.jar')
    }
    makeJar.dependsOn(clearJar, build)

2. Run gradlew makeJar under your project root

You will see your libs under dir as build/libs/ if you are luckily.

============================================================

If you met issue as "Socket timeout exception" on command line as below,

enter image description here

You can follow this steps to open Gradle window in the right part and click "makeJar" on Android studio like this,

enter image description here

enter image description here

Then go to build/libs dir, you will see your jar file.

Hope that it is helpful for u.

Good Luck @.@

Luna

jQuery: How to get to a particular child of a parent?

$(this).parent()

Tree traversal is fun

$(this).parent().siblings(".something1");

$(this).parent().prev(); // if you always want the parent's previous sibling

$(this).parents(".box").children(".something1");

And much more ways, you might find these docs helpful.

Multiple line comment in Python

Try this

'''
This is a multiline
comment. I can type here whatever I want.
'''

Python does have a multiline string/comment syntax in the sense that unless used as docstrings, multiline strings generate no bytecode -- just like #-prepended comments. In effect, it acts exactly like a comment.

On the other hand, if you say this behavior must be documented in the official docs to be a true comment syntax, then yes, you would be right to say it is not guaranteed as part of the language specification.

In any case your editor should also be able to easily comment-out a selected region (by placing a # in front of each line individually). If not, switch to an editor that does.

Programming in Python without certain text editing features can be a painful experience. Finding the right editor (and knowing how to use it) can make a big difference in how the Python programming experience is perceived.

Not only should the editor be able to comment-out selected regions, it should also be able to shift blocks of code to the left and right easily, and should automatically place the cursor at the current indentation level when you press Enter. Code folding can also be useful.

CSS : center form in page horizontally and vertically

I suggest you using bootstrap which works perfectly:

_x000D_
_x000D_
@import url('http://getbootstrap.com/dist/css/bootstrap.css');_x000D_
 html, body, .container-table {_x000D_
    height: 100%;_x000D_
}_x000D_
.container-table {_x000D_
    display: table;_x000D_
}_x000D_
.vertical-center-row {_x000D_
    display: table-cell;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1.0" />_x000D_
<title>Login Page | ... </title>_x000D_
_x000D_
<script src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.1.0/bootstrap.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
 <div class="container container-table">_x000D_
  <div class="row vertical-center-row">_x000D_
   <div class="text-center col-md-4 col-md-offset-4" style="">_x000D_
      <form id="login" action="dashboard.html" method="post">_x000D_
     _x000D_
     <div class="username">_x000D_
      <div class="usernameinner">_x000D_
       <input type="text" name="username" id="username" placeholder="Login" />_x000D_
      </div>_x000D_
     </div>_x000D_
     _x000D_
     <div class="password">_x000D_
      <div class="passwordinner">_x000D_
       <input type="password" name="password" id="password" placeholder="Mot de passe" />_x000D_
      </div>_x000D_
     </div>_x000D_
     _x000D_
     <button id="login-button">Connexion</button>_x000D_
     _x000D_
     <div class="keep"><input type="checkbox" /> Gardez moi connecté</div>_x000D_
    _x000D_
    </form>_x000D_
   </div>_x000D_
  </div>_x000D_
 </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

PostgreSQL: insert from another table

For referential integtity :

insert into  main_tbl (col1, ref1, ref2, createdby)
values ('col1_val',
        (select ref1 from ref1_tbl where lookup_val = 'lookup1'),
        (select ref2 from ref2_tbl where lookup_val = 'lookup2'),
        'init-load'
       );

How to select unique records by SQL

With the distinct keyword with single and multiple column names, you get distinct records:

SELECT DISTINCT column 1, column 2, ...
FROM table_name;

How do I pass data to Angular routed components?

It is 2019 and many of the answers here would work, depending on what you want to do. If you want to pass in some internal state not visible in URL (params, query) you can use state since 7.2 (as I have learned just today :) ).

From the blog (credits Tomasz Kula) - you navigate to route....

...from ts: this.router.navigateByUrl('/details', { state: { hello: 'world' } });

...from HTML template: <a routerLink="/details" [state]="{ hello: 'world' }">Go</a>

And to pick it up in the target component:

constructor(public activatedRoute: ActivatedRoute) {}

  ngOnInit() {
    this.state$ = this.activatedRoute.paramMap
      .pipe(map(() => window.history.state))
  }

Late, but hope this helps someone with recent Angular.

Checkout old commit and make it a new commit

The other answers so far create new commits that undo what is in older commits. It is possible to go back and "change history" as it were, but this can be a bit dangerous. You should only do this if the commit you're changing has not been pushed to other repositories.

The command you're looking for is git rebase --interactive

If you want to change HEAD~3, the command you want to issue is git rebase --interactive HEAD~4. This will open a text editor and allow you to specify which commits you want to change.

Practice on a different repository before you try this with something important. The man pages should give you all the rest of the information you need.

CSS Animation and Display None

The following will get you to animate an element when

  1. Giving it a Display - None
  2. Giving it a Display - Block

CSS

.MyClass {
       opacity: 0;
       display:none;
       transition: opacity 0.5s linear;
       -webkit-transition: opacity 0.5s linear;
       -moz-transition: opacity 0.5s linear;
       -o-transition: opacity 0.5s linear;
       -ms-transition: opacity 0.5s linear;
 }

JavaScript

function GetThisHidden(){
    $(".MyClass").css("opacity", "0").on('transitionend webkitTransitionEnd oTransitionEnd otransitionend', HideTheElementAfterAnimation);
}

function GetThisDisplayed(){
    $(".MyClass").css("display", "block").css("opacity", "1").unbind("transitionend webkitTransitionEnd oTransitionEnd otransitionend");
}

function HideTheElementAfterAnimation(){
    $(".MyClass").css("display", "none");
}

Check if the number is integer

For a vector m, m[round(m) != m] will return the indices of values in the vector that are not integers.

How to create an exit message

If you want to denote an actual error in your code, you could raise a RuntimeError exception:

raise RuntimeError, 'Message goes here'

This will print a stacktrace, the type of the exception being raised and the message that you provided. Depending on your users, a stacktrace might be too scary, and the actual message might get lost in the noise. On the other hand, if you die because of an actual error, a stacktrace will give you additional information for debugging.

XML parsing of a variable string in JavaScript

You can also through the jquery function($.parseXML) to manipulate xml string

example javascript:

var xmlString = '<languages><language name="c"></language><language name="php"></language></languages>';
var xmlDoc = $.parseXML(xmlString);
$(xmlDoc).find('name').each(function(){
    console.log('name:'+$(this).attr('name'))
})

Ping all addresses in network, windows

Best Utility in terms of speed is Nmap.

write @ cmd prompt:

Nmap -sn -oG ip.txt 192.168.1.1-255

this will just ping all the ip addresses in the range given and store it in simple text file

It takes just 2 secs to scan 255 hosts using Nmap.

Launch Failed. Binary not found. CDT on Eclipse Helios

Seems like having "Build Automatically" under the Project menu ought to take care of all of this. It does for Java.

How do I trap ctrl-c (SIGINT) in a C# console app

Here is a complete working example. paste into empty C# console project:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;

namespace TestTrapCtrlC {
    public class Program {
        static bool exitSystem = false;

        #region Trap application termination
        [DllImport("Kernel32")]
        private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);

        private delegate bool EventHandler(CtrlType sig);
        static EventHandler _handler;

        enum CtrlType {
            CTRL_C_EVENT = 0,
            CTRL_BREAK_EVENT = 1,
            CTRL_CLOSE_EVENT = 2,
            CTRL_LOGOFF_EVENT = 5,
            CTRL_SHUTDOWN_EVENT = 6
        }

        private static bool Handler(CtrlType sig) {
            Console.WriteLine("Exiting system due to external CTRL-C, or process kill, or shutdown");

            //do your cleanup here
            Thread.Sleep(5000); //simulate some cleanup delay

            Console.WriteLine("Cleanup complete");

            //allow main to run off
            exitSystem = true;

            //shutdown right away so there are no lingering threads
            Environment.Exit(-1);

            return true;
        }
        #endregion

        static void Main(string[] args) {
            // Some biolerplate to react to close window event, CTRL-C, kill, etc
            _handler += new EventHandler(Handler);
            SetConsoleCtrlHandler(_handler, true);

            //start your multi threaded program here
            Program p = new Program();
            p.Start();

            //hold the console so it doesn’t run off the end
            while (!exitSystem) {
                Thread.Sleep(500);
            }
        }

        public void Start() {
            // start a thread and start doing some processing
            Console.WriteLine("Thread started, processing..");
        }
    }
}

How to detect running app using ADB command

I just noticed that top is available in adb, so you can do things like

  adb shell
  top -m 5

to monitor the top five CPU hogging processes.

Or

  adb shell top -m 5 -s cpu -n 20 |tee top.log

to record this for one minute and collect the output to a file on your computer.

Entity Framework Provider type could not be loaded?

remove the entity framework from the project via nuget then add it back in.

How long would it take a non-programmer to learn C#, the .NET Framework, and SQL?

2-3 months to learn the basics...no way. Unless you're gonna code spaghetti sure. Same goes for the 1-2 years. Spaghetti it is then..

Could not establish secure channel for SSL/TLS with authority '*'

Ensure you run Visual Studio as an administrator.

Read .doc file with python

You can use python-docx2txt library to read text from Microsoft Word documents. It is an improvement over python-docx library as it can, in addition, extract text from links, headers and footers. It can even extract images.

You can install it by running: pip install docx2txt.

Let's download and read the first Microsoft document on here:

import docx2txt
my_text = docx2txt.process("test.docx")
print(my_text)

Here is a screenshot of the Terminal output the above code:

enter image description here

EDIT:

This does NOT work for .doc files. The only reason I am keep this answer is that it seems there are people who find it useful for .docx files.

Determine SQL Server Database Size

Common Query To Check Database Size in SQL Server that supports both Azure and On-Premises-

Method 1 – Using ‘sys.database_files’ System View

SELECT
    DB_NAME() AS [database_name],
    CONCAT(CAST(SUM(
        CAST( (size * 8.0/1024) AS DECIMAL(15,2) )
    ) AS VARCHAR(20)),' MB') AS [database_size]
FROM sys.database_files;

Method 2 – Using ‘sp_spaceused’ System Stored Procedure

EXEC sp_spaceused ;

Is there a way to get a list of column names in sqlite?

An alternative to the cursor.description solution from smallredstone could be to use row.keys():

import sqlite3
connection = sqlite3.connect('~/foo.sqlite')
connection.row_factory = sqlite3.Row
cursor = connection.execute('select * from bar')
# instead of cursor.description:
row = cursor.fetchone()
names = row.keys()

The drawback: it only works if there is at least a row returned from the query.

The benefit: you can access the columns by their name (row['your_column_name'])

Read more about the Row objects in the python documentation.

What does the DOCKER_HOST variable do?

Ok, I think I got it.

The client is the docker command installed into OS X.

The host is the Boot2Docker VM.

The daemon is a background service running inside Boot2Docker.

This variable tells the client how to connect to the daemon.

When starting Boot2Docker, the terminal window that pops up already has DOCKER_HOST set, so that's why docker commands work. However, to run Docker commands in other terminal windows, you need to set this variable in those windows.

Failing to set it gives a message like this:

$ docker run hello-world
2014/08/11 11:41:42 Post http:///var/run/docker.sock/v1.13/containers/create: 
dial unix /var/run/docker.sock: no such file or directory

One way to fix that would be to simply do this:

$ export DOCKER_HOST=tcp://192.168.59.103:2375

But, as pointed out by others, it's better to do this:

$ $(boot2docker shellinit)
$ docker run hello-world
Hello from Docker. [...]

To spell out this possibly non-intuitive Bash command, running boot2docker shellinit returns a set of Bash commands that set environment variables:

export DOCKER_HOST=tcp://192.168.59.103:2376
export DOCKER_CERT_PATH=/Users/ddavison/.boot2docker/certs/boot2docker-vm
export DOCKER_TLS_VERIFY=1

Hence running $(boot2docker shellinit) generates those commands, and then runs them.

how to convert an RGB image to numpy array?

PIL (Python Imaging Library) and Numpy work well together.

I use the following functions.

from PIL import Image
import numpy as np

def load_image( infilename ) :
    img = Image.open( infilename )
    img.load()
    data = np.asarray( img, dtype="int32" )
    return data

def save_image( npdata, outfilename ) :
    img = Image.fromarray( np.asarray( np.clip(npdata,0,255), dtype="uint8"), "L" )
    img.save( outfilename )

The 'Image.fromarray' is a little ugly because I clip incoming data to [0,255], convert to bytes, then create a grayscale image. I mostly work in gray.

An RGB image would be something like:

 outimg = Image.fromarray( ycc_uint8, "RGB" )
 outimg.save( "ycc.tif" )

CSV new-line character seen in unquoted field error

It'll be good to see the csv file itself, but this might work for you, give it a try, replace:

file_read = csv.reader(self.file)

with:

file_read = csv.reader(self.file, dialect=csv.excel_tab)

Or, open a file with universal newline mode and pass it to csv.reader, like:

reader = csv.reader(open(self.file, 'rU'), dialect=csv.excel_tab)

Or, use splitlines(), like this:

def read_file(self):
    with open(self.file, 'r') as f:
        data = [row for row in csv.reader(f.read().splitlines())]
    return data

What does void mean in C, C++, and C#?

I have always taken it to mean absent. Here are four cases in the C language that matches to this use of absent

  • R f(void) - Function parameters are absent
  • void f(P) - Return value is absent
  • void *p - Type of what is pointed to is absent
  • (void) p - Usage of value is absent

Other C descendants use it for other things. The D programming language uses it for cases where an initializer is absent

  • T t = void; - initializing value is absent

JavaScript pattern for multiple constructors

export default class Order {

    static fromCart(cart) {
        var newOrder = new Order();
        newOrder.items = cart.items;
        newOrder.sum = cart.sum;

        return newOrder;
    }

    static fromOrder(id, order) {
        var newOrder = new Order();
        newOrder.id = id;
        newOrder.items = order.items;
        newOrder.sum = order.sum;

        return newOrder;
    }
}

Useges:

  var newOrder = Order.fromCart(cart)
  var newOrder = Order.fromOrder(id, oldOrder)

Convert array to JSON string in swift

You can try this.

func convertToJSONString(value: AnyObject) -> String? {
        if JSONSerialization.isValidJSONObject(value) {
            do{
                let data = try JSONSerialization.data(withJSONObject: value, options: [])
                if let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
                    return string as String
                }
            }catch{
            }
        }
        return nil
    }

splitting a number into the integer and decimal parts

If you don't mind using NumPy, then:

In [319]: real = np.array([1234.5678])

In [327]: integ, deci = int(np.floor(real)), np.asscalar(real % 1)

In [328]: integ, deci
Out[328]: (1234, 0.5678000000000338)

HTML form do some "action" when hit submit button

index.html

<!DOCTYPE html>
<html>
   <body>
       <form action="submit.php" method="POST">
         First name: <input type="text" name="firstname" /><br /><br />
         Last name: <input type="text" name="lastname" /><br />
         <input type="submit" value="Submit" />
      </form> 
   </body>
</html>

After that one more file which page you want to display after pressing the submit button

submit.php

<html>
  <body>

    Your First Name is -  <?php echo $_POST["firstname"]; ?><br>
    Your Last Name is -   <?php echo $_POST["lastname"]; ?>

  </body>
</html>

How to get single value from this multi-dimensional PHP array

echo $myarray[0]->['email'];

Try this only if it you are passing the stdclass object

What is Parse/parsing?

Parsing is just process of analyse the string of character and find the tokens from that string and parser is a component of interpreter and compiler.It uses lexical analysis and then syntactic analysis.It parse it and then compile this code after this whole process of compilation.

How to ping multiple servers and return IP address and Hostnames using batch script?

Try this

$servers = Get-Content test.txt

$reg=""

foreach ($server in $servers) 

{

$reg=$reg+$server+"`t"+([System.Net.Dns]::GetHostAddresses($server) | foreach {echo $_.IPAddressToString})+"`n"

 }
$reg >reg.csv

Setting graph figure size

I managed to get a good result with the following sequence (run Matlab twice at the beginning):

h = gcf; % Current figure handle
set(h,'Resize','off');
set(h,'PaperPositionMode','manual');
set(h,'PaperPosition',[0 0 9 6]);
set(h,'PaperUnits','centimeters');
set(h,'PaperSize',[9 6]); % IEEE columnwidth = 9cm
set(h,'Position',[0 0 9 6]);
% xpos, ypos must be set
txlabel = text(xpos,ypos,'$$[\mathrm{min}]$$','Interpreter','latex','FontSize',9);

% Dump colored encapsulated PostScript
print('-depsc2','-loose', 'signals');

What is the C# equivalent of NaN or IsNumeric?

Yeah, IsNumeric is VB. Usually people use the TryParse() method, though it is a bit clunky. As you suggested, you can always write your own.

int i;
if (int.TryParse(string, out i))
{

}

How can I merge the columns from two tables into one output?

I had a similar problem with a small difference: some a.category_id are not in b and some b.category_id are not in a.
To solve this problem just adapt the excelent answer from beny23 to

select a.col1, b.col2, a.col3, b.col4, a.category_id 
from items_a a
LEFT OUTER JOIN
items_b b 
on a.category_id = b.category_id

Hope this helps someone.
Regards.

The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via

Try adding message credentials on your app.config like:

<bindings> 
<basicHttpBinding> 
<binding name="defaultBasicHttpBinding"> 
  <security mode="Transport"> 
    <transport clientCredentialType="None" proxyCredentialType="None" realm=""/> 
    <message clientCredentialType="Certificate" algorithmSuite="Default" />
  </security> 
</binding> 
</basicHttpBinding> 
</bindings> 

An object reference is required to access a non-static member

playSound is a static method meaning it exists when the program is loaded. audioSounds and minTime are SoundManager instance variable, meaning they will exist within an instance of SoundManager. You have not created an instance of SoundManager so audioSounds doesn't exist (or it does but you do not have a reference to a SoundManager object to see that).

To solve your problem you can either make audioSounds static:

public static List<AudioSource> audioSounds = new List<AudioSource>();
public static double minTime = 0.5;

so they will be created and may be referenced in the same way that PlaySound will be. Alternatively you can create an instance of SoundManager from within your method:

SoundManager soundManager = new SoundManager();
foreach (AudioSource sound in soundManager.audioSounds) // Loop through List with foreach
{
    if (sourceSound.name != sound.name && sound.time <= soundManager.minTime)
    {
        playsound = true;
    }
}

How to delete columns in numpy.array

This creates another array without those columns:

  b = a.compress(logical_not(z), axis=1)

Fastest way to convert JavaScript NodeList to Array?

faster and shorter :

// nl is the nodelist
var a=[], l=nl.length>>>0;
for( ; l--; a[l]=nl[l] );

Capturing Groups From a Grep RegEx

If you're using Bash, you don't even have to use grep:

files="*.jpg"
regex="[0-9]+_([a-z]+)_[0-9a-z]*"
for f in $files    # unquoted in order to allow the glob to expand
do
    if [[ $f =~ $regex ]]
    then
        name="${BASH_REMATCH[1]}"
        echo "${name}.jpg"    # concatenate strings
        name="${name}.jpg"    # same thing stored in a variable
    else
        echo "$f doesn't match" >&2 # this could get noisy if there are a lot of non-matching files
    fi
done

It's better to put the regex in a variable. Some patterns won't work if included literally.

This uses =~ which is Bash's regex match operator. The results of the match are saved to an array called $BASH_REMATCH. The first capture group is stored in index 1, the second (if any) in index 2, etc. Index zero is the full match.

You should be aware that without anchors, this regex (and the one using grep) will match any of the following examples and more, which may not be what you're looking for:

123_abc_d4e5
xyz123_abc_d4e5
123_abc_d4e5.xyz
xyz123_abc_d4e5.xyz

To eliminate the second and fourth examples, make your regex like this:

^[0-9]+_([a-z]+)_[0-9a-z]*

which says the string must start with one or more digits. The carat represents the beginning of the string. If you add a dollar sign at the end of the regex, like this:

^[0-9]+_([a-z]+)_[0-9a-z]*$

then the third example will also be eliminated since the dot is not among the characters in the regex and the dollar sign represents the end of the string. Note that the fourth example fails this match as well.

If you have GNU grep (around 2.5 or later, I think, when the \K operator was added):

name=$(echo "$f" | grep -Po '(?i)[0-9]+_\K[a-z]+(?=_[0-9a-z]*)').jpg

The \K operator (variable-length look-behind) causes the preceding pattern to match, but doesn't include the match in the result. The fixed-length equivalent is (?<=) - the pattern would be included before the closing parenthesis. You must use \K if quantifiers may match strings of different lengths (e.g. +, *, {2,4}).

The (?=) operator matches fixed or variable-length patterns and is called "look-ahead". It also does not include the matched string in the result.

In order to make the match case-insensitive, the (?i) operator is used. It affects the patterns that follow it so its position is significant.

The regex might need to be adjusted depending on whether there are other characters in the filename. You'll note that in this case, I show an example of concatenating a string at the same time that the substring is captured.

How to convert a JSON string to a dictionary?

I've updated Eric D's answer for Swift 5:

 func convertStringToDictionary(text: String) -> [String:AnyObject]? {
    if let data = text.data(using: .utf8) {
        do {
            let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:AnyObject]
            return json
        } catch {
            print("Something went wrong")
        }
    }
    return nil
}

Where to find the win32api module for Python?

I've found that UC Irvine has a great collection of python modules, pywin32 (win32api) being one of many listed there. I'm not sure how they do with keeping up with the latest versions of these modules but it hasn't let me down yet.

UC Irvine Python Extension Repository - http://www.lfd.uci.edu/~gohlke/pythonlibs

pywin32 module - http://www.lfd.uci.edu/~gohlke/pythonlibs/#pywin32

How to display a range input slider vertically

Without changing the position to absolute, see below. This supports all recent browsers as well.

_x000D_
_x000D_
.vranger {_x000D_
  margin-top: 50px;_x000D_
   transform: rotate(270deg);_x000D_
  -moz-transform: rotate(270deg); /*do same for other browsers if required*/_x000D_
}
_x000D_
<input type="range" class="vranger"/>
_x000D_
_x000D_
_x000D_

for very old browsers, you can use -sand-transform: rotate(10deg); from CSS sandpaper

or use

prefix selector such as -ms-transform: rotate(270deg); for IE9

How to search for a file in the CentOS command line

CentOS is Linux, so as in just about all other Unix/Linux systems, you have the find command. To search for files within the current directory:

find -name "filename"

You can also have wildcards inside the quotes, and not just a strict filename. You can also explicitly specify a directory to start searching from as the first argument to find:

find / -name "filename"

will look for "filename" or all the files that match the regex expression in between the quotes, starting from the root directory. You can also use single quotes instead of double quotes, but in most cases you don't need either one, so the above commands will work without any quotes as well. Also, for example, if you're searching for java files and you know they are somewhere in your /home/username, do:

find /home/username -name *.java

There are many more options to the find command and you should do a:

man find

to learn more about it.

One more thing: if you start searching from / and are not root or are not sudo running the command, you might get warnings that you don't have permission to read certain directories. To ignore/remove those, do:

find / -name 'filename' 2>/dev/null

That just redirects the stderr to /dev/null.

Compare two List<T> objects for equality, ignoring order

I use this method )

public delegate bool CompareValue<in T1, in T2>(T1 val1, T2 val2);

public static bool CompareTwoArrays<T1, T2>(this IEnumerable<T1> array1, IEnumerable<T2> array2, CompareValue<T1, T2> compareValue)
{
    return array1.Select(item1 => array2.Any(item2 => compareValue(item1, item2))).All(search => search)
            && array2.Select(item2 => array1.Any(item1 => compareValue(item1, item2))).All(search => search);
}

Set space between divs

Float them both the same way and add the margin of 40px. If you have 2 elements floating opposite ways you will have much less control and the containing element will determine how far apart they are.

#left{
    float: left;
    margin-right: 40px;
}
#right{
   float: left;
}

function to remove duplicate characters in a string

package com.java.exercise;

public class RemoveCharacter {

    /**
     * @param args
     */
    public static void main(String[] args) {
        RemoveCharacter rem = new RemoveCharacter();
        char[] ch=rem.GetDuplicates("JavavNNNNNNC".toCharArray());
        char[] desiredString="JavavNNNNNNC".toCharArray();
        System.out.println(rem.RemoveDuplicates(desiredString, ch));

    }
    char[] GetDuplicates(char[] input)
    {
        int ctr=0;
        char[] charDupl=new char[20];
        for (int i = 0; i <input.length; i++)
        {
            char tem=input[i];
            for (int j= 0; j < i; j++)
            {
                if (tem == input[j])
                {
                    charDupl[ctr++] = input[j];
                }

            }
        }


        return charDupl;
    }
     public char[] RemoveDuplicates(char[] input1, char []input2)
     {

         int coutn =0;
         char[] out2 = new char[10];
         boolean flag = false;
         for (int i = 0; i < input1.length; i++)
         {
             for (int j = 0; j < input2.length; j++)
             {

                     if (input1[i] == input2[j])
                     {
                         flag = false;
                         break;
                     }
                     else
                     {
                         flag = true;
                     }

             }
             if (flag)
             {
                 out2[coutn++]=input1[i];
                 flag = false;
             }
         }
         return out2;
     }
}

How do I set a program to launch at startup

    /// <summary>
    /// Add application to Startup of windows
    /// </summary>
    /// <param name="appName"></param>
    /// <param name="path"></param>
    public static void AddStartup(string appName, string path)
    {
        using (RegistryKey key = Registry.CurrentUser.OpenSubKey
            ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
        {
            key.SetValue(appName, "\"" + path + "\"");
        }
    }

    /// <summary>
    /// Remove application from Startup of windows
    /// </summary>
    /// <param name="appName"></param>
    public static void RemoveStartup(string appName)
    {
        using (RegistryKey key = Registry.CurrentUser.OpenSubKey
            ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
        {
            key.DeleteValue(appName, false);
        }
    }

Java and SSL - java.security.NoSuchAlgorithmException

Try javax.net.ssl.keyStorePassword instead of javax.net.ssl.keyPassword: the latter isn't mentioned in the JSSE ref guide.

The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmExceptions are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.

You could also use -Djavax.net.debug=ssl, or at least -Djavax.net.debug=ssl,keymanager, to get more debugging information, if the information in the stack trace isn't sufficient.

Which is the default location for keystore/truststore of Java applications?

Like bruno said, you're better configuring it yourself. Here's how I do it. Start by creating a properties file (/etc/myapp/config.properties).

javax.net.ssl.keyStore = /etc/myapp/keyStore
javax.net.ssl.keyStorePassword = 123456

Then load the properties to your environment from your code. This makes your application configurable.

FileInputStream propFile = new FileInputStream("/etc/myapp/config.properties");
Properties p = new Properties(System.getProperties());
p.load(propFile);
System.setProperties(p);

How to download/checkout a project from Google Code in Windows?

Thanks Mr. Tom Chantler adding that to get the exe http://downloadsvn.codeplex.com/ to pull the SVN source

just note that suppose you're downloading the below project: you have to enter exactly the following to donwload it in the exe URL:

http://myproject.googlecode.com/svn/trunk/

developer not taking care of appending the h t t p : / / if it does not exist. Hope it saves somebody's time.

How to set minDate to current date in jQuery UI Datepicker?

You can specify minDate as today by adding minDate: 0 to the options.

$("input.DateFrom").datepicker({
    minDate: 0,
    ...
});

Demo: http://jsfiddle.net/2CZtV/

Docs: http://jqueryui.com/datepicker/#min-max

Load image from resources area of project in C#

Strangely enough, from poking in the designer I find what seems to be a much simpler approach:

The image seems to be available from .Properties.Resources.

I'm simply using an image as all I'm interested in is pasting it into a control with an image on it.

(Net 4.0, VS2010.)

How to convert between bytes and strings in Python 3?

This is a Python 101 type question,

It's a simple question but one where the answer is not so simple.


In python3, a "bytes" object represents a sequence of bytes, a "string" object represents a sequence of unicode code points.

To convert between from "bytes" to "string" and from "string" back to "bytes" you use the bytes.decode and string.encode functions. These functions take two parameters, an encoding and an error handling policy.

Sadly there are an awful lot of cases where sequences of bytes are used to represent text, but it is not necessarily well-defined what encoding is being used. Take for example filenames on unix-like systems, as far as the kernel is concerned they are a sequence of bytes with a handful of special values, on most modern distros most filenames will be UTF-8 but there is no gaurantee that all filenames will be.

If you want to write robust software then you need to think carefully about those parameters. You need to think carefully about what encoding the bytes are supposed to be in and how you will handle the case where they turn out not to be a valid sequence of bytes for the encoding you thought they should be in. Python defaults to UTF-8 and erroring out on any byte sequence that is not valid UTF-8.

print(bytesThing)

Python uses "repr" as a fallback conversion to string. repr attempts to produce python code that will recreate the object. In the case of a bytes object this means among other things escaping bytes outside the printable ascii range.

How to exclude file only from root folder in Git

From the documentation:

If the pattern does not contain a slash /, git treats it as a shell glob pattern and checks for a match against the pathname relative to the location of the .gitignore file (relative to the toplevel of the work tree if not from a .gitignore file).

A leading slash matches the beginning of the pathname. For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".

So you should add the following line to your root .gitignore:

/config.php

Can't connect to MySQL server on 'localhost' (10061)

Edit your 'my-default.ini' file (by default it comes with commented properties)as below ie.

basedir=D:/D_Drive/mysql-5.6.20-win32
datadir=D:/D_Drive/mysql-5.6.20-win32/data
port=8888

There is very good article present that dictates commands to create user, browse tables etc ie.

http://www.ntu.edu.sg/home/ehchua/programming/sql/MySQL_HowTo.html#zz-3.1

Passing parameters to a JQuery function

<script type="text/javascript" src="jquery.js">
</script>

 <script type="text/javascript">

  function omtCallFromAjax(urlVariable)
{ 
    alert("omt:"+urlVariable);
     $("#omtDiv").load("omtt.php?"+urlVariable);
}

 </script>

try this it work for me

Simplest way to detect a mobile device in PHP

<?php 

//-- Very simple way
$useragent = $_SERVER['HTTP_USER_AGENT']; 
$iPod = stripos($useragent, "iPod"); 
$iPad = stripos($useragent, "iPad"); 
$iPhone = stripos($useragent, "iPhone");
$Android = stripos($useragent, "Android"); 
$iOS = stripos($useragent, "iOS");
//-- You can add billion devices 

$DEVICE = ($iPod||$iPad||$iPhone||$Android||$iOS);

if (!$DEVICE) { ?>

<!-- What you want for all non-mobile devices. Anything with all HTML, PHP, CSS, even full page codes-->

<?php }else{ ?> 

<!-- What you want for all mobile devices. Anything with all HTML, PHP, CSS, even full page codes --> 

<?php } ?>

How do you wait for input on the same Console.WriteLine() line?

As Matt has said, use Console.Write. I would also recommend explicitly flushing the output, however - I believe WriteLine does this automatically, but I'd seen oddities when just using Console.Write and then waiting. So Matt's code becomes:

Console.Write("What is your name? ");
Console.Out.Flush();
var name = Console.ReadLine();

Node.js Hostname/IP doesn't match certificate's altnames

Since 0.9.2 (including 0.10.x) node.js now validates certificates by default. This is why you could see it become more strict when you upgrade past node.js 0.8. (HT: https://github.com/mscdex/node-imap/issues/181#issuecomment-14781480)

You can avoid this with the {rejectUnauthorized:false} option, however this has serious security implications. Anything you send to the peer will still be encrypted, but it becomes much easier to mount a man-in-the-middle attack, i.e. your data will be encrypted to the peer but the peer itself is not the server you think it is!

It would be better to first diagnose why the certificate is not authorizing and see if that could be fixed instead.

How to count how many values per level in a given factor?

Use the package plyr with lapply to get frequencies for every value (level) and every variable (factor) in your data frame.

library(plyr)
lapply(df, count)

Using sessions & session variables in a PHP Login Script

$session_start();

extract($_POST);         
//extract data from submit post 

if(isset($submit))  
{

if($user=="user" && $pass=="pass")

{

$_SESSION['user']= $user;   

//if correct password and name store in session 

}
else {

echo "Invalid user and password";

header("Locatin:form.php");

}

if(isset($_SESSION['user'])) 

{

//your home page code here

exit;
}

How do I use Join-Path to combine more than two strings into a file path?

You can use the .NET Path class:

[IO.Path]::Combine('C:\', 'Foo', 'Bar')

PostgreSQL: How to change PostgreSQL user password?

TLDR:

On many systems, a user's account often contains a period, or some sort of punction (user: john.smith, horise.johnson). IN these cases a modification will have to be made to the accepted answer above. The change requires the username to be double-quoted.

Example:

ALTER USER "username.lastname" WITH PASSWORD 'password'; 

Rational:

Postgres is quite picky on when to use a 'double quote' and when to use a 'single quote'. Typically when providing a string you would use a single quote.

refresh div with jquery

I want to just refresh the div, without refreshing the page ... Is this possible?

Yes, though it isn't going to be obvious that it does anything unless you change the contents of the div.

If you just want the graphical fade-in effect, simply remove the .html(data) call:

$("#panel").hide().fadeIn('fast');

Here is a demo you can mess around with: http://jsfiddle.net/ZPYUS/

It changes the contents of the div without making an ajax call to the server, and without refreshing the page. The content is hard coded, though. You can't do anything about that fact without contacting the server somehow: ajax, some sort of sub-page request, or some sort of page refresh.

html:

<div id="panel">test data</div>
<input id="changePanel" value="Change Panel" type="button">?

javascript:

$("#changePanel").click(function() {
    var data = "foobar";
    $("#panel").hide().html(data).fadeIn('fast');
});?

css:

div {
    padding: 1em;
    background-color: #00c000;
}

input {
    padding: .25em 1em;
}?

Change background position with jQuery

Here you go:

$(document).ready(function(){
    $('#submenu li').hover(function(){
        $('#carousel').css('background-position', '10px 10px');
    }, function(){
        $('#carousel').css('background-position', '');
    });
});

String contains another string

You can use .indexOf():

if(str.indexOf(substr) > -1) {

}

What is the difference between dim and set in vba


However, I don't think this is what you're really asking.

Sometimes I use:

    Dim r as Range
    r = Range("A1")

This will never work. Without Set you will receive runtime error #91 Object variable or With block variable not set. This is because you must use Set to assign a variables value to an object reference. Then the code above will work.

I think the code below illustrates what you're really asking about. Let's suppose we don't declare a type and let r be a Variant type instead.

Public Sub test()
    Dim r
    debug.print TypeName(r)

    Set r = Range("A1")
    debug.print TypeName(r)

    r = Range("A1")
    debug.print TypeName(r)
End Sub

So, let's break down what happens here.

  1. r is declared as a Variant

    `Dim r` ' TypeName(r) returns "Empty", which is the value for an uninitialized variant
    
  2. r is set to the Range containing cell "A1"

    Set r = Range("A1") ' TypeName(r) returns "Range"
    
  3. r is set to the value of the default property of Range("A1").

    r = Range("A1") ' TypeName(r) returns "String"
    

In this case, the default property of a Range is .Value, so the following two lines of code are equivalent.

r = Range("A1")
r = Range("A1").Value

For more about default object properties, please see Chip Pearson's "Default Member of a Class".


As for your Set example:

Other times I use

Set r = Range("A1")

This wouldn't work without first declaring that r is a Range or Variant object... using the Dim statement - unless you don't have Option Explicit enabled, which you should. Always. Otherwise, you're using identifiers that you haven't declared and they are all implicitly declared as Variants.

Daemon Threads Explanation

When your second thread is non-Daemon, your application's primary main thread cannot quit because its exit criteria is being tied to the exit also of non-Daemon thread(s). Threads cannot be forcibly killed in python, therefore your app will have to really wait for the non-Daemon thread(s) to exit. If this behavior is not what you want, then set your second thread as daemon so that it won't hold back your application from exiting.

linking problem: fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

building on these answers - i also had to modify an X86 reference under Librarian -> Command Line -> Additional Options (for the x64 Platform)

How to add CORS request in header in Angular 5

The following worked for me after hours of trying

      $http.post("http://localhost:8080/yourresource", parameter, {headers: 
      {'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } }).

However following code did not work, I am unclear as to why, hopefully someone can improve this answer.

          $http({   method: 'POST', url: "http://localhost:8080/yourresource", 
                    parameter, 
                    headers: {'Content-Type': 'application/json', 
                              'Access-Control-Allow-Origin': '*',
                              'Access-Control-Allow-Methods': 'POST'} 
                })

Receiving "fatal: Not a git repository" when attempting to remote add a Git repo

For that you need to enter one command that is missing from bitbucket commands

Please try git init.

How to create a new database after initally installing oracle database 11g Express Edition?

"How do I create an initial database ?"

You created a database when you installed XE. At some point the installation process prompted you to enter a password for the SYSTEM account. Use that to connect to the XE database using the SQL commandline on the application menu.

The XE documentation is online and pretty helpful. Find it here.

It's worth mentioning that 11g XE has several limitations, one of which is only one database per server. So using the pre-installed database is the sensible option.

Facebook database design?

Have a look at the following database schema, reverse engineered by Anatoly Lubarsky:

Facebook Schema

How do I create a right click context menu in Java Swing?

There's a section on Bringing Up a Popup Menu in the How to Use Menus article of The Java Tutorials which explains how to use the JPopupMenu class.

The example code in the tutorial shows how to add MouseListeners to the components which should display a pop-up menu, and displays the menu accordingly.

(The method you describe is fairly similar to the way the tutorial presents the way to show a pop-up menu on a component.)

Set opacity of background image without affecting child elements

#footer ul li {
  position: relative;
  opacity: 0.99;
}

#footer ul li::before {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: -1;
  background: url(/images/arrow.png) no-repeat 0 50%;
  opacity: 0.5;
}

Hack with opacity .99 (less than 1) creates z-index context so you can not worry about global z-index values. (Try to remove it and see what happens in the next demo where parent wrapper has positive z-index.)
If your element already has z-index, then you don't need this hack.

Demo of this technique.

Databinding an enum property to a ComboBox in WPF

This is a DevExpress specific answer based on the top-voted answer by Gregor S. (currently it has 128 votes).

This means we can keep the styling consistent across the entire application:

enter image description here

Unfortunately, the original answer doesn't work with a ComboBoxEdit from DevExpress without some modifications.

First, the XAML for the ComboBoxEdit:

<dxe:ComboBoxEdit ItemsSource="{Binding Source={xamlExtensions:XamlExtensionEnumDropdown {x:myEnum:EnumFilter}}}"
    SelectedItem="{Binding BrokerOrderBookingFilterSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
    DisplayMember="Description"
    MinWidth="144" Margin="5" 
    HorizontalAlignment="Left"
    IsTextEditable="False"
    ValidateOnTextInput="False"
    AutoComplete="False"
    IncrementalFiltering="True"
    FilterCondition="Like"
    ImmediatePopup="True"/>

Needsless to say, you will need to point xamlExtensions at the namespace that contains the XAML extension class (which is defined below):

xmlns:xamlExtensions="clr-namespace:XamlExtensions"

And we have to point myEnum at the namespace that contains the enum:

xmlns:myEnum="clr-namespace:MyNamespace"

Then, the enum:

namespace MyNamespace
{
    public enum EnumFilter
    {
        [Description("Free as a bird")]
        Free = 0,

        [Description("I'm Somewhat Busy")]
        SomewhatBusy = 1,

        [Description("I'm Really Busy")]
        ReallyBusy = 2
    }
}

The problem in with the XAML is that we can't use SelectedItemValue, as this throws an error as the setter is unaccessable (bit of an oversight on your part, DevExpress). So we have to modify our ViewModel to obtain the value directly from the object:

private EnumFilter _filterSelected = EnumFilter.All;
public object FilterSelected
{
    get
    {
        return (EnumFilter)_filterSelected;
    }
    set
    {
        var x = (XamlExtensionEnumDropdown.EnumerationMember)value;
        if (x != null)
        {
            _filterSelected = (EnumFilter)x.Value;
        }
        OnPropertyChanged("FilterSelected");
    }
}

For completeness, here is the XAML extension from the original answer (slightly renamed):

namespace XamlExtensions
{
    /// <summary>
    ///     Intent: XAML markup extension to add support for enums into any dropdown box, see http://bit.ly/1g70oJy. We can name the items in the
    ///     dropdown box by using the [Description] attribute on the enum values.
    /// </summary>
    public class XamlExtensionEnumDropdown : MarkupExtension
    {
        private Type _enumType;


        public XamlExtensionEnumDropdown(Type enumType)
        {
            if (enumType == null)
            {
                throw new ArgumentNullException("enumType");
            }

            EnumType = enumType;
        }

        public Type EnumType
        {
            get { return _enumType; }
            private set
            {
                if (_enumType == value)
                {
                    return;
                }

                var enumType = Nullable.GetUnderlyingType(value) ?? value;

                if (enumType.IsEnum == false)
                {
                    throw new ArgumentException("Type must be an Enum.");
                }

                _enumType = value;
            }
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            var enumValues = Enum.GetValues(EnumType);

            return (
                from object enumValue in enumValues
                select new EnumerationMember
                       {
                           Value = enumValue,
                           Description = GetDescription(enumValue)
                       }).ToArray();
        }

        private string GetDescription(object enumValue)
        {
            var descriptionAttribute = EnumType
                .GetField(enumValue.ToString())
                .GetCustomAttributes(typeof (DescriptionAttribute), false)
                .FirstOrDefault() as DescriptionAttribute;


            return descriptionAttribute != null
                ? descriptionAttribute.Description
                : enumValue.ToString();
        }

        #region Nested type: EnumerationMember
        public class EnumerationMember
        {
            public string Description { get; set; }
            public object Value { get; set; }
        }
        #endregion
    }
}

Disclaimer: I have no affiliation with DevExpress. Telerik is also a great library.

commands not found on zsh

As others have said, simply restarting the terminal after you've made changes should reset and changes you've made to your ~/.zshrc file. For instance after adding function to open visual studio:

function code {  
    if [[ $# = 0 ]]
    then
        open -a "Visual Studio Code"
    else
        local argPath="$1"
        [[ $1 = /* ]] && argPath="$1" || argPath="$PWD/${1#./}"
        open -a "Visual Studio Code" "$argPath"
    fi
}

I was able to use the keyword code to open the program from the command line.

How to hide reference counts in VS2013?

Workaround....

In VS 2015 Professional (and probably other versions). Go to Tools / Options / Environment / Fonts and Colours. In the "Show Settings For" drop-down, select "CodeLens" Choose the smallest font you can find e.g. Calibri 6. Change the foreground colour to your editor foreground colour (say "White") Click OK.

Array functions in jQuery

Look into the jQuery functions .grep() and .map()

fe_sendauth: no password supplied

This occurs if the password for the database is not given.

default="postgres://postgres:[email protected]:5432/DBname"

How to check if a value exists in an array in Ruby

Try

['Cat', 'Dog', 'Bird'].include?('Dog')

What is the facade design pattern?

Facade Design Pattern comes under Structural Design Pattern. In short Facade means the exterior appearance. It means in Facade design pattern we hide something and show only what actually client requires. Read more at below blog: http://www.sharepointcafe.net/2017/03/facade-design-pattern-in-aspdotnet.html

Accessing Imap in C#

I haven't tried it myself, but this is a free library you could try (I not so sure about the SSL part on this one):

http://www.codeproject.com/KB/IP/imaplibrary.aspx

Also, there is xemail, which has parameters for SSL:

http://xemail-net.sourceforge.net/

[EDIT] If you (or the client) have the money for a professional mail-client, this thread has some good recommendations:

Recommendations for a .NET component to access an email inbox

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply?

In general, the key to avoiding an explicit loop would be to join (merge) 2 instances of the dataframe on rowindex-1==rowindex.

Then you would have a big dataframe containing rows of r and r-1, from where you could do a df.apply() function.

However the overhead of creating the large dataset may offset the benefits of parallel processing...

Set "Homepage" in Asp.Net MVC

Step 1: Click on Global.asax File in your Solution.

Step 2: Then Go to Definition of

RouteConfig.RegisterRoutes(RouteTable.Routes);

Step 3: Change Controller Name and View Name

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(name: "Default",
                        url: "{controller}/{action}/{id}",
                        defaults: new { controller = "Home", 
                                        action = "Index", 
                                        id = UrlParameter.Optional }
                        );
    }
}

How to emulate a do-while loop in Python?

My code below might be a useful implementation, highlighting the main difference between vs as I understand it.

So in this one case, you always go through the loop at least once.

first_pass = True
while first_pass or condition:
    first_pass = False
    do_stuff()

How can I sort one set of data to match another set of data in Excel?

You can use VLOOKUP.

Assuming those are in columns A and B in Sheet1 and Sheet2 each, 22350 is in cell A2 of Sheet1, you can use:

=VLOOKUP(A2, Sheet2!A:B, 2, 0)

This will return you #N/A if there are no matches. Drag/Fill/Copy&Paste the formula to the bottom of your table and that should do it.

Correct way of using log4net (logger naming)

My Answer might be coming late, but I think it can help newbie. You shall not see logs executed unless the changes are made as below.

2 Files have to be changes when you implement Log4net.


  1. Add Reference of log4net.dll in the project.
  2. app.config
  3. Class file where you will implement Logs.

Inside [app.config] :

First, under 'configSections', you need to add below piece of code;

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />

Then, under 'configuration' block, you need to write below piece of code.(This piece of code is customised as per my need , but it works like charm.)

<log4net debug="true">
    <logger name="log">
      <level value="All"></level>
      <appender-ref ref="RollingLogFileAppender" />
    </logger>

    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="log.txt" />
      <appendToFile value="true" />
      <rollingStyle value="Composite" />
      <maxSizeRollBackups value="1" />
      <maximumFileSize value="1MB" />
      <staticLogFileName value="true" />

      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %C.%M [%line] %-5level - %message %newline %exception %newline" />
      </layout>
    </appender>
</log4net>

Inside Calling Class :

Inside the class where you are going to use this log4net, you need to declare below piece of code.

 ILog log = LogManager.GetLogger("log");

Now, you are ready call log wherever you want in that same class. Below is one of the method you can call while doing operations.

log.Error("message");

Auto logout with Angularjs based on idle user

ng-Idle looks like the way to go, but I could not figure out Brian F's modifications and wanted to timeout for a sleeping session too, also I had a pretty simple use case in mind. I pared it down to the code below. It hooks events to reset a timeout flag (lazily placed in $rootScope). It only detects the timeout has happened when the user returns (and triggers an event) but that's good enough for me. I could not get angular's $location to work here but again, using document.location.href gets the job done.

I stuck this in my app.js after the .config has run.

app.run(function($rootScope,$document) 
{
  var d = new Date();
  var n = d.getTime();  //n in ms

    $rootScope.idleEndTime = n+(20*60*1000); //set end time to 20 min from now
    $document.find('body').on('mousemove keydown DOMMouseScroll mousewheel mousedown touchstart', checkAndResetIdle); //monitor events

    function checkAndResetIdle() //user did something
    {
      var d = new Date();
      var n = d.getTime();  //n in ms

        if (n>$rootScope.idleEndTime)
        {
            $document.find('body').off('mousemove keydown DOMMouseScroll mousewheel mousedown touchstart'); //un-monitor events

            //$location.search('IntendedURL',$location.absUrl()).path('/login'); //terminate by sending to login page
            document.location.href = 'https://whatever.com/myapp/#/login';
            alert('Session ended due to inactivity');
        }
        else
        {
            $rootScope.idleEndTime = n+(20*60*1000); //reset end time
        }
    }
});

How to Set user name and Password of phpmyadmin

You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.

Android Button Onclick

If you write like this in Button tag in xml file : android:onClick="setLogin" then

Do like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<Button
    android:id="@+id/button1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/btn"
    android:onClick="onClickBtn" />

</LinearLayout>

and in Code part:

public class StartUpActivity extends Activity 
{
    public void onCreate(Bundle savedInstanceState) 
    {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);    
    }

    public void onClickBtn(View v)
    {
        Toast.makeText(this, "Clicked on Button", Toast.LENGTH_LONG).show();
    } 
}

and no need all this:

 Button button = (Button) findViewById(R.id.button1);
 button.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        // TODO Auto-generated method stub

    }
 });

Check it once;

How do I convert a org.w3c.dom.Document object to a String?

If you are ok to do transformation, you may try this.

DocumentBuilderFactory domFact = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFact.newDocumentBuilder();
Document doc = builder.parse(st);
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
System.out.println("XML IN String format is: \n" + writer.toString());

How can I send mail from an iPhone application

Below code is used in my application to send email with an attachment here the attachments is an image .You can send any type of file only thing is to keep in mind is that you had to specify the correct 'mimeType'

add this to your .h file

#import <MessageUI/MFMailComposeViewController.h>

Add MessageUI.framework to your project file

NSArray *paths = SSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:@"myGreenCard.png"];



MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:@"Green card application"];
[controller setMessageBody:@"Hi , <br/>  This is my new latest designed green card." isHTML:YES]; 
[controller addAttachmentData:[NSData dataWithContentsOfFile:getImagePath] mimeType:@"png" fileName:@"My Green Card"];
if (controller)
    [self presentModalViewController:controller animated:YES];
[controller release];

Delegate method is as shown below

  -(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error;
{
    if (result == MFMailComposeResultSent) {
        NSLog(@"It's away!");
    }
    [self dismissModalViewControllerAnimated:YES];
}

How to get the index of an item in a list in a single step?

  1. Simple solution to find index for any string value in the List.

Here is code for List Of String:

int indexOfValue = myList.FindIndex(a => a.Contains("insert value from list"));
  1. Simple solution to find index for any Integer value in the List.

Here is Code for List Of Integer:

    int indexOfNumber = myList.IndexOf(/*insert number from list*/);

Serializing to JSON in jQuery

I haven't used it but you might want to try the jQuery plugin written by Mark Gibson

It adds the two functions: $.toJSON(value), $.parseJSON(json_str, [safe]).

Failed to load the JNI shared Library (JDK)

You have change proper version of the JAVA_HOME and PATH in environmental variables.

Does "git fetch --tags" include "git fetch"?

Note: this answer is only valid for git v1.8 and older.

Most of this has been said in the other answers and comments, but here's a concise explanation:

  • git fetch fetches all branch heads (or all specified by the remote.fetch config option), all commits necessary for them, and all tags which are reachable from these branches. In most cases, all tags are reachable in this way.
  • git fetch --tags fetches all tags, all commits necessary for them. It will not update branch heads, even if they are reachable from the tags which were fetched.

Summary: If you really want to be totally up to date, using only fetch, you must do both.

It's also not "twice as slow" unless you mean in terms of typing on the command-line, in which case aliases solve your problem. There is essentially no overhead in making the two requests, since they are asking for different information.

Delete multiple rows by selecting checkboxes using PHP

Delete Multiple checkbox using PHP Code

<input type="checkbox" name="chkbox[]  value=".$row[0]."/>
<input type="submit" name="delete" value="delete"/>
<?php
if(isset($_POST['delete']))
{
 $cnt=array();
 $cnt=count($_POST['chkbox']);
 for($i=0;$i<$cnt;$i++)
  {
     $del_id=$_POST['chkbox'][$i];
     $query="delete from $tablename where Id=".$del_id;
     mysql_query($query);
  }
}

Extract the first word of a string in a SQL Server query

Try This:

Select race_id, race_description
, Case patIndex ('%[ /-]%', LTrim (race_description))
    When 0 Then LTrim (race_description)
    Else substring (LTrim (race_description), 1, patIndex ('%[ /-]%', LTrim (race_description)) - 1)
End race_abbreviation

from tbl_races

Difference between StringBuilder and StringBuffer

First lets see the similarities: Both StringBuilder and StringBuffer are mutable. That means you can change the content of them, with in the same location.

Differences: StringBuffer is mutable and synchronized as well. Where as StringBuilder is mutable but not synchronized by default.

Meaning of synchronized (synchronization): When some thing is synchronized, then multiple threads can access, and modify it with out any problem or side effect. StringBuffer is synchronized, so you can use it with multiple threads with out any problem.

Which one to use when? StringBuilder : When you need a string, which can be modifiable, and only one thread is accessing and modifying it. StringBuffer : When you need a string, which can be modifiable, and multiple threads are accessing and modifying it.

Note : Don't use StringBuffer unnecessarily, i.e., don't use it if only one thread is modifying and accessing it because it has lot of locking and unlocking code for synchronization which will unnecessarily take up CPU time. Don't use locks unless it is required.

Sqlite primary key on multiple columns

PRIMARY KEY (id, name) didn't work for me. Adding a constraint did the job instead.

CREATE TABLE IF NOT EXISTS customer (
    id INTEGER, name TEXT,
    user INTEGER,
    CONSTRAINT PK_CUSTOMER PRIMARY KEY (user, id)
)

C# - Simplest way to remove first occurrence of a substring from another string

Wrote a quick TDD Test for this

    [TestMethod]
    public void Test()
    {
        var input = @"ProjectName\Iteration\Release1\Iteration1";
        var pattern = @"\\Iteration";

        var rgx = new Regex(pattern);
        var result = rgx.Replace(input, "", 1);

        Assert.IsTrue(result.Equals(@"ProjectName\Release1\Iteration1"));
    }

rgx.Replace(input, "", 1); says to look in input for anything matching the pattern, with "", 1 time.

How can we convert an integer to string in AngularJs

.toString() is available, or just add "" to the end of the int

var x = 3,
    toString = x.toString(),
    toConcat = x + "";

Angular is simply JavaScript at the core.

How to find the foreach index?

It should be noted that you can call key() on any array to find the current key its on. As you can guess current() will return the current value and next() will move the array's pointer to the next element.

What is `related_name` used for in Django?

The related_name attribute specifies the name of the reverse relation from the User model back to your model.

If you don't specify a related_name, Django automatically creates one using the name of your model with the suffix _set, for instance User.map_set.all().

If you do specify, e.g. related_name=maps on the User model, User.map_set will still work, but the User.maps. syntax is obviously a bit cleaner and less clunky; so for example, if you had a user object current_user, you could use current_user.maps.all() to get all instances of your Map model that have a relation to current_user.

The Django documentation has more details.

Passing JavaScript array to PHP through jQuery $.ajax

You need to turn this into a string. You can do this using the stringify method in the JSON2 library.

http://www.json.org/

http://www.json.org/js.html

The code would look something like:

var myJSONText = JSON.stringify(myObject);

So

['Location Zero', 'Location One', 'Location Two'];

Will become:

"['Location Zero', 'Location One', 'Location Two']"

You'll have to refer to a PHP guru on how to handle this on the server. I think other answers here intimate a solution.

Data can be returned from the server in a similar way. I.e. you can turn it back into an object.

var myObject = JSON.parse(myJSONString);

Spring Boot without the web server

Remove folowing dependancy on your pom file will work for me

  <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

Add comma to numbers every three digits

A more thorough solution

The core of this is the replace call. So far, I don't think any of the proposed solutions handle all of the following cases:

  • Integers: 1000 => '1,000'
  • Strings: '1000' => '1,000'
  • For strings:
    • Preserves zeros after decimal: 10000.00 => '10,000.00'
    • Discards leading zeros before decimal: '01000.00 => '1,000.00'
    • Does not add commas after decimal: '1000.00000' => '1,000.00000'
    • Preserves leading - or +: '-1000.0000' => '-1,000.000'
    • Returns, unmodified, strings containing non-digits: '1000k' => '1000k'

The following function does all of the above.

addCommas = function(input){
  // If the regex doesn't match, `replace` returns the string unmodified
  return (input.toString()).replace(
    // Each parentheses group (or 'capture') in this regex becomes an argument 
    // to the function; in this case, every argument after 'match'
    /^([-+]?)(0?)(\d+)(.?)(\d+)$/g, function(match, sign, zeros, before, decimal, after) {

      // Less obtrusive than adding 'reverse' method on all strings
      var reverseString = function(string) { return string.split('').reverse().join(''); };

      // Insert commas every three characters from the right
      var insertCommas  = function(string) { 

        // Reverse, because it's easier to do things from the left
        var reversed           = reverseString(string);

        // Add commas every three characters
        var reversedWithCommas = reversed.match(/.{1,3}/g).join(',');

        // Reverse again (back to normal)
        return reverseString(reversedWithCommas);
      };

      // If there was no decimal, the last capture grabs the final digit, so
      // we have to put it back together with the 'before' substring
      return sign + (decimal ? insertCommas(before) + decimal + after : insertCommas(before + after));
    }
  );
};

You could use it in a jQuery plugin like this:

$.fn.addCommas = function() {
  $(this).each(function(){
    $(this).text(addCommas($(this).text()));
  });
};

javascript create array from for loop

Remove obj and just do this inside your for loop:

arr.push(i);

Also, the i < yearEnd condition will not include the final year, so change it to i <= yearEnd.

source command not found in sh shell

The source builtin is a bashism. Write this simply as . instead.

e.g.

. $FILE

# OR you may need to use a relative path (such as in an `npm` script):

. ./$FILE

https://wiki.ubuntu.com/DashAsBinSh#source

Check if value is in select list with JQuery

Here is another similar option. In my case, I'm checking values in another box as I build a select list. I kept running into undefined values when I would compare, so I set my check this way:

if ( $("#select-box option[value='" + thevalue + "']").val() === undefined) { //do stuff }

I've no idea if this approach is more expensive.

Can Selenium interact with an existing browser session?

This is a duplicate answer **Reconnect to a driver in python selenium ** This is applicable on all drivers and for java api.

  1. open a driver
driver = webdriver.Firefox()  #python
  1. extract to session_id and _url from driver object.
url = driver.command_executor._url       #"http://127.0.0.1:60622/hub"
session_id = driver.session_id            #'4e167f26-dc1d-4f51-a207-f761eaf73c31'
  1. Use these two parameter to connect to your driver.
driver = webdriver.Remote(command_executor=url,desired_capabilities={})
driver.close()   # this prevents the dummy browser
driver.session_id = session_id

And you are connected to your driver again.

driver.get("http://www.mrsmart.in")

Javascript | Set all values of an array

The ES6 approach is very clean. So first you initialize an array of x length, and then call the fill method on it.

let arr = new Array(3).fill(9)

this will create an array with 3 elements like:

[9, 9, 9]

jQuery validate: How to add a rule for regular expression validation?

    $.validator.methods.checkEmail = function( value, element ) {
        return this.optional( element ) || /[a-z]+@[a-z]+\.[a-z]+/.test( value );
    }

    $("#myForm").validate({
        rules: {
            email: {
                required: true,
                checkEmail: true
            }
        },
        messages: {
            email: "incorrect email"
        }
    });

Find the smallest positive integer that does not occur in a given sequence

This works very well for java. It uses bitwise exclusive OR and assignment operator

    public int solution(int[] A) {
        // write your code in Java SE 8
        int sol = 0;
        for(int val:A){
            sol ^= val;
        }
        return sol;
    }
}


Android Studio: Drawable Folder: How to put Images for Multiple dpi?

  1. Right click "drawable"
  2. Click on "New", then "Image Asset"
  3. Change "Icon Type" to "Action Bar and Tab Icons"
  4. Change "Asset Type" to "Clip Art" for icon & "Image" for images
  5. For Icon: Click on "Clip Art" icon button & choose your icon
  6. For Image: Click on "Path" folder icon & choose your image
  7. For "Name" type in your icon / image file name

What is the difference between & vs @ and = in angularJS

It took me a hell of a long time to really get a handle on this. The key to me was in understanding that "@" is for stuff that you want evaluated in situ and passed through into the directive as a constant where "=" actually passes the object itself.

There's a nice blog post that explains this this at: http://blog.ramses.io/technical/AngularJS-the-difference-between-@-&-and-=-when-declaring-directives-using-isolate-scopes

How do we download a blob url video

If you can NOT find the .m3u8 file you will need to do a couple of steps different.

1) Go to the network tab and sort by Media

Sort by media

2) You will see something here and select the first item. In my example, it's an mpd file. then copy the Request URL.

3) Next, download the file using your favorite command line tool using the URL from step 2.

youtube-dl -f bestvideo+bestaudio https://url.com/destination/stream.mpd

4) Depending on the encoding you might have to join the audio and video files together but this will depend on a video by video case.

CSS selector (id contains part of text)

Try this:

a[id*='Some:Same'][id$='name']

This will get you all a elements with id containing

Some:Same

and have the id ending in

name

How to Get the Query Executed in Laravel 5? DB::getQueryLog() Returning Empty Array

This code is for:

  • Laravel 5.2
  • Log the statements into the mysql database

Here is the code, which is based on @milz 's answer:

    DB::listen(function($sql) {
        $LOG_TABLE_NAME = 'log';
        foreach ($sql->bindings as $i => $binding) {
            if ($binding instanceof \DateTime) {
                $sql->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
            } else {
                if (is_string($binding)) {
                    $sql->bindings[$i] = "'$binding'";
                }
            }
        }
        // Insert bindings into query
        $query = str_replace(array('%', '?'), array('%%', '%s'), $sql->sql);
        $query = vsprintf($query, $sql->bindings);
        if(stripos($query, 'insert into `'.$LOG_TABLE_NAME.'`')===false){
            $toLog = new LogModel();
            $toLog->uId = 100;
            $toLog->sql = $query;
            $toLog->save();
        }
    });

The core is the if(stripos... line, which prevents the recursion of inserting the insert into log sql statement into database.

Python Error: "ValueError: need more than 1 value to unpack"

You shouldn't be doing tuple dereferencing on values that can change like your line below.

 script, user_name = argv

The line above will fail if you pass less than one argument or more than one argument. A better way of doing this is to do something like this:

 for arg in argv[1:]:
     print arg

Of cause you will do something other than print the args. Maybe put a series of 'if' statement in the 'for' loop that set variables depending on the arguments passed. An even better way is to use the getopt or optparse packages.

Windows equivalent of OS X Keychain?

Credential dumping on Windows, even with "Credential Manager" is still an issue, and I don't think there is any way to prevent it outside of special hardware. MacOS keychain doesn't have this problem and so I don't think there is an exact equivalent.

bootstrap 3 tabs not working properly

This will work

$(".nav-tabs a").click(function(){
     $(this).tab('show');
 });

generate random string for div id

A edited version of @jfriend000 version:

    /**
     * Generates a random string
     * 
     * @param int length_
     * @return string
     */
    function randomString(length_) {

        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz'.split('');
        if (typeof length_ !== "number") {
            length_ = Math.floor(Math.random() * chars.length_);
        }
        var str = '';
        for (var i = 0; i < length_; i++) {
            str += chars[Math.floor(Math.random() * chars.length)];
        }
        return str;
    }

How can I add an item to a IEnumerable<T> collection?

To add second message you need to -

IEnumerable<T> items = new T[]{new T("msg")};
items = items.Concat(new[] {new T("msg2")})

How can I fix WebStorm warning "Unresolved function or method" for "require" (Firefox Add-on SDK)

Do you mean that require() is not resolved? You need to either add require.js to your project or enable Node.js Globals predefined library in Settings/Languages and Frameworks/JavaScript/Libraries.

(Edited settings path by @yurik)

In WebStorm 2016.x-2017.x: make sure that the Node.js Core library is enabled in Settings (Preferences) | Languages & Frameworks | Node.js and NPM

In IntelliJ 2018.3.2+ go to Settings (Preferences) | Languages & Frameworks | Node.js and NPM and enable Coding assistance for Node.js

How do I test a single file using Jest?

I just installed Jest as global, ran jest myFileToTest.spec.js, and it worked.

Decreasing for loops in Python impossible?

Late to the party, but for anyone tasked with creating their own or wants to see how this would work, here's the function with an added bonus of rearranging the start-stop values based on the desired increment:

def RANGE(start, stop=None, increment=1):
    if stop is None:
        stop = start
        start = 1

    value_list = sorted([start, stop])

    if increment == 0:
        print('Error! Please enter nonzero increment value!')
    else:
        value_list = sorted([start, stop])
        if increment < 0:
            start = value_list[1]
            stop = value_list[0]
            while start >= stop:
                worker = start
                start += increment
                yield worker
        else:
            start = value_list[0]
            stop = value_list[1]
            while start < stop:
                worker = start
                start += increment
                yield worker

Negative increment:

for i in RANGE(1, 10, -1):
    print(i)

Or, with start-stop reversed:

for i in RANGE(10, 1, -1):
    print(i)

Output:

10
9
8
7
6
5
4
3
2
1

Regular increment:

for i in RANGE(1, 10):
    print(i)

Output:

1
2
3
4
5
6
7
8
9

Zero increment:

for i in RANGE(1, 10, 0):
    print(i)

Output:

'Error! Please enter nonzero increment value!'

Is log(n!) = T(n·log(n))?

enter image description here

Sorry, I don't know how to use LaTeX syntax on stackoverflow..

Reading/parsing Excel (xls) files with Python

For xlsx I like the solution posted earlier as https://web.archive.org/web/20180216070531/https://stackoverflow.com/questions/4371163/reading-xlsx-files-using-python. I uses modules from the standard library only.

def xlsx(fname):
    import zipfile
    from xml.etree.ElementTree import iterparse
    z = zipfile.ZipFile(fname)
    strings = [el.text for e, el in iterparse(z.open('xl/sharedStrings.xml')) if el.tag.endswith('}t')]
    rows = []
    row = {}
    value = ''
    for e, el in iterparse(z.open('xl/worksheets/sheet1.xml')):
        if el.tag.endswith('}v'):  # Example: <v>84</v>                            
            value = el.text
        if el.tag.endswith('}c'):  # Example: <c r="A3" t="s"><v>84</v></c>                                 
            if el.attrib.get('t') == 's':
                value = strings[int(value)]
            letter = el.attrib['r']  # Example: AZ22                         
            while letter[-1].isdigit():
                letter = letter[:-1]
            row[letter] = value
            value = ''
        if el.tag.endswith('}row'):
            rows.append(row)
            row = {}
    return rows

Improvements added are fetching content by sheet name, using re to get the column and checking if sharedstrings are used.

def xlsx(fname,sheet):
    import zipfile
    from xml.etree.ElementTree import iterparse
    import re
    z = zipfile.ZipFile(fname)
    if 'xl/sharedStrings.xml' in z.namelist():
        # Get shared strings
        strings = [element.text for event, element
                   in iterparse(z.open('xl/sharedStrings.xml')) 
                   if element.tag.endswith('}t')]
    sheetdict = { element.attrib['name']:element.attrib['sheetId'] for event,element in iterparse(z.open('xl/workbook.xml'))
                                      if element.tag.endswith('}sheet') }
    rows = []
    row = {}
    value = ''

    if sheet in sheets:
    sheetfile = 'xl/worksheets/sheet'+sheets[sheet]+'.xml'
    #print(sheet,sheetfile)
    for event, element in iterparse(z.open(sheetfile)):
        # get value or index to shared strings
        if element.tag.endswith('}v') or element.tag.endswith('}t'):
            value = element.text
        # If value is a shared string, use value as an index
        if element.tag.endswith('}c'):
            if element.attrib.get('t') == 's':
                value = strings[int(value)]
            # split the row/col information so that the row leter(s) can be separate
            letter = re.sub('\d','',element.attrib['r'])
            row[letter] = value
            value = ''
        if element.tag.endswith('}row'):
            rows.append(row)
            row = {}

    return rows

session handling in jquery

Assuming you're referring to this plugin, your code should be:

// To Store
$(function() {
    $.session.set("myVar", "value");
});


// To Read
$(function() {
    alert($.session.get("myVar"));
});

Before using a plugin, remember to read its documentation in order to learn how to use it. In this case, an usage example can be found in the README.markdown file, which is displayed on the project page.

Execution failed for task :':app:mergeDebugResources'. Android Studio

By default, Android Studio has a maximum heap size of 1280MB. If you are working on a large project, or your system has a lot of RAM, you can improve performance by increasing the maximum heap size for Android Studio processes, such as the core IDE, Gradle daemon, and Kotlin daemon.

If you use a 64-bit system that has at least 5 GB of RAM, you can also adjust the heap sizes for your project manually. To do so, follow these steps:

Click File > Settings from the menu bar (or Android Studio > Preferences on macOS). Click Appearance & Behavior > System Settings > Memory Settings.

For more Info click

https://developer.android.com/studio/intro/studio-config

enter image description here

How to loop through each and every row, column and cells in a GridView and get its value

foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            for (int i = 0; i < dataGridView1.Columns.Count; i++)
            {
                String header = dataGridView1.Columns[i].HeaderText;
                //String cellText = row.Cells[i].Text;
                DataGridViewColumn column = dataGridView1.Columns[i]; // column[1] selects the required column 
                column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; // sets the AutoSizeMode of column defined in previous line
                int colWidth = column.Width; // store columns width after auto resize           
                colWidth += 50; // add 30 pixels to what 'colWidth' already is
                this.dataGridView1.Columns[i].Width = colWidth; // set the columns width to the value stored in 'colWidth'
            }
        }

Want to make Font Awesome icons clickable

Using bootstrap with font awesome.

<a class="btn btn-large btn-primary logout" href="#">
        <i class="fa fa-sign-out" aria-hidden="true">Logout</i>
</a>

Operator overloading ==, !=, Equals

In fact, this is a "how to" subject. So, here is the reference implementation:

    public class BOX
    {
        double height, length, breadth;

        public static bool operator == (BOX b1, BOX b2)
        {
            if ((object)b1 == null)
                return (object)b2 == null;

            return b1.Equals(b2);
        }

        public static bool operator != (BOX b1, BOX b2)
        {
            return !(b1 == b2);
        }

        public override bool Equals(object obj)
        {
            if (obj == null || GetType() != obj.GetType())
                return false;

            var b2 = (BOX)obj;
            return (length == b2.length && breadth == b2.breadth && height == b2.height);
        }

        public override int GetHashCode()
        {
            return height.GetHashCode() ^ length.GetHashCode() ^ breadth.GetHashCode();
        }
    }

REF: https://msdn.microsoft.com/en-us/library/336aedhh(v=vs.100).aspx#Examples

UPDATE: the cast to (object) in the operator == implementation is important, otherwise, it would re-execute the operator == overload, leading to a stackoverflow. Credits to @grek40.

This (object) cast trick is from Microsoft String == implementaiton. SRC: https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/string.cs#L643

Checking for Undefined In React

I was face same problem ..... And I got solution by using typeof()

if (typeof(value) !== 'undefined' && value != null) {
         console.log('Not Undefined and Not Null')
  } else {
         console.log('Undefined or Null')
}

You must have to use typeof() to identified undefined

Windows Task Scheduler doesn't start batch file task

Had the same issue, make sure you check "Run only when user is logged on" at least that is what made my bat file alive again.

JavaFX and OpenJDK

According to Oracle integration of OpenJDK & javaFX will be on Q1-2014 ( see roadmap : http://www.oracle.com/technetwork/java/javafx/overview/roadmap-1446331.html ). So, for the 1st question the answer is that you have to wait until then. For the 2nd question there is no other way. So, for now go with java swing or start javaFX and wait

clear data inside text file in c++

Deleting the file will also remove the content. See remove file.

Set scroll position

Note that if you want to scroll an element instead of the full window, elements don't have the scrollTo and scrollBy methods. You should:

var el = document.getElementById("myel"); // Or whatever method to get the element

// To set the scroll
el.scrollTop = 0;
el.scrollLeft = 0;

// To increment the scroll
el.scrollTop += 100;
el.scrollLeft += 100;

You can also mimic the window.scrollTo and window.scrollBy functions to all the existant HTML elements in the webpage on browsers that don't support it natively:

Object.defineProperty(HTMLElement.prototype, "scrollTo", {
    value: function(x, y) {
        el.scrollTop = y;
        el.scrollLeft = x;
    },
    enumerable: false
});

Object.defineProperty(HTMLElement.prototype, "scrollBy", {
    value: function(x, y) {
        el.scrollTop += y;
        el.scrollLeft += x;
    },
    enumerable: false
});

so you can do:

var el = document.getElementById("myel"); // Or whatever method to get the element, again

// To set the scroll
el.scrollTo(0, 0);

// To increment the scroll
el.scrollBy(100, 100);

NOTE: Object.defineProperty is encouraged, as directly adding properties to the prototype is a breaking bad habit (When you see it :-).

Sql error on update : The UPDATE statement conflicted with the FOREIGN KEY constraint

I guess if you change the id_no, some of the foreign keys would not reference anything, thus the constraint violation. You could add initialy deffered to the foreign keys, so the constraints are checked when the changes are commited

multiprocessing: How do I share a dict among multiple processes?

Maybe you can try pyshmht, sharing memory based hash table extension for Python.

Notice

  1. It's not fully tested, just for your reference.

  2. It currently lacks lock/sem mechanisms for multiprocessing.

XPath:: Get following Sibling

You should be looking for the second tr that has the td that equals ' Color Digest ', then you need to look at either the following sibling of the first td in the tr, or the second td.

Try the following:

//tr[td='Color Digest'][2]/td/following-sibling::td[1]

or

//tr[td='Color Digest'][2]/td[2]

http://www.xpathtester.com/saved/76bb0bca-1896-43b7-8312-54f924a98a89

Select parent element of known element in Selenium

Little more about XPath axes

Lets say we have below HTML structure:

<div class="third_level_ancestor">
    <nav class="second_level_ancestor">
        <div class="parent">
            <span>Child</span>
        </div>
    </nav>
</div>
  1. //span/parent::* - returns any element which is direct parent.

In this case output is <div class="parent">

  1. //span/parent::div[@class="parent"] - returns parent element only of exact node type and only if specified predicate is True.

Output: <div class="parent">

  1. //span/ancestor::* - returns all ancestors (including parent).

Output: <div class="parent">, <nav class="second_level_ancestor">, <div class="third_level_ancestor">...

  1. //span/ancestor-or-self::* - returns all ancestors and current element itself.

Output: <span>Child</span>, <div class="parent">, <nav class="second_level_ancestor">, <div class="third_level_ancestor">...

  1. //span/ancestor::div[2] - returns second ancestor (starting from parent) of type div.

Output: <div class="third_level_ancestor">

MySQL "Or" Condition

Use brackets to group the OR statements.

mysql_query("SELECT * FROM Drinks WHERE email='$Email' AND (date='$Date_Today' OR date='$Date_Yesterday' OR date='$Date_TwoDaysAgo' OR date='$Date_ThreeDaysAgo' OR date='$Date_FourDaysAgo' OR date='$Date_FiveDaysAgo' OR date='$Date_SixDaysAgo' OR date='$Date_SevenDaysAgo')");

You can also use IN

mysql_query("SELECT * FROM Drinks WHERE email='$Email' AND date IN ('$Date_Today','$Date_Yesterday','$Date_TwoDaysAgo','$Date_ThreeDaysAgo','$Date_FourDaysAgo','$Date_FiveDaysAgo','$Date_SixDaysAgo','$Date_SevenDaysAgo')");

Valid content-type for XML, HTML and XHTML documents

HTML: text/html, full-stop.

XHTML: application/xhtml+xml, or only if following HTML compatbility guidelines, text/html. See the W3 Media Types Note.

XML: text/xml, application/xml (RFC 2376).

There are also many other media types based around XML, for example application/rss+xml or image/svg+xml. It's a safe bet that any unrecognised but registered ending in +xml is XML-based. See the IANA list for registered media types ending in +xml.

(For unregistered x- types, all bets are off, but you'd hope +xml would be respected.)

How to change the default charset of a MySQL table?

If you want to change the table default character set and all character columns to a new character set, use a statement like this:

ALTER TABLE tbl_name CONVERT TO CHARACTER SET charset_name;

So query will be:

ALTER TABLE etape_prospection CONVERT TO CHARACTER SET utf8;

How does a PreparedStatement avoid or prevent SQL injection?

The SQL used in a PreparedStatement is precompiled on the driver. From that point on, the parameters are sent to the driver as literal values and not executable portions of SQL; thus no SQL can be injected using a parameter. Another beneficial side effect of PreparedStatements (precompilation + sending only parameters) is improved performance when running the statement multiple times even with different values for the parameters (assuming that the driver supports PreparedStatements) as the driver does not have to perform SQL parsing and compilation each time the parameters change.

Could not load file or assembly '' or one of its dependencies

Juntos answer is correct but you should also consider:

For the unity v2.1.505.2 different AssemblyVersion and AssemblyFileVersion attributes are specified:

enter image description here

AssemblyFileVersion is used by the NuGet but CLR does not care about it! CLR is going to use only AssemblyVersion!

So your redirects should be applied to a version that specified in AssemblyVersion attribute. So 2.1.505.0 should be used

<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
 <assemblyIdentity name="Microsoft.Practices.Unity" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.1.505.0" newVersion="2.1.505.0" />
</dependentAssembly>
</assemblyBinding>

See also: What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

Using GregorianCalendar with SimpleDateFormat

SimpleDateFormat.format() method takes a Date as a parameter. You can get a Date from a Calendar by calling its getTime() method:

public static String format(GregorianCalendar calendar) {
    SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
    fmt.setCalendar(calendar);
    String dateFormatted = fmt.format(calendar.getTime());

    return dateFormatted;
}

Also note that the months start at 0, so you probably meant:

int month = Integer.parseInt(splitDate[1]) - 1;

Wait until all jQuery Ajax requests are done?

NOTE: The above answers use functionality that didn't exist at the time that this answer was written. I recommend using jQuery.when() instead of these approaches, but I'm leaving the answer for historical purposes.

-

You could probably get by with a simple counting semaphore, although how you implement it would be dependent on your code. A simple example would be something like...

var semaphore  = 0,     // counting semaphore for ajax requests
    all_queued = false; // bool indicator to account for instances where the first request might finish before the second even starts

semaphore++;
$.get('ajax/test1.html', function(data) {
    semaphore--;
    if (all_queued && semaphore === 0) {
        // process your custom stuff here
    }
});

semaphore++;
$.get('ajax/test2.html', function(data) {
    semaphore--;
    if (all_queued && semaphore === 0) {
        // process your custom stuff here
    }
});

semaphore++;
$.get('ajax/test3.html', function(data) {
    semaphore--;
    if (all_queued && semaphore === 0) {
        // process your custom stuff here
    }
});

semaphore++;
$.get('ajax/test4.html', function(data) {
    semaphore--;
    if (all_queued && semaphore === 0) {
        // process your custom stuff here
    }
});

// now that all ajax requests are queued up, switch the bool to indicate it
all_queued = true;

If you wanted this to operate like {async: false} but you didn't want to lock the browser, you could accomplish the same thing with a jQuery queue.

var $queue = $("<div/>");
$queue.queue(function(){
    $.get('ajax/test1.html', function(data) {
        $queue.dequeue();
    });
}).queue(function(){
    $.get('ajax/test2.html', function(data) {
        $queue.dequeue();
    });
}).queue(function(){
    $.get('ajax/test3.html', function(data) {
        $queue.dequeue();
    });
}).queue(function(){
    $.get('ajax/test4.html', function(data) {
        $queue.dequeue();
    });
});

Batch script to find and replace a string in text file without creating an extra output file for storing the modified file

@echo off 
    setlocal enableextensions disabledelayedexpansion

    set "search=%1"
    set "replace=%2"

    set "textFile=Input.txt"

    for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        >>"%textFile%" echo(!line:%search%=%replace%!
        endlocal
    )

for /f will read all the data (generated by the type comamnd) before starting to process it. In the subprocess started to execute the type, we include a redirection overwritting the file (so it is emptied). Once the do clause starts to execute (the content of the file is in memory to be processed) the output is appended to the file.

UILabel font size?

Answers above helped greatly.

Here is the Swift version.

@IBOutlet weak var priceLabel: UILabel!

*.... lines of code later*

self.priceLabel.font = self.priceLabel.font.fontWithSize(22)

What is the difference between localStorage, sessionStorage, session and cookies?

This is an extremely broad scope question, and a lot of the pros/cons will be contextual to the situation.

In all cases, these storage mechanisms will be specific to an individual browser on an individual computer/device. Any requirement to store data on an ongoing basis across sessions will need to involve your application server side - most likely using a database, but possibly XML or a text/CSV file.

localStorage, sessionStorage, and cookies are all client storage solutions. Session data is held on the server where it remains under your direct control.

localStorage and sessionStorage

localStorage and sessionStorage are relatively new APIs (meaning, not all legacy browsers will support them) and are near identical (both in APIs and capabilities) with the sole exception of persistence. sessionStorage (as the name suggests) is only available for the duration of the browser session (and is deleted when the tab or window is closed) - it does, however, survive page reloads (source DOM Storage guide - Mozilla Developer Network).

Clearly, if the data you are storing needs to be available on an ongoing basis then localStorage is preferable to sessionStorage - although you should note both can be cleared by the user so you should not rely on the continuing existence of data in either case.

localStorage and sessionStorage are perfect for persisting non-sensitive data needed within client scripts between pages (for example: preferences, scores in games). The data stored in localStorage and sessionStorage can easily be read or changed from within the client/browser so should not be relied upon for storage of sensitive or security-related data within applications.

Cookies

This is also true for cookies, these can be trivially tampered with by the user, and data can also be read from them in plain text - so if you are wanting to store sensitive data then the session is really your only option. If you are not using SSL, cookie information can also be intercepted in transit, especially on an open wifi.

On the positive side cookies can have a degree of protection applied from security risks like Cross-Site Scripting (XSS)/Script injection by setting an HTTP only flag which means modern (supporting) browsers will prevent access to the cookies and values from JavaScript (this will also prevent your own, legitimate, JavaScript from accessing them). This is especially important with authentication cookies, which are used to store a token containing details of the user who is logged on - if you have a copy of that cookie then for all intents and purposes you become that user as far as the web application is concerned, and have the same access to data and functionality the user has.

As cookies are used for authentication purposes and persistence of user data, all cookies valid for a page are sent from the browser to the server for every request to the same domain - this includes the original page request, any subsequent Ajax requests, all images, stylesheets, scripts, and fonts. For this reason, cookies should not be used to store large amounts of information. The browser may also impose limits on the size of information that can be stored in cookies. Typically cookies are used to store identifying tokens for authentication, session, and advertising tracking. The tokens are typically not human readable information in and of themselves, but encrypted identifiers linked to your application or database.

localStorage vs. sessionStorage vs. Cookies

In terms of capabilities, cookies, sessionStorage, and localStorage only allow you to store strings - it is possible to implicitly convert primitive values when setting (these will need to be converted back to use them as their type after reading) but not Objects or Arrays (it is possible to JSON serialise them to store them using the APIs). Session storage will generally allow you to store any primitives or objects supported by your Server Side language/framework.

Client-side vs. Server-side

As HTTP is a stateless protocol - web applications have no way of identifying a user from previous visits on returning to the web site - session data usually relies on a cookie token to identify the user for repeat visits (although rarely URL parameters may be used for the same purpose). Data will usually have a sliding expiry time (renewed each time the user visits), and depending on your server/framework data will either be stored in-process (meaning data will be lost if the web server crashes or is restarted) or externally in a state server or database. This is also necessary when using a web-farm (more than one server for a given website).

As session data is completely controlled by your application (server side) it is the best place for anything sensitive or secure in nature.

The obvious disadvantage of server-side data is scalability - server resources are required for each user for the duration of the session, and that any data needed client side must be sent with each request. As the server has no way of knowing if a user navigates to another site or closes their browser, session data must expire after a given time to avoid all server resources being taken up by abandoned sessions. When using session data you should, therefore, be aware of the possibility that data will have expired and been lost, especially on pages with long forms. It will also be lost if the user deletes their cookies or switches browsers/devices.

Some web frameworks/developers use hidden HTML inputs to persist data from one page of a form to another to avoid session expiration.

localStorage, sessionStorage, and cookies are all subject to "same-origin" rules which means browsers should prevent access to the data except the domain that set the information to start with.

For further reading on client storage technologies see Dive Into Html 5.

How to get a microtime in Node.js?

I'm not so proud about this solution but you can have timestamp in microsecond or nanosecond in this way:

const microsecond = () => Number(Date.now() + String(process.hrtime()[1]).slice(3,6))
const nanosecond = () => Number(Date.now() + String(process.hrtime()[1]).slice(3))

// usage
microsecond() // return 1586878008997591
nanosecond()  // return 1586878009000645600

// Benchmark with 100 000 iterations
// Date.now: 7.758ms
// microsecond: 33.382ms
// nanosecond: 31.252ms

Know that:

  • This solution works exclusively with node.js,
  • This is about 3 to 10 times slower than Date.now()
  • Weirdly, it seems very accurate, hrTime seems to follow exactly js timestamp ticks.
  • You can replace Date.now() by Number(new Date()) to get timestamp in milliseconds

Edit:

Here a solution to have microsecond with comma, however, the number version will be rounded natively by javascript. So if you want the same format every time, you should use the String version of it.

const microsecondWithCommaString = () => (Date.now() + '.' + String(process.hrtime()[1]).slice(3,7))
const microsecondWithComma = () => Number(Date.now() + '.' + String(process.hrtime()[1]).slice(3,7))

microsecondWithCommaString() // return "1586883629984.8997"
microsecondWithComma() // return 1586883629985.966

Create a simple Login page using eclipse and mysql

use this code it is working

// index.jsp or login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="login" method="post">
Username : <input type="text" name="username"><br>
Password : <input type="password" name="pass"><br>
<input type="submit"><br>
</form>

</body>
</html>

// authentication servlet class

    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    public class auth extends HttpServlet {
        private static final long serialVersionUID = 1L;

        public auth() {
            super();
        }
        protected void doGet(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {

        }

        protected void doPost(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {

            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

            String username = request.getParameter("username");
            String pass = request.getParameter("pass");

            String sql = "select * from reg where username='" + username + "'";
            Connection conn = null;

            try {
                conn = DriverManager.getConnection("jdbc:mysql://localhost/Exam",
                        "root", "");
                Statement s = conn.createStatement();

                java.sql.ResultSet rs = s.executeQuery(sql);
                String un = null;
                String pw = null;
                String name = null;

            /* Need to put some condition in case the above query does not return any row, else code will throw Null Pointer exception */   

            PrintWriter prwr1 = response.getWriter();               
            if(!rs.isBeforeFirst()){
                prwr1.write("<h1> No Such User in Database<h1>");
            } else {

/* Conditions to be executed after at least one row is returned by query execution */ 
                while (rs.next()) {
                    un = rs.getString("username");
                    pw = rs.getString("password");
                    name = rs.getString("name");
                }

                PrintWriter pww = response.getWriter();

                if (un.equalsIgnoreCase(username) && pw.equals(pass)) {
                                // use this or create request dispatcher 
                    response.setContentType("text/html");
                    pww.write("<h1>Welcome, " + name + "</h1>");
                } else {
                    pww.write("wrong username or password\n");
                }
              }

            } catch (SQLException e) {
                e.printStackTrace();
            }

        }

    }

CSS Always On Top

Ensure position is on your element and set the z-index to a value higher than the elements you want to cover.

element {
    position: fixed;
    z-index: 999;
}

div {
    position: relative;
    z-index: 99;
}

It will probably require some more work than that but it's a start since you didn't post any code.

What is the __del__ method, How to call it?

I wrote up the answer for another question, though this is a more accurate question for it.

How do constructors and destructors work?

Here is a slightly opinionated answer.

Don't use __del__. This is not C++ or a language built for destructors. The __del__ method really should be gone in Python 3.x, though I'm sure someone will find a use case that makes sense. If you need to use __del__, be aware of the basic limitations per http://docs.python.org/reference/datamodel.html:

  • __del__ is called when the garbage collector happens to be collecting the objects, not when you lose the last reference to an object and not when you execute del object.
  • __del__ is responsible for calling any __del__ in a superclass, though it is not clear if this is in method resolution order (MRO) or just calling each superclass.
  • Having a __del__ means that the garbage collector gives up on detecting and cleaning any cyclic links, such as losing the last reference to a linked list. You can get a list of the objects ignored from gc.garbage. You can sometimes use weak references to avoid the cycle altogether. This gets debated now and then: see http://mail.python.org/pipermail/python-ideas/2009-October/006194.html.
  • The __del__ function can cheat, saving a reference to an object, and stopping the garbage collection.
  • Exceptions explicitly raised in __del__ are ignored.
  • __del__ complements __new__ far more than __init__. This gets confusing. See http://www.algorithm.co.il/blogs/programming/python-gotchas-1-del-is-not-the-opposite-of-init/ for an explanation and gotchas.
  • __del__ is not a "well-loved" child in Python. You will notice that sys.exit() documentation does not specify if garbage is collected before exiting, and there are lots of odd issues. Calling the __del__ on globals causes odd ordering issues, e.g., http://bugs.python.org/issue5099. Should __del__ called even if the __init__ fails? See http://mail.python.org/pipermail/python-dev/2000-March/thread.html#2423 for a long thread.

But, on the other hand:

And my pesonal reason for not liking the __del__ function.

  • Everytime someone brings up __del__ it devolves into thirty messages of confusion.
  • It breaks these items in the Zen of Python:
    • Simple is better than complicated.
    • Special cases aren't special enough to break the rules.
    • Errors should never pass silently.
    • In the face of ambiguity, refuse the temptation to guess.
    • There should be one – and preferably only one – obvious way to do it.
    • If the implementation is hard to explain, it's a bad idea.

So, find a reason not to use __del__.

A long bigger than Long.MAX_VALUE

You can't. If you have a method called isBiggerThanMaxLong(long) it should always return false.

If you were to increment the bits of Long.MAX_VALUE, the next value should be Long.MIN_VALUE. Read up on twos-complement and that should tell you why.

Create a Cumulative Sum Column in MySQL

If performance is an issue, you could use a MySQL variable:

set @csum := 0;
update YourTable
set cumulative_sum = (@csum := @csum + count)
order by id;

Alternatively, you could remove the cumulative_sum column and calculate it on each query:

set @csum := 0;
select id, count, (@csum := @csum + count) as cumulative_sum
from YourTable
order by id;

This calculates the running sum in a running way :)

DateTime.ToString() format that can be used in a filename or extension?

I have a similar situation but I want a consistent way to be able to use DateTime.Parse from the filename as well, so I went with

DateTime.Now.ToString("s").Replace(":", ".") // <-- 2016-10-25T16.50.35

When I want to parse, I can simply reverse the Replace call. This way I don't have to type in any yymmdd stuff or guess what formats DateTime.Parse allows.

How to call Stored Procedure in a View?

create view sampleView as 
select field1, field2, ... 
from dbo.MyTableValueFunction

Note that even if your MyTableValueFunction doesn't accept any parameters, you still need to include parentheses after it, i.e.:

... from dbo.MyTableValueFunction()

Without the parentheses, you'll get an "Invalid object name" error.

How to convert upper case letters to lower case

str.lower() converts all cased characters to lowercase.

Asynchronous Process inside a javascript for loop

_x000D_
_x000D_
var i = 0;_x000D_
var length = 10;_x000D_
_x000D_
function for1() {_x000D_
  console.log(i);_x000D_
  for2();_x000D_
}_x000D_
_x000D_
function for2() {_x000D_
  if (i == length) {_x000D_
    return false;_x000D_
  }_x000D_
  setTimeout(function() {_x000D_
    i++;_x000D_
    for1();_x000D_
  }, 500);_x000D_
}_x000D_
for1();
_x000D_
_x000D_
_x000D_

Here is a sample functional approach to what is expected here.

How does one use the onerror attribute of an img element

very simple

  <img onload="loaded(this, 'success')" onerror="error(this, 
 'error')"  src="someurl"  alt="" />

 function loaded(_this, status){
   console.log(_this, status)
  // do your work in load
 }
 function error(_this, status){
  console.log(_this, status)
  // do your work in error
  }

How to extract one column of a csv file

You can also use while loop

IFS=,
while read name val; do
        echo "............................"

        echo Name: "$name"
done<itemlst.csv

What is the difference between a static and const variable?

Constants can't be changed, static variables have more to do with how they are allocated and where they are accessible.

Check out this site.

basic authorization command for curl

curl -D- -X GET -H "Authorization: Basic ZnJlZDpmcmVk" -H "Content-Type: application/json" http://localhost:7990/rest/api/1.0/projects

--note

base46 encode =ZnJlZDpmcmVk

How to create a directory if it doesn't exist using Node.js?

Using async / await:

const mkdirP = async (directory) => {
  try {
    return await fs.mkdirAsync(directory);
  } catch (error) {
    if (error.code != 'EEXIST') {
      throw e;
    }
  }
};

You will need to promisify fs:

import nodeFs from 'fs';
import bluebird from 'bluebird';

const fs = bluebird.promisifyAll(nodeFs);

Mongoose and multiple database in single node.js project

According to the fine manual, createConnection() can be used to connect to multiple databases.

However, you need to create separate models for each connection/database:

var conn      = mongoose.createConnection('mongodb://localhost/testA');
var conn2     = mongoose.createConnection('mongodb://localhost/testB');

// stored in 'testA' database
var ModelA    = conn.model('Model', new mongoose.Schema({
  title : { type : String, default : 'model in testA database' }
}));

// stored in 'testB' database
var ModelB    = conn2.model('Model', new mongoose.Schema({
  title : { type : String, default : 'model in testB database' }
}));

I'm pretty sure that you can share the schema between them, but you have to check to make sure.

how to print an exception using logger?

Use: LOGGER.log(Level.INFO, "Got an exception.", e);
or LOGGER.info("Got an exception. " + e.getMessage());

Switching a DIV background image with jQuery

One way to do this is to put both images in the HTML, inside a SPAN or DIV, you can hide the default either with CSS, or with JS on page load. Then you can toggle on click. Here is a similar example I am using to put left/down icons on a list:

$(document).ready(function(){
    $(".button").click(function () {
        $(this).children(".arrow").toggle();
            return false;
    });
});

<a href="#" class="button">
    <span class="arrow">
        <img src="/images/icons/left.png" alt="+" />
    </span>
    <span class="arrow" style="display: none;">
        <img src="/images/down.png" alt="-" />
    </span>
</a>

How do I add an existing Solution to GitHub from Visual Studio 2013

None of the answers were specific to my problem, so here's how I did it.

This is for Visual Studio 2015 and I had already made a repository on Github.com

If you already have your repository URL copy it and then in visual studio:

  • Go to Team Explorer
  • Click the "Sync" button
  • It should have 3 options listed with "get started" links.
  • I chose the "get started" link against "publish to remote repository", which it the bottom one
  • A yellow box will appear asking for the URL. Just paste the URL there and click publish.

How to get content body from a httpclient call?

If you are not wanting to use async you can add .Result to force the code to execute synchronously:

private string GetResponseString(string text)
{
    var httpClient = new HttpClient();

    var parameters = new Dictionary<string, string>();
    parameters["text"] = text;

    var response = httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters)).Result;
    var contents = response.Content.ReadAsStringAsync().Result;

    return contents;
 }