Programs & Examples On #Debug backtrace

debug_backtrace() is a PHP function that prints the backtrace.

Return value in SQL Server stored procedure

@EmailAddress varchar(200),
@NickName varchar(100),
@Password varchar(150),
@Sex varchar(50),
@Age int,
@EmailUpdates int,
@UserId int OUTPUT
DECLARE @AA INT
SET @AA=(SELECT COUNT(UserId) FROM RegUsers WHERE EmailAddress = @EmailAddress)

IF @AA> 0
    BEGIN
        SET @UserId = 0
    END
ELSE
    BEGIN
        INSERT INTO RegUsers (EmailAddress,NickName,PassWord,Sex,Age,EmailUpdates) VALUES (@EmailAddress,@NickName,@Password,@Sex,@Age,@EmailUpdates)
        SELECT SCOPE_IDENTITY()
    END

END

Deserialize JSON string to c# object

I think the JavaScriptSerializer does not create a dynamic object.

So you should define the class first:

class MyObj {
    public int arg1 {get;set;}
    public int arg2 {get;set;}
}

And deserialize that instead of object:

serializer.Deserialize<MyObj>(str);

Not testet, please try.

How to show changed file name only with git log?

Now I use the following to get the list of changed files my current branch has, comparing it to master (the compare-to branch is easily changed):

git log --oneline --pretty="format:" --name-only master.. | awk 'NF' | sort -u

Before, I used to rely on this:

git log --name-status <branch>..<branch> | grep -E '^[A-Z]\b' | sort -k 2,2 -u

which outputs a list of files only and their state (added, modified, deleted):

A   foo/bar/xyz/foo.txt
M   foo/bor/bar.txt
...

The -k2,2 option for sort, makes it sort by file path instead of the type of change (A, M, D,).

Define global variable with webpack

I solved this issue by setting the global variables as a static properties on the classes to which they are most relevant. In ES5 it looks like this:

var Foo = function(){...};
Foo.globalVar = {};

Python Timezone conversion

To convert a time in one timezone to another timezone in Python, you could use datetime.astimezone():

time_in_new_timezone = time_in_old_timezone.astimezone(new_timezone)

Given aware_dt (a datetime object in some timezone), to convert it to other timezones and to print the times in a given time format:

#!/usr/bin/env python3
import pytz  # $ pip install pytz

time_format = "%Y-%m-%d %H:%M:%S%z"
tzids = ['Asia/Shanghai', 'Europe/London', 'America/New_York']
for tz in map(pytz.timezone, tzids):
    time_in_tz = aware_dt.astimezone(tz)
    print(f"{time_in_tz:{time_format}}")

If f"" syntax is unavailable, you could replace it with "".format(**vars())

where you could set aware_dt from the current time in the local timezone:

from datetime import datetime
import tzlocal  # $ pip install tzlocal

local_timezone = tzlocal.get_localzone()
aware_dt = datetime.now(local_timezone) # the current time

Or from the input time string in the local timezone:

naive_dt = datetime.strptime(time_string, time_format)
aware_dt = local_timezone.localize(naive_dt, is_dst=None)

where time_string could look like: '2016-11-19 02:21:42'. It corresponds to time_format = '%Y-%m-%d %H:%M:%S'.

is_dst=None forces an exception if the input time string corresponds to a non-existing or ambiguous local time such as during a DST transition. You could also pass is_dst=False, is_dst=True. See links with more details at Python: How do you convert datetime/timestamp from one timezone to another timezone?

Hide Spinner in Input Number - Firefox 29

/* for chrome */
    input[type=number]::-webkit-inner-spin-button,
    input[type=number]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;}             


/* for mozilla */  
   input[type=number] {-moz-appearance: textfield;}

Throw keyword in function's signature

Jalf already linked to it, but the GOTW puts it quite nicely why exception specifications are not as useful as one might hope:

int Gunc() throw();    // will throw nothing (?)
int Hunc() throw(A,B); // can only throw A or B (?)

Are the comments correct? Not quite. Gunc() may indeed throw something, and Hunc() may well throw something other than A or B! The compiler just guarantees to beat them senseless if they do… oh, and to beat your program senseless too, most of the time.

That's just what it comes down to, you probably just will end up with a call to terminate() and your program dying a quick but painful death.

The GOTWs conclusion is:

So here’s what seems to be the best advice we as a community have learned as of today:

  • Moral #1: Never write an exception specification.
  • Moral #2: Except possibly an empty one, but if I were you I’d avoid even that.

Adding a new array element to a JSON object

For example here is a element like button for adding item to basket and appropriate attributes for saving in localStorage.

'<a href="#" cartBtn pr_id='+e.id+' pr_name_en="'+e.nameEn+'" pr_price="'+e.price+'" pr_image="'+e.image+'" class="btn btn-primary"><i class="fa fa-shopping-cart"></i>Add to cart</a>'

var productArray=[];


$(document).on('click','[cartBtn]',function(e){
  e.preventDefault();
  $(this).html('<i class="fa fa-check"></i>Added to cart');
  console.log('Item added ');
  var productJSON={"id":$(this).attr('pr_id'), "nameEn":$(this).attr('pr_name_en'), "price":$(this).attr('pr_price'), "image":$(this).attr('pr_image')};


  if(localStorage.getObj('product')!==null){
    productArray=localStorage.getObj('product');
    productArray.push(productJSON);  
    localStorage.setObj('product', productArray);  
  }
  else{
    productArray.push(productJSON);  
    localStorage.setObj('product', productArray);  
  }


});

Storage.prototype.setObj = function(key, value) {
    this.setItem(key, JSON.stringify(value));
}

Storage.prototype.getObj = function(key) {
    var value = this.getItem(key);
    return value && JSON.parse(value);
}

After adding JSON object to Array result is (in LocalStorage):

[{"id":"99","nameEn":"Product Name1","price":"767","image":"1462012597217.jpeg"},{"id":"93","nameEn":"Product Name2","price":"76","image":"1461449637106.jpeg"},{"id":"94","nameEn":"Product Name3","price":"87","image":"1461449679506.jpeg"}]

after this action you can easily send data to server as List in Java

Full code example is here

How do I store a simple cart using localStorage?

Gridview with two columns and auto resized images

another simple approach with modern built-in stuff like PercentRelativeLayout is now available for new users who hit this problem. thanks to android team for release this item.

<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
app:layout_widthPercent="50%">

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/picture"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop" />

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="#55000000"
        android:paddingBottom="15dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="15dp"
        android:textColor="@android:color/white" />

</FrameLayout>

and for better performance you can use some stuff like picasso image loader which help you to fill whole width of every image parents. for example in your adapter you should use this:

int width= context.getResources().getDisplayMetrics().widthPixels;
    com.squareup.picasso.Picasso
            .with(context)
            .load("some url")
            .centerCrop().resize(width/2,width/2)
            .error(R.drawable.placeholder)
            .placeholder(R.drawable.placeholder)
            .into(item.drawableId);

now you dont need CustomImageView Class anymore.

P.S i recommend to use ImageView in place of Type Int in class Item.

hope this help..

How to find integer array size in java

The length of an array is available as

int l = array.length;

The size of a List is availabe as

int s = list.size();

How to create checkbox inside dropdown?

Simply use bootstrap-multiselect where you can populate dropdown with multiselect option and many more feaatures.

For doc and tutorials you may visit below link

https://www.npmjs.com/package/bootstrap-multiselect

http://davidstutz.de/bootstrap-multiselect/

Find most frequent value in SQL column

If you can't use LIMIT or LIMIT is not an option for your query tool. You can use "ROWNUM" instead, but you will need a sub query:

SELECT FIELD_1, ALIAS1
FROM(SELECT FIELD_1, COUNT(FIELD_1) ALIAS1
    FROM TABLENAME
    GROUP BY FIELD_1
    ORDER BY COUNT(FIELD_1) DESC)
WHERE ROWNUM = 1

PLS-00103: Encountered the symbol when expecting one of the following:

The keyword for Oracle PL/SQL is "ELSIF" ( no extra "E"), not ELSEIF (yes, confusing and stupid)

declare
    var_number number;
begin
    var_number := 10;
    if var_number > 100 then
       dbms_output.put_line(var_number||' is greater than 100');
    elsif var_number < 100 then
       dbms_output.put_line(var_number||' is less than 100');
    else
       dbms_output.put_line(var_number||' is equal to 100');
    end if;
end;

html5: display video inside canvas

You need to update currentTime video element and then draw the frame in canvas. Don't init play() event on the video.

You can also use for ex. this plugin https://github.com/tstabla/stVideo

Metadata file '.dll' could not be found

I am running Visual Studio 2013.

It appears that the build dependencies were incorrect. Deleting the *.suo files did fix the problems I had.

Launch custom android application from android browser

You need to add a pseudo-hostname to the CALLBACK_URL 'app://' doesn't make sense as a URL and cannot be parsed.

How can I list (ls) the 5 last modified files in a directory?

The accepted answer lists only the filenames, but to get the top 5 files one can also use:

ls -lht | head -6

where:

-l outputs in a list format

-h makes output human readable (i.e. file sizes appear in kb, mb, etc.)

-t sorts output by placing most recently modified file first

head -6 will show 5 files because ls prints the block size in the first line of output.

I think this is a slightly more elegant and possibly more useful approach.

Example output:

total 26960312 -rw-r--r--@ 1 user staff 1.2K 11 Jan 11:22 phone2.7.py -rw-r--r--@ 1 user staff 2.7M 10 Jan 15:26 03-cookies-1.pdf -rw-r--r--@ 1 user staff 9.2M 9 Jan 16:21 Wk1_sem.pdf -rw-r--r--@ 1 user staff 502K 8 Jan 10:20 lab-01.pdf -rw-rw-rw-@ 1 user staff 2.0M 5 Jan 22:06 0410-1.wmv

Best programming based games

If you are willing to look at single player games like Light Bot and Manufactoria then I highly recommend RoboZZle. It has conditional commands which include function calls. This allows for complex stack manipulation. There are thousands of user created puzzles from pathetically obvious to mind blowing enigmas. They have recently added support for smartphones.

I also think The Codex of Alchemical Engineering is worth a look.

Does the join order matter in SQL?

If you try joining C on a field from B before joining B, i.e.:

SELECT A.x, 
       A.y, 
       A.z 
FROM A 
   INNER JOIN C
       on B.x = C.x
   INNER JOIN B
       on A.x = B.x

your query will fail, so in this case the order matters.

HTML: how to force links to open in a new tab, not new window

Simply using "target=_blank" will respect the user/browser preference of whether to use a tab or a new window, which in most cases is "doing the right thing".

If you specify the dimensions of the new window, some browsers will use this as an indicator that a certain size is needed, in which case a new window will always be used. Stack overflow code example Stack Overflow

How to find the php.ini file used by the command line?

If you need to pass it to another app, you can do something like:

php --ini | grep Loaded | cut -d" " -f12

returns the path only. php -c $(php --ini | grep Loaded | cut -d" " -f12) will pass in the config file (useful for fpm)

What's the simplest way of detecting keyboard input in a script from the terminal?

This needs run as root: (Warning, this is a system-wide keylogger)

#!/usr/bin/python3

import signal
import keyboard
import time
import os


if not os.geteuid() == 0:
  print("This script needs to be run as root.")
  exit()

def exitNice(signum, frame):
  global running 
  running = False

def keyEvent(e):
  global running
  if e.event_type == "up":
    print("Key up: " + str(e.name))
  if e.event_type == "down":
    print("Key down: " + str(e.name))
  if e.name == "q":
    exitNice("", "")
    print("Quitting")

running = True
signal.signal(signal.SIGINT, exitNice)
keyboard.hook(keyEvent)

print("Press 'q' to quit")
fps = 1/24
while running:
  time.sleep(fps)

Throughput and bandwidth difference?

As an analogy consider a water pipe as a channel. Pipe diameter corresponds to bandwidth or capacity, and pipe contents corresponds to throughput or usage. In the following image we can see three pipes (or channels), all of which are under-utilised, hence, usage could be increased without the need for a bigger pipe.

Bandwidth vs. throughput

How to call Stored Procedures with EntityFramework?

Basically you just have to map the procedure to the entity using Stored Procedure Mapping.

Once mapped, you use the regular method for adding an item in EF, and it will use your stored procedure instead.

Please see: This Link for a walkthrough. The result will be adding an entity like so (which will actually use your stored procedure)

using (var ctx = new SchoolDBEntities())
        {
            Student stud = new Student();
            stud.StudentName = "New sp student";
            stud.StandardId = 262;

            ctx.Students.Add(stud);
            ctx.SaveChanges();
        }

Remove table row after clicking table row delete button

you can do it like this:

<script>
    function SomeDeleteRowFunction(o) {
     //no clue what to put here?
     var p=o.parentNode.parentNode;
         p.parentNode.removeChild(p);
    }
    </script>

    <table>
       <tr>
           <td><input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this)"></td>
       </tr>
       <tr>
           <td><input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this)"></td>
       </tr>
       <tr>
           <td><input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this)"></td>
       </tr>
    </table>

MySQL - SELECT all columns WHERE one column is DISTINCT

I think the best solution would be to do a subquery and then join that to the table. The sub query would return the primary key of the table. Here is an example:

select *
from (
          SELECT row_number() over(partition by link order by day, month) row_id
          , *

          FROM posted 
          WHERE ad='$key' 
          ) x
where x.row_id = 1

What this does is the row_number function puts a numerical sequence partitioned by each distinct link that results in the query.

By taking only those row_numbers that = 1, then you only return 1 row for each link.

The way you change what link gets marked "1" is through the order-by clause in the row_number function.

Hope this helps.

How to change sender name (not email address) when using the linux mail command for autosending mail?

You just need to add a From: header. By default there is none.

echo "Test" | mail -a "From: Someone <[email protected]>" [email protected]

You can add any custom headers using -a:

echo "Test" | mail -a "From: Someone <[email protected]>" \
                   -a "Subject: This is a test" \
                   -a "X-Custom-Header: yes" [email protected]

CSS last-child selector: select last-element of specific class, not last child inside of parent?

if the last element type is article too, last-of-type will not work as expected.

maybe i not really understand how it work.

demo

How to assert two list contain the same elements in Python?

Needs ensure library but you can compare list by:

ensure([1, 2]).contains_only([2, 1])

This will not raise assert exception. Documentation of thin is really thin so i would recommend to look at ensure's codes on github

How to install a PHP IDE plugin for Eclipse directly from the Eclipse environment?

Easiest Way To install PDT

  1. Run eclipse
  2. Click on "Help", "Install New Software"
  3. “Choose all available sites”, in search box type "php"(takes a while to load)
  4. => “programming languages” => "PHP Development Tools", => PhP Development Tools (PDT) SDK Feature.
  5. Restart eclipse
  6. File new => other => php .
  7. Should be able to follow from their

AccessDenied for ListObjects for S3 bucket when permissions are s3:*

I tried the following:

aws s3 ls s3.console.aws.amazon.com/s3/buckets/{bucket name}

This gave me the error:

An error occurred (AccessDenied) when calling the ListObjectsV2 operation: Access Denied

Using this form worked:

aws s3 ls {bucket name}

Equivalent function for DATEADD() in Oracle

--ORACLE SQL EXAMPLE
SELECT
SYSDATE
,TO_DATE(SUBSTR(LAST_DAY(ADD_MONTHS(SYSDATE, -1)),1,10),'YYYY-MM-DD')
FROM DUAL

'System.Net.Http.HttpContent' does not contain a definition for 'ReadAsAsync' and no extension method

or if you have VS 2012 you can goto the package manager console and type Install-Package Microsoft.AspNet.WebApi.Client

This would download the latest version of the package

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

For people using boto3 (Python SDK) use the below code

from botocore.client import Config


s3 = boto3.resource(
    's3',
    aws_access_key_id='xxxxxx',
    aws_secret_access_key='xxxxxx',
    config=Config(signature_version='s3v4')
)

"On Exit" for a Console Application

This code works to catch the user closing the console window:

using System;
using System.Runtime.InteropServices;

class Program {
    static void Main(string[] args) {
        handler = new ConsoleEventDelegate(ConsoleEventCallback);
        SetConsoleCtrlHandler(handler, true);
        Console.ReadLine();
    }

    static bool ConsoleEventCallback(int eventType) {
        if (eventType == 2) {
            Console.WriteLine("Console window closing, death imminent");
        }
        return false;
    }
    static ConsoleEventDelegate handler;   // Keeps it from getting garbage collected
    // Pinvoke
    private delegate bool ConsoleEventDelegate(int eventType);
    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);

}

Beware of the restrictions. You have to respond quickly to this notification, you've got 5 seconds to complete the task. Take longer and Windows will kill your code unceremoniously. And your method is called asynchronously on a worker thread, the state of the program is entirely unpredictable so locking is likely to be required. Do make absolutely sure that an abort cannot cause trouble. For example, when saving state into a file, do make sure you save to a temporary file first and use File.Replace().

Converting a Pandas GroupBy output from Series to DataFrame

I found this worked for me.

import numpy as np
import pandas as pd

df1 = pd.DataFrame({ 
    "Name" : ["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"] , 
    "City" : ["Seattle", "Seattle", "Portland", "Seattle", "Seattle", "Portland"]})

df1['City_count'] = 1
df1['Name_count'] = 1

df1.groupby(['Name', 'City'], as_index=False).count()

Foreign key constraints: When to use ON UPDATE and ON DELETE

You'll need to consider this in context of the application. In general, you should design an application, not a database (the database simply being part of the application).

Consider how your application should respond to various cases.

The default action is to restrict (i.e. not permit) the operation, which is normally what you want as it prevents stupid programming errors. However, on DELETE CASCADE can also be useful. It really depends on your application and how you intend to delete particular objects.

Personally, I'd use InnoDB because it doesn't trash your data (c.f. MyISAM, which does), rather than because it has FK constraints.

NPM clean modules

You can just delete the node_module directory

rm -rf node_modules/

Can you use @Autowired with static fields?

In short, no. You cannot autowire or manually wire static fields in Spring. You'll have to write your own logic to do this.

How to check if array element exists or not in javascript?

var myArray = ["Banana", "Orange", "Apple", "Mango"];

if (myArray.indexOf(searchTerm) === -1) {
  console.log("element doesn't exist");
}
else {
  console.log("element found");
}

Effectively use async/await with ASP.NET Web API

You are not leveraging async / await effectively because the request thread will be blocked while executing the synchronous method ReturnAllCountries()

The thread that is assigned to handle a request will be idly waiting while ReturnAllCountries() does it's work.

If you can implement ReturnAllCountries() to be asynchronous, then you would see scalability benefits. This is because the thread could be released back to the .NET thread pool to handle another request, while ReturnAllCountries() is executing. This would allow your service to have higher throughput, by utilizing threads more efficiently.

Can't get ScriptManager.RegisterStartupScript in WebControl nested in UpdatePanel to work

DO NOT Use GUID For Key

ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UpdatePanel) 
       Guid.NewGuid().ToString(), myScript, true);

and if you want to do that , call Something Like this function

 public static string GetGuidClear(string x)
 {
      return x.Replace("-", "").Replace("0", "").Replace("1", "")
              .Replace("2",  "").Replace("3", "").Replace("4", "")
              .Replace("5", "").Replace("6", "").Replace("7", "")
              .Replace("8", "").Replace("9", "");
 }

Using :: in C++

One use for the 'Unary Scope Resolution Operator' or 'Colon Colon Operator' is for local and global variable selection of identical names:

    #include <iostream>
    using namespace std;
    
    int variable = 20;
    
    int main()
    {
    float variable = 30;
    
    cout << "This is local to the main function: " << variable << endl;
    cout << "This is global to the main function: " << ::variable << endl;
    
    return 0;
    }

The resulting output would be:

This is local to the main function: 30

This is global to the main function: 20

Other uses could be: Defining a function from outside of a class, to access a static variable within a class or to use multiple inheritance.

Read tab-separated file line into array

You could also try,

OIFS=$IFS;
IFS="\t";

animals=`cat animals.txt`
animalArray=$animals;

for animal in $animalArray
do
    echo $animal
done

IFS=$OIFS;

Get exit code for command in bash/ksh

The normal idea would be to run the command and then use $? to get the exit code. However, some times you have multiple cases in which you need to get the exit code. For example, you might need to hide it's output but still return the exit code, or print both the exit code and the output.

ec() { [[ "$1" == "-h" ]] && { shift && eval $* > /dev/null 2>&1; ec=$?; echo $ec; } || eval $*; ec=$?; }

This will give you the option to suppress the output of the command you want the exit code for. When the output is suppressed for the command, the exit code will directly be returned by the function.

I personally like to put this function in my .bashrc file

Below I demonstrate a few ways in which you can use this:


# In this example, the output for the command will be
# normally displayed, and the exit code will be stored
# in the variable $ec.

$ ec echo test
test
$ echo $ec
0

# In this example, the exit code is output
# and the output of the command passed
# to the `ec` function is suppressed.

$ echo "Exit Code: $(ec -h echo test)"
Exit Code: 0

# In this example, the output of the command
# passed to the `ec` function is suppressed
# and the exit code is stored in `$ec`

$ ec -h echo test
$ echo $ec
0

Solution to your code using this function

#!/bin/bash
if [[ "$(ec -h 'ls -l | grep p')" != "0" ]]; then
    echo "Error when executing command: 'grep p' [$ec]"
    exit $ec;
fi

You should also note that the exit code you will be seeing will be for the grep command that's being run, as it is the last command being executed. Not the ls.

How to find the minimum value of a column in R?

Since it is a numeric operation, we should be converting it to numeric form first. This operation cannot take place if the data is in factor data type.
Check the data type of the columns using str().

min(as.numeric(data[,2]))

Sum of values in an array using jQuery

    var arr = ["20.0","40.1","80.2","400.3"],
    sum = 0;
$.each(arr,function(){sum+=parseFloat(this) || 0; });

Worked perfectly for what i needed. Thanks vol7ron

How to loop backwards in python?

To reverse a string without using reversed or [::-1], try something like:

def reverse(text):
    # Container for reversed string
    txet=""

    # store the length of the string to be reversed
    # account for indexes starting at 0
    length = len(text)-1

    # loop through the string in reverse and append each character
    # deprecate the length index
    while length>=0:
        txet += "%s"%text[length]
        length-=1
    return txet

Find objects between two dates MongoDB

Querying for a Date Range (Specific Month or Day) in the MongoDB Cookbook has a very good explanation on the matter, but below is something I tried out myself and it seems to work.

items.save({
    name: "example",
    created_at: ISODate("2010-04-30T00:00:00.000Z")
})
items.find({
    created_at: {
        $gte: ISODate("2010-04-29T00:00:00.000Z"),
        $lt: ISODate("2010-05-01T00:00:00.000Z")
    }
})
=> { "_id" : ObjectId("4c0791e2b9ec877893f3363b"), "name" : "example", "created_at" : "Sun May 30 2010 00:00:00 GMT+0300 (EEST)" }

Based on my experiments you will need to serialize your dates into a format that MongoDB supports, because the following gave undesired search results.

items.save({
    name: "example",
    created_at: "Sun May 30 18.49:00 +0000 2010"
})
items.find({
    created_at: {
        $gte:"Mon May 30 18:47:00 +0000 2015",
        $lt: "Sun May 30 20:40:36 +0000 2010"
    }
})
=> { "_id" : ObjectId("4c079123b9ec877893f33638"), "name" : "example", "created_at" : "Sun May 30 18.49:00 +0000 2010" }

In the second example no results were expected, but there was still one gotten. This is because a basic string comparison is done.

How do I get first name and last name as whole name in a MYSQL query?

When you have three columns : first_name, last_name, mid_name:

SELECT CASE 
    WHEN mid_name IS NULL OR TRIM(mid_name) ='' THEN
        CONCAT_WS( " ", first_name, last_name ) 
    ELSE 
        CONCAT_WS( " ", first_name, mid_name, last_name ) 
    END 
FROM USER;

Setting up a websocket on Apache?

I can't answer all questions, but I will do my best.

As you already know, WS is only a persistent full-duplex TCP connection with framed messages where the initial handshaking is HTTP-like. You need some server that's listening for incoming WS requests and that binds a handler to them.

Now it might be possible with Apache HTTP Server, and I've seen some examples, but there's no official support and it gets complicated. What would Apache do? Where would be your handler? There's a module that forwards incoming WS requests to an external shared library, but this is not necessary with the other great tools to work with WS.

WS server trends now include: Autobahn (Python) and Socket.IO (Node.js = JavaScript on the server). The latter also supports other hackish "persistent" connections like long polling and all the COMET stuff. There are other little known WS server frameworks like Ratchet (PHP, if you're only familiar with that).

In any case, you will need to listen on a port, and of course that port cannot be the same as the Apache HTTP Server already running on your machine (default = 80). You could use something like 8080, but even if this particular one is a popular choice, some firewalls might still block it since it's not supposed to be Web traffic. This is why many people choose 443, which is the HTTP Secure port that, for obvious reasons, firewalls do not block. If you're not using SSL, you can use 80 for HTTP and 443 for WS. The WS server doesn't need to be secure; we're just using the port.

Edit: According to Iharob Al Asimi, the previous paragraph is wrong. I have no time to investigate this, so please see his work for more details.

About the protocol, as Wikipedia shows, it looks like this:

Client sends:

GET /mychat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat
Sec-WebSocket-Version: 13
Origin: http://example.com

Server replies:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat

and keeps the connection alive. If you can implement this handshaking and the basic message framing (encapsulating each message with a small header describing it), then you can use any client-side language you want. JavaScript is only used in Web browsers because it's built-in.

As you can see, the default "request method" is an initial HTTP GET, although this is not really HTTP and looses everything in common with HTTP after this handshaking. I guess servers that do not support

Upgrade: websocket
Connection: Upgrade

will reply with an error or with a page content.

Javascript Confirm popup Yes, No button instead of OK and Cancel

Have a look at http://bootboxjs.com/

Very easy to use:

 bootbox.confirm("Are you sure?", function(result) {
  Example.show("Confirm result: "+result);
});

How to copy file from HDFS to the local file system

bin/hadoop fs -put /localfs/destination/path /hdfs/source/path 

Why is my toFixed() function not working?

Example simple (worked):

var a=Number.parseFloat($("#budget_project").val()); // from input field
var b=Number.parseFloat(html); // from ajax
var c=a-b;
$("#result").html(c.toFixed(2)); // put to id='result' (div or others)

Android: resizing imageview in XML

Please try this one works for me:

<ImageView android:id="@+id/image_view"     
  android:layout_width="wrap_content"  
  android:layout_height="wrap_content"  
  android:adjustViewBounds="true"  
  android:maxWidth="60dp" 
  android:layout_gravity="center" 
  android:maxHeight="60dp"  
  android:scaleType="fitCenter"  
  android:src="@drawable/icon"  
  /> 

Automatically running a batch file as an administrator

Runas.exe won't work here. You can use VBScript to invoke the "Run as Administrator" shell verb. The Elevation Powertoys contain a batchfile that allows you to invoke an elevated command:

elevatecmd.exe

http://blogs.technet.com/b/elevationpowertoys/

Calling JavaScript Function From CodeBehind

This is how I've done it.

HTML markup showing a label and button control is as follows.

<body> 
  <form id="form1" runat="server"> 
  <div> 
    <asp:Label ID="lblJavaScript" runat="server" Text=""></asp:Label> 
    <asp:Button ID="btnShowDialogue" runat="server" Text="Show Dialogue" /> 
  </div> 
  </form> 
</body>

JavaScript function is here.

<head runat="server"> 
  <title>Calling javascript function from code behind example</title> 
  <script type="text/javascript"> 
    function showDialogue() { 
      alert("this dialogue has been invoked through codebehind."); 
    } 
  </script> 
</head>

Code behind to trigger the JavaScript function is here.

lblJavaScript.Text = "<script type='text/javascript'>showDialogue();</script>";

C# compiler error: "not all code paths return a value"

The compiler doesn't get the intricate logic where you return in the last iteration of the loop, so it thinks that you could exit out of the loop and end up not returning anything at all.

Instead of returning in the last iteration, just return true after the loop:

public static bool isTwenty(int num) {
  for(int j = 1; j <= 20; j++) {
    if(num % j != 0) {
      return false;
    }
  }
  return true;
}

Side note, there is a logical error in the original code. You are checking if num == 20 in the last condition, but you should have checked if j == 20. Also checking if num % j == 0 was superflous, as that is always true when you get there.

How to respond to clicks on a checkbox in an AngularJS directive?

This is the way I've been doing this sort of stuff. Angular tends to favor declarative manipulation of the dom rather than a imperative one(at least that's the way I've been playing with it).

The markup

<table class="table">
  <thead>
    <tr>
      <th>
        <input type="checkbox" 
          ng-click="selectAll($event)"
          ng-checked="isSelectedAll()">
      </th>
      <th>Title</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="e in entities" ng-class="getSelectedClass(e)">
      <td>
        <input type="checkbox" name="selected"
          ng-checked="isSelected(e.id)"
          ng-click="updateSelection($event, e.id)">
      </td>
      <td>{{e.title}}</td>
    </tr>
  </tbody>
</table>

And in the controller

var updateSelected = function(action, id) {
  if (action === 'add' && $scope.selected.indexOf(id) === -1) {
    $scope.selected.push(id);
  }
  if (action === 'remove' && $scope.selected.indexOf(id) !== -1) {
    $scope.selected.splice($scope.selected.indexOf(id), 1);
  }
};

$scope.updateSelection = function($event, id) {
  var checkbox = $event.target;
  var action = (checkbox.checked ? 'add' : 'remove');
  updateSelected(action, id);
};

$scope.selectAll = function($event) {
  var checkbox = $event.target;
  var action = (checkbox.checked ? 'add' : 'remove');
  for ( var i = 0; i < $scope.entities.length; i++) {
    var entity = $scope.entities[i];
    updateSelected(action, entity.id);
  }
};

$scope.getSelectedClass = function(entity) {
  return $scope.isSelected(entity.id) ? 'selected' : '';
};

$scope.isSelected = function(id) {
  return $scope.selected.indexOf(id) >= 0;
};

//something extra I couldn't resist adding :)
$scope.isSelectedAll = function() {
  return $scope.selected.length === $scope.entities.length;
};

EDIT: getSelectedClass() expects the entire entity but it was being called with the id of the entity only, which is now corrected

How to reload/refresh jQuery dataTable?

Destroy the datatable first and then draw the datatable.

$('#table1').DataTable().destroy();
$('#table1').find('tbody').append("<tr><td><value1></td><td><value1></td></tr>");
$('#table1').DataTable().draw();

Difference between variable declaration syntaxes in Javascript (including global variables)?

In global scope there is no semantic difference.

But you really should avoid a=0 since your setting a value to an undeclared variable.

Also use closures to avoid editing global scope at all

(function() {
   // do stuff locally

   // Hoist something to global scope
   window.someGlobal = someLocal
}());

Always use closures and always hoist to global scope when its absolutely neccesary. You should be using asynchronous event handling for most of your communication anyway.

As @AvianMoncellor mentioned there is an IE bug with var a = foo only declaring a global for file scope. This is an issue with IE's notorious broken interpreter. This bug does sound familiar so it's probably true.

So stick to window.globalName = someLocalpointer

"Fade" borders in CSS

You could also use box-shadow property with higher value of blur and rgba() color to set opacity level. Sounds like a better choice in your case.

box-shadow: 0 30px 40px rgba(0,0,0,.1);

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

casting int to char using C++ style casting

reinterpret_cast cannot be used for this conversion, the code will not compile. According to C++03 standard section 5.2.10-1:

Conversions that can be performed explicitly using reinterpret_cast are listed below. No other conversion can be performed explicitly using reinterpret_cast.

This conversion is not listed in that section. Even this is invalid:

long l = reinterpret_cast<long>(i)

static_cast is the one which has to be used here. See this and this SO questions.

Java GUI frameworks. What to choose? Swing, SWT, AWT, SwingX, JGoodies, JavaFX, Apache Pivot?

Decision tree:

  1. Frameworks like Qt and SWT need native DLLs. So you have to ask yourself: Are all necessary platforms supported? Can you package the native DLLs with your app?

    See here, how to do this for SWT.

    If you have a choice here, you should prefer Qt over SWT. Qt has been developed by people who understand UI and the desktop while SWT has been developed out of necessity to make Eclipse faster. It's more a performance patch for Java 1.4 than a UI framework. Without JFace, you're missing many major UI components or very important features of UI components (like filtering on tables).

    If SWT is missing a feature that you need, the framework is somewhat hostile to extending it. For example, you can't extend any class in it (the classes aren't final, they just throw exceptions when the package of this.getClass() isn't org.eclipse.swt and you can't add new classes in that package because it's signed).

  2. If you need a native, pure Java solution, that leaves you with the rest. Let's start with AWT, Swing, SwingX - the Swing way.

    AWT is outdated. Swing is outdated (maybe less so but not much work has been done on Swing for the past 10 years). You could argue that Swing was good to begin with but we all know that code rots. And that's especially true for UIs today.

    That leaves you with SwingX. After a longer period of slow progress, development has picked up again. The major drawback with Swing is that it hangs on to some old ideas which very kind of bleeding edge 15 years ago but which feel "clumsy" today. For example, the table views do support filtering and sorting but you still have to configure this. You'll have to write a lot of boiler plate code just to get a decent UI that feels modern.

    Another weak area is theming. As of today, there are a lot of themes around. See here for a top 10. But some are slow, some are buggy, some are incomplete. I hate it when I write a UI and users complain that something doesn't work for them because they selected an odd theme.

  3. JGoodies is another layer on top of Swing, like SwingX. It tries to make Swing more pleasant to use. The web site looks great. Let's have a look at the tutorial ... hm ... still searching ... hang on. It seems that there is no documentation on the web site at all. Google to the rescue. Nope, no useful tutorials at all.

    I'm not feeling confident with a UI framework that tries so hard to hide the documentation from potential new fans. That doesn't mean JGoodies is bad; I just couldn't find anything good to say about it but that it looks nice.

  4. JavaFX. Great, stylish. Support is there but I feel it's more of a shiny toy than a serious UI framework. This feeling roots in the lack of complex UI components like tree tables. There is a webkit-based component to display HTML.

    When it was introduced, my first thought was "five years too late." If your aim is a nice app for phones or web sites, good. If your aim is professional desktop application, make sure it delivers what you need.

  5. Pivot. First time I heard about it. It's basically a new UI framework based on Java2D. So I gave it a try yesterday. No Swing, just tiny bit of AWT (new Font(...)).

    My first impression was a nice one. There is an extensive documentation that helps you getting started. Most of the examples come with live demos (Note: You must have Java enabled in your web browser; this is a security risk) in the web page, so you can see the code and the resulting application side by side.

    In my experience, more effort goes into code than into documentation. By looking at the Pivot docs, a lot of effort must have went into the code. Note that there is currently a bug which prevents some of the examples to work (PIVOT-858) in your browser.

    My second impression of Pivot is that it's easy to use. When I ran into a problem, I could usually solve it quickly by looking at an example. I'm missing a reference of all the styles which each component supports, though.

    As with JavaFX, it's missing some higher level components like a tree table component (PIVOT-306). I didn't try lazy loading with the table view. My impression is that if the underlying model uses lazy loading, then that's enough.

    Promising. If you can, give it a try.

Count character occurrences in a string in C++

Pseudocode:

count = 0
For each character c in string s
  Check if c equals '_'
    If yes, increase count

EDIT: C++ example code:

int count_underscores(string s) {
  int count = 0;

  for (int i = 0; i < s.size(); i++)
    if (s[i] == '_') count++;

  return count;
}

Note that this is code to use together with std::string, if you're using char*, replace s.size() with strlen(s).

Also note: I can understand you want something "as small as possible", but I'd suggest you to use this solution instead. As you see you can use a function to encapsulate the code for you so you won't have to write out the for loop everytime, but can just use count_underscores("my_string_") in the rest of your code. Using advanced C++ algorithms is certainly possible here, but I think it's overkill.

Keyboard shortcut to "untab" (move a block of code to the left) in eclipse / aptana?

Shift-tab does that in Flex Builder (Based on Eclipse) - SO it hopefully should work in regular eclipse :)

Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK)

You can use Cursor like that:

USE master
GO

DECLARE @SQL AS VARCHAR(255)
DECLARE @SPID AS SMALLINT
DECLARE @Database AS VARCHAR(500)
SET @Database = 'AdventureWorks2016CTP3'

DECLARE Murderer CURSOR FOR
SELECT spid FROM sys.sysprocesses WHERE DB_NAME(dbid) = @Database

OPEN Murderer

FETCH NEXT FROM Murderer INTO @SPID
WHILE @@FETCH_STATUS = 0

    BEGIN
    SET @SQL = 'Kill ' + CAST(@SPID AS VARCHAR(10)) + ';'
    EXEC (@SQL)
    PRINT  ' Process ' + CAST(@SPID AS VARCHAR(10)) +' has been killed'
    FETCH NEXT FROM Murderer INTO @SPID
    END 

CLOSE Murderer
DEALLOCATE Murderer

I wrote about that in my blog here: http://www.pigeonsql.com/single-post/2016/12/13/Kill-all-connections-on-DB-by-Cursor

Using LINQ to concatenate strings

You can combine LINQ and string.join() quite effectively. Here I am removing an item from a string. There are better ways of doing this too but here it is:

filterset = String.Join(",",
                        filterset.Split(',')
                                 .Where(f => mycomplicatedMatch(f,paramToMatch))
                       );

add image to uitableview cell

Swift 4 solution:

    cell.imageView?.image = UIImage(named: "yourImageName")

Set default time in bootstrap-datetimepicker

I solved my problem like this

$('#startdatetime-from').datetimepicker({
language: 'en',
format: 'yyyy-MM-dd hh:mm',
defaultDate:new Date()
});

Posting a File and Associated Data to a RESTful WebService preferably as JSON

@RequestMapping(value = "/uploadImageJson", method = RequestMethod.POST)
    public @ResponseBody Object jsongStrImage(@RequestParam(value="image") MultipartFile image, @RequestParam String jsonStr) {
-- use  com.fasterxml.jackson.databind.ObjectMapper convert Json String to Object
}

What is the difference between pull and clone in git?

git clone is used for just downloading exactly what is currently working on the remote server repository and saving it in your machine's folder where that project is placed. Mostly it is used only when we are going to upload the project for the first time. After that pull is the better option.

git pull is basically a (clone(download) + merge) operation and mostly used when you are working as teamwork. In other words, when you want the recent changes in that project, you can pull.

Excel VBA Copy a Range into a New Workbook

Modify to suit your specifics, or make more generic as needed:

Private Sub CopyItOver()
  Set NewBook = Workbooks.Add
  Workbooks("Whatever.xlsx").Worksheets("output").Range("A1:K10").Copy
  NewBook.Worksheets("Sheet1").Range("A1").PasteSpecial (xlPasteValues)
  NewBook.SaveAs FileName:=NewBook.Worksheets("Sheet1").Range("E3").Value
End Sub

How to allow CORS in react.js?

there are 6 ways to do this in React,

number 1 and 2 and 3 are the best:

1-config CORS in the Server-Side

2-set headers manually like this:

resonse_object.header("Access-Control-Allow-Origin", "*");
resonse_object.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

3-config NGINX for proxy_pass which is explained here.

4-bypass the Cross-Origin-Policy with chrom extension(only for development and not recommended !)

5-bypass the cross-origin-policy with URL bellow(only for development)

"https://cors-anywhere.herokuapp.com/{type_your_url_here}"

6-use proxy in your package.json file:(only for development)

if this is your API: http://45.456.200.5:7000/api/profile/

add this part in your package.json file: "proxy": "http://45.456.200.5:7000/",

and then make your request with the next parts of the api:

React.useEffect(() => {
    axios
        .get('api/profile/')
        .then(function (response) {
            console.log(response);
        })
        .catch(function (error) {
            console.log(error);
        });
});

Create a menu Bar in WPF?

<StackPanel VerticalAlignment="Top">
    <Menu Width="Auto" Height="20">
        <MenuItem Header="_File">
            <MenuItem x:Name="AppExit" Header="E_xit" HorizontalAlignment="Left" Width="140" Click="AppExit_Click"/>
        </MenuItem>
        <MenuItem Header="_Tools">
            <MenuItem x:Name="Options" Header="_Options" HorizontalAlignment="Left" Width="140"/>
        </MenuItem>
        <MenuItem Header="_Help">
            <MenuItem x:Name="About" Header="&amp;About" HorizontalAlignment="Left" Width="140"/>
        </MenuItem>
    </Menu>
    <Label Content="Label"/>
</StackPanel>

How to find if an array contains a string

Using the code from my answer to a very similar question:

Sub DoSomething()
Dim Mainfram(4) As String
Dim cell As Excel.Range

Mainfram(0) = "apple"
Mainfram(1) = "pear"
Mainfram(2) = "orange"
Mainfram(3) = "fruit"

For Each cell In Selection
  If IsInArray(cell.Value, MainFram) Then
    Row(cell.Row).Style = "Accent1"
  End If
Next cell

End Sub

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function

How to use jquery $.post() method to submit form values

You have to select and send the form data as well:

$("#post-btn").click(function(){        
    $.post("process.php", $("#reg-form").serialize(), function(data) {
        alert(data);
    });
});

Take a look at the documentation for the jQuery serialize method, which encodes the data from the form fields into a data-string to be sent to the server.

Creating stored procedure with declare and set variables

You should try this syntax - assuming you want to have @OrderID as a parameter for your stored procedure:

CREATE PROCEDURE dbo.YourStoredProcNameHere
   @OrderID INT
AS
BEGIN
 DECLARE @OrderItemID AS INT
 DECLARE @AppointmentID AS INT
 DECLARE @PurchaseOrderID AS INT
 DECLARE @PurchaseOrderItemID AS INT
 DECLARE @SalesOrderID AS INT
 DECLARE @SalesOrderItemID AS INT

 SELECT @OrderItemID = OrderItemID 
 FROM [OrderItem] 
 WHERE OrderID = @OrderID

 SELECT @AppointmentID = AppoinmentID 
 FROM [Appointment] 
 WHERE OrderID = @OrderID

 SELECT @PurchaseOrderID = PurchaseOrderID 
 FROM [PurchaseOrder] 
 WHERE OrderID = @OrderID

END

OF course, that only works if you're returning exactly one value (not multiple values!)

Cluster analysis in R: determine the optimal number of clusters

In order to determine optimal k-cluster in clustering methods. I usually using Elbow method accompany by Parallel processing to avoid time-comsuming. This code can sample like this:

Elbow method

elbow.k <- function(mydata){
dist.obj <- dist(mydata)
hclust.obj <- hclust(dist.obj)
css.obj <- css.hclust(dist.obj,hclust.obj)
elbow.obj <- elbow.batch(css.obj)
k <- elbow.obj$k
return(k)
}

Running Elbow parallel

no_cores <- detectCores()
    cl<-makeCluster(no_cores)
    clusterEvalQ(cl, library(GMD))
    clusterExport(cl, list("data.clustering", "data.convert", "elbow.k", "clustering.kmeans"))
 start.time <- Sys.time()
 elbow.k.handle(data.clustering))
 k.clusters <- parSapply(cl, 1, function(x) elbow.k(data.clustering))
    end.time <- Sys.time()
    cat('Time to find k using Elbow method is',(end.time - start.time),'seconds with k value:', k.clusters)

It works well.

How get total sum from input box values using Javascript?

Try this:

function add() 
{
  var sum = 0;
  var inputs = document.getElementsByTagName("input");
  for(i = 0; i <= inputs.length; i++) 
  {
   if( inputs[i].name == 'qty'+i) 
   {
     sum += parseInt(input[i].value);
   }
  }
  console.log(sum)

}

PHPExcel - creating multiple sheets by iteration

Complementing the coment of @Mark Baker.
Do as follow:

$titles = array('title 1', 'title 2');
$sheet = 0;
foreach($array as $value){
    if($sheet > 0){
        $objPHPExcel->createSheet();
        $sheet = $objPHPExcel->setActiveSheetIndex($sheet);
        $sheet->setTitle("$value");
        //Do you want something more here
    }else{
        $objPHPExcel->setActiveSheetIndex(0)->setTitle("$value");
    }
    $sheet++;
}  

This worked for me. And hope it works for those who need! :)

Save Screen (program) output to a file

Here's a trick: wrap it in sh -c!

screen sh -c './some-script 2>&1 | tee mylog.log'

Where 2>&1 redirects stderr to stdout so tee can catch and log error messages.

What is the purpose of .PHONY in a Makefile?

Let's assume you have install target, which is a very common in makefiles. If you do not use .PHONY, and a file named install exists in the same directory as the Makefile, then make install will do nothing. This is because Make interprets the rule to mean "execute such-and-such recipe to create the file named install". Since the file is already there, and its dependencies didn't change, nothing will be done.

However if you make the install target PHONY, it will tell the make tool that the target is fictional, and that make should not expect it to create the actual file. Hence it will not check whether the install file exists, meaning: a) its behavior will not be altered if the file does exist and b) extra stat() will not be called.

Generally all targets in your Makefile which do not produce an output file with the same name as the target name should be PHONY. This typically includes all, install, clean, distclean, and so on.

Call a "local" function within module.exports from another function in module.exports?

You can also do this to make it more concise and readable. This is what I've seen done in several of the well written open sourced modules:

var self = module.exports = {

  foo: function (req, res, next) {
    return ('foo');
  },

  bar: function(req, res, next) {
    self.foo();
  }

}

How to select the row with the maximum value in each group

A dplyr solution:

library(dplyr)
ID <- c(1,1,1,2,2,2,2,3,3)
Value <- c(2,3,5,2,5,8,17,3,5)
Event <- c(1,1,2,1,2,1,2,2,2)
group <- data.frame(Subject=ID, pt=Value, Event=Event)

group %>%
    group_by(Subject) %>%
    summarize(max.pt = max(pt))

This yields the following data frame:

  Subject max.pt
1       1      5
2       2     17
3       3      5

What does java:comp/env/ do?

After several attempts and going deep in Tomcat's source code I found out that the simple property useNaming="false" did the trick!! Now Tomcat resolves names java:/liferay instead of java:comp/env/liferay

Get the time difference between two datetimes

Instead of

Math.floor(duration.asHours()) + moment.utc(duration.asMilliseconds()).format(":mm:ss")

It's better to do

moment.utc(total.asMilliseconds()).format("HH:mm:ss");

What does "./" (dot slash) refer to in terms of an HTML file path location?

For example css files are in folder named CSS and html files are in folder HTML, and both these are in folder named XYZ means we refer css files in html as

<link rel="stylesheet" type="text/css" href="./../CSS/style.css" />

Here .. moves up to HTML
and . refers to the current directory XYZ

---by this logic you would just reference as:

<link rel="stylesheet" type="text/css" href="CSS/style.css" />

What does if __name__ == "__main__": do?

Before explaining anything about if __name__ == '__main__' it is important to understand what __name__ is and what it does.

What is __name__?

__name__ is a DunderAlias - can be thought of as a global variable (accessible from modules) and works in a similar way to global.

It is a string (global as mentioned above) as indicated by type(__name__) (yielding <class 'str'>), and is an inbuilt standard for both Python 3 and Python 2 versions.

Where:

It can not only be used in scripts but can also be found in both the interpreter and modules/packages.

Interpreter:

>>> print(__name__)
__main__
>>>

Script:

test_file.py:

print(__name__)

Resulting in __main__

Module or package:

somefile.py:

def somefunction():
    print(__name__)

test_file.py:

import somefile
somefile.somefunction()

Resulting in somefile

Notice that when used in a package or module, __name__ takes the name of the file. The path of the actual module or package path is not given, but has its own DunderAlias __file__, that allows for this.

You should see that, where __name__, where it is the main file (or program) will always return __main__, and if it is a module/package, or anything that is running off some other Python script, will return the name of the file where it has originated from.

Practice:

Being a variable means that it's value can be overwritten ("can" does not mean "should"), overwriting the value of __name__ will result in a lack of readability. So do not do it, for any reason. If you need a variable define a new variable.

It is always assumed that the value of __name__ to be __main__ or the name of the file. Once again changing this default value will cause more confusion that it will do good, causing problems further down the line.

example:

>>> __name__ = 'Horrify' # Change default from __main__
>>> if __name__ == 'Horrify': print(__name__)
...
>>> else: print('Not Horrify')
...
Horrify
>>>

It is considered good practice in general to include the if __name__ == '__main__' in scripts.

Now to answer if __name__ == '__main__':

Now we know the behaviour of __name__ things become clearer:

An if is a flow control statement that contains the block of code will execute if the value given is true. We have seen that __name__ can take either __main__ or the file name it has been imported from.

This means that if __name__ is equal to __main__ then the file must be the main file and must actually be running (or it is the interpreter), not a module or package imported into the script.

If indeed __name__ does take the value of __main__ then whatever is in that block of code will execute.

This tells us that if the file running is the main file (or you are running from the interpreter directly) then that condition must execute. If it is a package then it should not, and the value will not be __main__.

Modules:

__name__ can also be used in modules to define the name of a module

Variants:

It is also possible to do other, less common but useful things with __name__, some I will show here:

Executing only if the file is a module or package:

if __name__ != '__main__':
    # Do some useful things 

Running one condition if the file is the main one and another if it is not:

if __name__ == '__main__':
    # Execute something
else:
    # Do some useful things

You can also use it to provide runnable help functions/utilities on packages and modules without the elaborate use of libraries.

It also allows modules to be run from the command line as main scripts, which can be also very useful.

SELECT data from another schema in oracle

In addition to grants, you can try creating synonyms. It will avoid the need for specifying the table owner schema every time.

From the connecting schema:

CREATE SYNONYM pi_int FOR pct.pi_int;

Then you can query pi_int as:

SELECT * FROM pi_int;

Creating runnable JAR with Gradle

  1. Configure Main Class to your Manifest

If you are using gradle project, just add the following into your build.gradle

jar {
    manifest {
        attributes(
               'Main-Class': 'pokerhandscorer.PokerHandScorer'
        )
    }
}
  • Where 'pokerhandscorer' is the name of the package name, and PokerHandScorer is the main class name

This creates a jar file into your \build\libs{jarFilename}.jar

  1. Run jar file using java -jar /{path}/{jarFileName.jar}

java -jar /{path}/{jarFileName.jar}

fatal: The current branch master has no upstream branch

For me, I was pushing the changes to a private repo to which I didn't had the write access. Make sure you have the valid access rights while performing push or pull operations.

You can directly verify via

Install shows error in console: INSTALL FAILED CONFLICTING PROVIDER

Solution 1

Run the app on a physical device instead of the emulator. I encountered this issue and my app didnt have a content provider defined.

Solution 2

In the other instance, i had an instrumented test app installed matching the same applicationId.

To fix the issue i had to run ./gradlew uA - uA short for uninstallAll task.

You can alternatively use the Gradle panel and choose navigate to app\install\uninstallAll task

If you using an emulator, you can wipe out the data

Change background color for selected ListBox item

Or you can apply HighlightBrushKey directly to the ListBox. Setter Property="Background" Value="Transparent" did NOT work. But I did have to set the Foreground to Black.

<ListBox  ... >
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Style.Triggers>
                <Trigger Property="IsSelected" Value="True" >
                    <Setter Property="FontWeight" Value="Bold" />
                    <Setter Property="Background" Value="Transparent" />
                    <Setter Property="Foreground" Value="Black" />
                </Trigger>
            </Style.Triggers>
            <Style.Resources>
                <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/>
            </Style.Resources>
        </Style>                
    </ListBox.ItemContainerStyle>
</ListBox>

XAMPP keeps showing Dashboard/Welcome Page instead of the Configuration Page

I was also experiencing the same issue. 5.5.24 was the latest version that worked for me. The Apache Friends blog has a post, https://www.apachefriends.org/blog/new_xampp_20150723.html, that mentions the newer versions shipping with the 'Dashboard'.

How would I create a UIAlertView in Swift?

The reason it doesn't work because some value you passed to the function isn't correct. swift doesn't like Objective-C, you can put nil to arguments which are class type without any restriction(might be). Argument otherButtonTitles is defined as non-optional which its type do not have (?)at its end. so you must pass a concrete value to it.

How to play a notification sound on websites?

How about the yahoo's media player Just embed yahoo's library

<script type="text/javascript" src="http://mediaplayer.yahoo.com/js"></script> 

And use it like

<a id="beep" href="song.mp3">Play Song</a>

To autostart

$(function() { $("#beep").click(); });

How to generate a random alpha-numeric string

Here is the one-liner by AbacusUtil:

String.valueOf(CharStream.random('0', 'z').filter(c -> N.isLetterOrDigit(c)).limit(12).toArray())

Random doesn't mean it must be unique. To get unique strings, use:

N.uuid() // E.g.: "e812e749-cf4c-4959-8ee1-57829a69a80f". length is 36.
N.guid() // E.g.: "0678ce04e18945559ba82ddeccaabfcd". length is 32 without '-'

How to create string with multiple spaces in JavaScript

var a = 'something' + Array(10).fill('\xa0').join('') + 'something'

number inside Array(10) can be changed to needed number of spaces

Declare a dictionary inside a static class

You can use the static/class constructor to initialize your dictionary:

public static class ErrorCode
{
    public const IDictionary<string, string> ErrorCodeDic;
    public static ErrorCode()
    {
        ErrorCodeDic = new Dictionary<string, string>()
            { {"1", "User name or password problem"} };
    }
}

Error: "Adb connection Error:An existing connection was forcibly closed by the remote host"

I know I'm 4 years late but my answer is for anyone who may not have figured it out. I'm using a Samsung Galaxy S6, what worked for me was:

  1. Disable USB debugging

  2. Disable Developer mode

  3. Unplug the device from the USB cable

  4. Re-enable Developer mode

  5. Re-enable USB debugging

  6. Reconnect the USB cable to your device

It is important you do it in this order as it didn't work until it was done in this order.

How do I create a constant in Python?

from enum import Enum
class StringConsts(str,Enum):
    ONE='one'
    TWO='two'

print(f'Truth is  {StringConsts.ONE=="one"}') #Truth is True
StringConsts.ONE="one" #Error: Cannot reassign

This mixin of Enum and str gives you the power of not having to reimplement setattr (through Enum) and comparison to other str objects (through str).

This might deprecate http://code.activestate.com/recipes/65207-constants-in-python/?in=user-97991 completely.

XPath to select multiple tags

You can avoid the repetition with an attribute test instead:

a/b/*[local-name()='c' or local-name()='d' or local-name()='e']

Contrary to Dimitre's antagonistic opinion, the above is not incorrect in a vacuum where the OP has not specified the interaction with namespaces. The self:: axis is namespace restrictive, local-name() is not. If the OP's intention is to capture c|d|e regardless of namespace (which I'd suggest is even a likely scenario given the OR nature of the problem) then it is "another answer that still has some positive votes" which is incorrect.

You can't be definitive without definition, though I'm quite happy to delete my answer as genuinely incorrect if the OP clarifies his question such that I am incorrect.

Removing object properties with Lodash

This is my solution to deep remove empty properties with Lodash:

const compactDeep = obj => {
    const emptyFields = [];

    function calculateEmpty(prefix, source) {
        _.each(source, (val, key) => {
           if (_.isObject(val) && !_.isEmpty(val)) {
                calculateEmpty(`${prefix}${key}.`, val);
            } else if ((!_.isBoolean(val) && !_.isNumber(val) && !val) || (_.isObject(val) && _.isEmpty(val))) {
                emptyFields.push(`${prefix}${key}`);
            }
        });
    }

    calculateEmpty('', obj);

    return _.omit(obj, emptyFields);
};

c++ compile error: ISO C++ forbids comparison between pointer and integer

A string literal is delimited by quotation marks and is of type char* not char.

Example: "hello"

So when you compare a char to a char* you will get that same compiling error.

char c = 'c';
char *p = "hello";

if(c==p)//compiling error
{
} 

To fix use a char literal which is delimited by single quotes.

Example: 'c'

Run cURL commands from Windows console

  1. Visit download page https://curl.haxx.se/download.html - it's incredible
  2. Choose your sytem in list
  3. Don't forget SSL support, it's obvious now, e.g. for https
  4. Unpack curl.exe and .crt to C:\Windows\System32
  5. Restart cmd
  6. Enjoy > curl https://api.stackexchange.com

p.s. If you want another folder to store executable check your paths > echo %PATH%

How can I move a tag on a git branch to a different commit?

Alias to move one tag to a different commit.

In your sample, to move commit with hash e2ea1639 do: git tagm v0.1 e2ea1639.

For pushed tags, use git tagmp v0.1 e2ea1639.

Both alias keeps you original date and message. If you use git tag -d you lost your original message.

Save them on your .gitconfig file

# Return date of tag. (To use in another alias)
tag-date = "!git show $1 | awk '{ if ($1 == \"Date:\") { print substr($0, index($0,$3)) }}' | tail -2 | head -1 #"

# Show tag message
tag-message = "!git show $1 | awk -v capture=0 '{ if(capture) message=message\"\\n\"$0}; BEGIN {message=\"\"}; { if ($1 == \"Date:\" && length(message)==0 ) {capture=1}; if ($1 == \"commit\" ) {capture=0}  }; END { print message }' | sed '$ d' | cat -s #"

### Move tag. Use: git tagm <tagname> <newcommit> 
tagm = "!GIT_TAG_MESSAGE=$(git tag-message $1) && GIT_COMMITTER_DATE=$(git tag-date $1) && git tag-message $1 && git tag -d $1 && git tag -a $1 $2 -m \"$GIT_TAG_MESSAGE\" #"

### Move pushed tag. Use: git tagmp <tagname> <newcommit> 
tagmp = "!git tagm $1 $2 && git push --delete origin $1 && git push origin $1 #"

How to insert new cell into UITableView in Swift

Swift 5.0, 4.0, 3.0 Updated Solution

Insert at Bottom

self.yourArray.append(msg)

self.tblView.beginUpdates()
self.tblView.insertRows(at: [IndexPath.init(row: self.yourArray.count-1, section: 0)], with: .automatic)
self.tblView.endUpdates()

Insert at Top of TableView

self.yourArray.insert(msg, at: 0)
self.tblView.beginUpdates()
self.tblView.insertRows(at: [IndexPath.init(row: 0, section: 0)], with: .automatic)
self.tblView.endUpdates()

How to use custom packages

For a project hosted on GitHub, here's what people usually do:

github.com/
  laike9m/
    myproject/
      mylib/
        mylib.go
        ...
      main.go

mylib.go

package mylib

...

main.go

import "github.com/laike9m/myproject/mylib"

...

Delete a dictionary item if the key exists

Approach: calculate keys to remove, mutate dict

Let's call keys the list/iterator of keys that you are given to remove. I'd do this:

keys_to_remove = set(keys).intersection(set(mydict.keys()))
for key in keys_to_remove:
    del mydict[key]

You calculate up front all the affected items and operate on them.

Approach: calculate keys to keep, make new dict with those keys

I prefer to create a new dictionary over mutating an existing one, so I would probably also consider this:

keys_to_keep = set(mydict.keys()) - set(keys)
new_dict = {k: v for k, v in mydict.iteritems() if k in keys_to_keep}

or:

keys_to_keep = set(mydict.keys()) - set(keys)
new_dict = {k: mydict[k] for k in keys_to_keep}

How to get build time stamp from Jenkins build variables?

NOTE: This changed in Jenkins 1.597, Please see here for more info regarding the migration

You should be able to view all the global environment variables that are available during the build by navigating to https://<your-jenkins>/env-vars.html.

Replace https://<your-jenkins>/ with the URL you use to get to Jenkins webpage (for example, it could be http://localhost:8080/env-vars.html).

One of the environment variables is :

BUILD_ID
    The current build id, such as "2005-08-22_23-59-59" (YYYY-MM-DD_hh-mm-ss)

If you use jenkins editable email notification, you should be able to use ${ENV, var="BUILD_ID"} in the subject line of your email.

Java : Comparable vs Comparator

When your class implements Comparable, the compareTo method of the class is defining the "natural" ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals() comparisons return true.

A Comparator is its own definition of how to compare two objects, and can be used to compare objects in a way that might not align with the natural ordering.

For example, Strings are generally compared alphabetically. Thus the "a".compareTo("b") would use alphabetical comparisons. If you wanted to compare Strings on length, you would need to write a custom comparator.

In short, there isn't much difference. They are both ends to similar means. In general implement comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.

How to Compare a long value is equal to Long value

Since Java 7 you can use java.util.Objects.equals(Object a, Object b):

These utilities include null-safe or null-tolerant methods

Long id1 = null;
Long id2 = 0l;
Objects.equals(id1, id2));

Send request to curl with post data sourced from a file

I had to use a HTTP connection, because on HTTPS there is default file size limit.

https://techcommunity.microsoft.com/t5/IIS-Support-Blog/Solution-for-Request-Entity-Too-Large-error/ba-p/501134

    curl -i -X 'POST' -F 'file=@/home/testeincremental.xlsx' 'http://example.com/upload.aspx?user=example&password=example123&type=XLSX'

SQL Server returns error "Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'." in Windows application

Got it! Solved the issue modifying the user properties in security session of SQL Server. In SQL Server Management, go into security -> Logon -> Choose the user used for DB connection and go into his properties. Go to "Securators" tab and look for line "Connect SQL", mark "Grant" option and take a try. It works for me!

Regards

How to escape apostrophe (') in MySql?

The MySQL documentation you cite actually says a little bit more than you mention. It also says,

A “'” inside a string quoted with “'” may be written as “''”.

(Also, you linked to the MySQL 5.0 version of Table 8.1. Special Character Escape Sequences, and the current version is 5.6 — but the current Table 8.1. Special Character Escape Sequences looks pretty similar.)

I think the Postgres note on the backslash_quote (string) parameter is informative:

This controls whether a quote mark can be represented by \' in a string literal. The preferred, SQL-standard way to represent a quote mark is by doubling it ('') but PostgreSQL has historically also accepted \'. However, use of \' creates security risks...

That says to me that using a doubled single-quote character is a better overall and long-term choice than using a backslash to escape the single-quote.

Now if you also want to add choice of language, choice of SQL database and its non-standard quirks, and choice of query framework to the equation, then you might end up with a different choice. You don't give much information about your constraints.

How to change font size in html?

Give them a class and add your style to the class.

<style>
  p {
    color: red;
  }
  .paragraph1 {
    font-size: 18px;
  }
  .paragraph2 {
    font-size: 13px;
  }
</style>

<p class="paragraph1">Paragraph 1</p>
<p class="paragraph2">Paragraph 2</p>

Check this EXAMPLE

How to return a value from try, catch, and finally?

It is because you are in a try statement. Since there could be an error, sum might not get initialized, so put your return statement in the finally block, that way it will for sure be returned.

Make sure that you initialize sum outside the try/catch/finally so that it is in scope.

What is the difference between require and require-dev sections in composer.json?

Different Environments

Typically, software will run in different environments:

  • development
  • testing
  • staging
  • production

Different Dependencies in Different Environments

The dependencies which are declared in the require section of composer.json are typically dependencies which are required for running an application or a package in

  • staging
  • production

environments, whereas the dependencies declared in the require-dev section are typically dependencies which are required in

  • developing
  • testing

environments.

For example, in addition to the packages used for actually running an application, packages might be needed for developing the software, such as:

  • friendsofphp/php-cs-fixer (to detect and fix coding style issues)
  • squizlabs/php_codesniffer (to detect and fix coding style issues)
  • phpunit/phpunit (to drive the development using tests)
  • etc.

Deployment

Now, in development and testing environments, you would typically run

$ composer install

to install both production and development dependencies.

However, in staging and production environments, you only want to install dependencies which are required for running the application, and as part of the deployment process, you would typically run

$ composer install --no-dev

to install only production dependencies.

Semantics

In other words, the sections

  • require
  • require-dev

indicate to composer which packages should be installed when you run

$ composer install

or

$ composer install --no-dev

That is all.

Note Development dependencies of packages your application or package depend on will never be installed

For reference, see:

Access props inside quotes in React JSX

Here is the Best Option for Dynamic className or Props , just do some concatenation like we do in Javascript.

     className={
        "badge " +
        (this.props.value ? "badge-primary " : "badge-danger ") +
        " m-4"
      }

Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App

STEP 1: Include the following in OnConfiguring()

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
            .AddJsonFile("appsettings.json")
            .Build();
        optionsBuilder.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));
    }

STEP 2: Create appsettings.json:

  {
    "ConnectionStrings": {       
      "DefaultConnection": "Server=YOURSERVERNAME; Database=YOURDATABASENAME; Trusted_Connection=True; MultipleActiveResultSets=true"        
    } 
  }

STEP 3: Hard copy appsettings.json to the correct directory

  Hard copy appsettings.json.config to the directory specified in the AppDomain.CurrentDomain.BaseDirectory directory. 
  Use your debugger to find out which directory that is.        

Assumption: you have already included package Microsoft.Extensions.Configuration.Json (get it from Nuget) in your project.

Checking on a thread / remove from list

you need to call thread.isAlive()to find out if the thread is still running

Sort a list by multiple attributes?

Several years late to the party but I want to both sort on 2 criteria and use reverse=True. In case someone else wants to know how, you can wrap your criteria (functions) in parenthesis:

s = sorted(my_list, key=lambda i: ( criteria_1(i), criteria_2(i) ), reverse=True)

JavaScript get clipboard data on paste event (Cross browser)

This is an existing code posted above but I have updated it for IE's, the bug was when the existing text is selected and pasted will not delete the selected content. This has been fixed by the below code

selRange.deleteContents(); 

See complete code below

$('[contenteditable]').on('paste', function (e) {
    e.preventDefault();

    if (window.clipboardData) {
        content = window.clipboardData.getData('Text');        
        if (window.getSelection) {
            var selObj = window.getSelection();
            var selRange = selObj.getRangeAt(0);
            selRange.deleteContents();                
            selRange.insertNode(document.createTextNode(content));
        }
    } else if (e.originalEvent.clipboardData) {
        content = (e.originalEvent || e).clipboardData.getData('text/plain');
        document.execCommand('insertText', false, content);
    }        
});

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

That method was added in Servlet 2.5.

So this problem can have at least 3 causes:

  1. The servlet container does not support Servlet 2.5.
  2. The web.xml is not declared conform Servlet 2.5 or newer.
  3. The webapp's runtime classpath is littered with servlet container specific JAR files of a different servlet container make/version which does not support Servlet 2.5.

To solve it,

  1. Make sure that your servlet container supports at least Servlet 2.5. That are at least Tomcat 6, Glassfish 2, JBoss AS 4.1, etcetera. Tomcat 5.5 for example supports at highest Servlet 2.4. If you can't upgrade Tomcat, then you'd need to downgrade Spring to a Servlet 2.4 compatible version.
  2. Make sure that the root declaration of web.xml complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.
  3. Make sure that you don't have any servlet container specific libraries like servlet-api.jar or j2ee.jar in /WEB-INF/lib or even worse, the JRE/lib or JRE/lib/ext. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.

How to POST a JSON object to a JAX-RS service

The answer was surprisingly simple. I had to add a Content-Type header in the POST request with a value of application/json. Without this header Jersey did not know what to do with the request body (in spite of the @Consumes(MediaType.APPLICATION_JSON) annotation)!

Elevating process privilege programmatically?

According to the article Chris Corio: Teach Your Apps To Play Nicely With Windows Vista User Account Control, MSDN Magazine, Jan. 2007, only ShellExecute checks the embedded manifest and prompts the user for elevation if needed, while CreateProcess and other APIs don't. Hope it helps.

See also: same article as .chm.

Return HTML content as a string, given URL. Javascript Function

you need to return when the readystate==4 e.g.

function httpGet(theUrl)
{
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            return xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", theUrl, false );
    xmlhttp.send();    
}

How to register multiple servlets in web.xml in one Spring application

I know this is a bit old but the answer in short would be <load-on-startup> both occurrences have given the same id which is 1 twice. This may confuse loading sequence.

Func vs. Action vs. Predicate

Func - When you want a delegate for a function that may or may not take parameters and returns a value. The most common example would be Select from LINQ:

var result = someCollection.Select( x => new { x.Name, x.Address });

Action - When you want a delegate for a function that may or may not take parameters and does not return a value. I use these often for anonymous event handlers:

button1.Click += (sender, e) => { /* Do Some Work */ }

Predicate - When you want a specialized version of a Func that evaluates a value against a set of criteria and returns a boolean result (true for a match, false otherwise). Again, these are used in LINQ quite frequently for things like Where:

var filteredResults = 
    someCollection.Where(x => x.someCriteriaHolder == someCriteria);

I just double checked and it turns out that LINQ doesn't use Predicates. Not sure why they made that decision...but theoretically it is still a situation where a Predicate would fit.

Is there a concise way to iterate over a stream with indices in Java 8?

I found the solutions here when the Stream is created of list or array (and you know the size). But what if Stream is with unknown size? In this case try this variant:

public class WithIndex<T> {
    private int index;
    private T value;

    WithIndex(int index, T value) {
        this.index = index;
        this.value = value;
    }

    public int index() {
        return index;
    }

    public T value() {
        return value;
    }

    @Override
    public String toString() {
        return value + "(" + index + ")";
    }

    public static <T> Function<T, WithIndex<T>> indexed() {
        return new Function<T, WithIndex<T>>() {
            int index = 0;
            @Override
            public WithIndex<T> apply(T t) {
                return new WithIndex<>(index++, t);
            }
        };
    }
}

Usage:

public static void main(String[] args) {
    Stream<String> stream = Stream.of("a", "b", "c", "d", "e");
    stream.map(WithIndex.indexed()).forEachOrdered(e -> {
        System.out.println(e.index() + " -> " + e.value());
    });
}

return SQL table as JSON in python

After 10 years :) . Without list comprehension

Return a single row of values from a select query like below.

"select name,userid, address from table1 where userid = 1"

json output

{ name : "name1", userid : 1, address : "adress1, street1" }

Code

cur.execute(f"select name,userid, address from table1 where userid = 1 ")
row = cur.fetchone()
desc = list(zip(*cur.description))[0]  #To get column names
rowdict = dict(zip(desc,row))
jsondict = jsonify(rowdict)  #Flask jsonify

cur.description is a tuple of tuples as below. unzip and zip to combine column name with values

(('name', None, None, None, None, None, None), ('userid', None, None, None, None, None, None), ('address', None, None, None, None, None, None))

For homebrew mysql installs, where's my.cnf?

In case of Homebrew, mysql would also look for my.cnf in it's Cellar directory, for example:

/usr/local/Cellar/mysql/5.7.21/my.cnf

For the case one prefers to keep the config close to the binaries - create my.cnf here if it's missing.

Restart mysql after change:

brew services restart mysql

Increment counter with loop

The varStatus references to LoopTagStatus which has a getIndex() method.

So:

<c:forEach var="tableEntity" items='${requestScope.tables}' varStatus="outer">
   <c:forEach var="rowEntity" items='${tableEntity.rows}' varStatus="inner">            
        <c:out value="${(outer.index * fn:length(tableEntity.rows)) + inner.index}" />
    </c:forEach>
</c:forEach>

See also:

Open window in JavaScript with HTML inserted

You can open a new popup window by following code:

var myWindow = window.open("", "newWindow", "width=500,height=700");
//window.open('url','name','specs');

Afterwards, you can add HTML using both myWindow.document.write(); or myWindow.document.body.innerHTML = "HTML";

What I will recommend is that first you create a new html file with any name. In this example I am using

newFile.html

And make sure to add all content in that file such as bootstrap cdn or jquery, means all the links and scripts. Then make a div with some id or use your body and give that a id. in this example I have given id="mainBody" to my newFile.html <body> tag

<body id="mainBody">

Then open this file using

<script>    
var myWindow = window.open("newFile.html", "newWindow", "width=500,height=700");
</script>

And add whatever you want to add in your body tag. using following code

<script>    
 var myWindow = window.open("newFile.html","newWindow","width=500,height=700");  

   myWindow.onload = function(){
     let content = "<button class='btn btn-primary' onclick='window.print();'>Confirm</button>";
   myWindow.document.getElementById('mainBody').innerHTML = content;
    } 

myWindow.window.close();
 </script>

it is as simple as that.

jwt check if token expired

Sadly @Andrés Montoya answer has a flaw which is related to how he compares the obj. I found a solution here which should solve this:

const now = Date.now().valueOf() / 1000

if (typeof decoded.exp !== 'undefined' && decoded.exp < now) {
    throw new Error(`token expired: ${JSON.stringify(decoded)}`)
}
if (typeof decoded.nbf !== 'undefined' && decoded.nbf > now) {
    throw new Error(`token expired: ${JSON.stringify(decoded)}`)
}

Thanks to thejohnfreeman!

How to get the cell value by column name not by index in GridView in asp.net

You can use the DataRowView to get the column index.

    void OnRequestsGridRowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            var data = e.Row.DataItem as DataRowView;

            // replace request name with a link
            if (data.DataView.Table.Columns["Request Name"] != null)
            {
                // get the request name
                string title = data["Request Name"].ToString();
                // get the column index
                int idx = data.Row.Table.Columns["Request Name"].Ordinal;

                // ...

                e.Row.Cells[idx].Controls.Clear();
                e.Row.Cells[idx].Controls.Add(link);
            }
        }
    }

How to increase memory limit for PHP over 2GB?

For unlimited memory limit set -1 in memory_limit variable:

ini_set('memory_limit', '-1');

GCC dump preprocessor defines

Yes, use -E -dM options instead of -c. Example (outputs them to stdout):

 gcc -dM -E - < /dev/null

For C++

 g++ -dM -E -x c++ - < /dev/null

From the gcc manual:

Instead of the normal output, generate a list of `#define' directives for all the macros defined during the execution of the preprocessor, including predefined macros. This gives you a way of finding out what is predefined in your version of the preprocessor. Assuming you have no file foo.h, the command

touch foo.h; cpp -dM foo.h

will show all the predefined macros.

If you use -dM without the -E option, -dM is interpreted as a synonym for -fdump-rtl-mach.

How do you update a DateTime field in T-SQL?

Is there maybe a trigger on the table setting it back?

Strip HTML from Text JavaScript

simple 2 line jquery to strip the html.

 var content = "<p>checking the html source&nbsp;</p><p>&nbsp;
  </p><p>with&nbsp;</p><p>all</p><p>the html&nbsp;</p><p>content</p>";

 var text = $(content).text();//It gets you the plain text
 console.log(text);//check the data in your console

 cj("#text_area_id").val(text);//set your content to text area using text_area_id

How to check whether a Button is clicked by using JavaScript

Just hook up the onclick event:

<input id="button" type="submit" name="button" value="enter" onclick="myFunction();"/>

How do I configure IIS for URL Rewriting an AngularJS application in HTML5 mode?

The issue with only having these two conditions:

  <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
  <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />

is that they work only as long as the {REQUEST_FILENAME} exists physically on disk. This means that there can be scenarios where a request for an incorrectly named partial view would return the root page instead of a 404 which would cause angular to be loaded twice (and in certain scenarios it can cause a nasty infinite loop).

Thus, some safe "fallback" rules would be recommended to avoid these hard to troubleshoot issues:

  <add input="{REQUEST_FILENAME}" pattern="(.*?)\.html$" negate="true" />
  <add input="{REQUEST_FILENAME}" pattern="(.*?)\.js$" negate="true" />
  <add input="{REQUEST_FILENAME}" pattern="(.*?)\.css$" negate="true" />

or a condition that matches any file ending:

<conditions>
  <!-- ... -->
  <add input="{REQUEST_FILENAME}" pattern=".*\.[\d\w]+$" negate="true" />
</conditions>

Splitting a Java String by the pipe symbol using split("|")

test.split("\\|",999);

Specifing a limit or max will be accurate for examples like: "boo|||a" or "||boo|" or " |||"

But test.split("\\|"); will return different length strings arrays for the same examples.

use reference: link

Byte Array to Hex String

Consider the hex() method of the bytes type on Python 3.5 and up:

>>> array_alpha = [ 133, 53, 234, 241 ]
>>> print(bytes(array_alpha).hex())
8535eaf1

EDIT: it's also much faster than hexlify (modified @falsetru's benchmarks above)

from timeit import timeit
N = 10000
print("bytearray + hexlify ->", timeit(
    'binascii.hexlify(data).decode("ascii")',
    setup='import binascii; data = bytearray(range(255))',
    number=N,
))
print("byte + hex          ->", timeit(
    'data.hex()',
    setup='data = bytes(range(255))',
    number=N,
))

Result:

bytearray + hexlify -> 0.011218150997592602
byte + hex          -> 0.005952142993919551

PHP - print all properties of an object

As no one has not provided an OO approach yet here is like it would be done.

class Person {
    public $name = 'Alex Super Tramp';

    public $age = 100;

    private $property = 'property';
}


$r = new ReflectionClass(new Person);
print_r($r->getProperties());

//Outputs
Array
(
    [0] => ReflectionProperty Object
        (
            [name] => name
            [class] => Person
        )

    [1] => ReflectionProperty Object
        (
            [name] => age
            [class] => Person
        )

    [2] => ReflectionProperty Object
        (
            [name] => property
            [class] => Person
        )

)

The advantage when using reflection is that you can filter by visibility of property, like this:

print_r($r->getProperties(ReflectionProperty::IS_PRIVATE));

Since Person::$property is private it's returned when filtering by IS_PRIVATE:

//Outputs
Array
(
    [0] => ReflectionProperty Object
        (
            [name] => property
            [class] => Person
        )

)

Read the docs!

How to hide a column (GridView) but still access its value?

You can do it programmatically:

grid0.Columns[0].Visible = true;
grid0.DataSource = dt;
grid0.DataBind();
grid0.Columns[0].Visible = false;

In this way you set the column to visible before databinding, so the column is generated. The you set the column to not visible, so it is not displayed.

Vue equivalent of setTimeout?

Arrow Function

The best and simplest way to solve this problem is by using an arrow function () => {}:

    addToBasket() {
        var item = this.photo;
        this.$http.post('/api/buy/addToBasket', item);
        this.basketAddSuccess = true;
        // now 'this' is referencing the Vue object and not the 'setTimeout' scope
        setTimeout(() => this.basketAddSuccess = false, 2000);
    }

This works because the this of arrow functions is bound to the this of its enclosing scope- in Vue, that's the parent/ enclosing component. Inside a traditional function called by setTimeout, however, this refers to the window object (which is why you ran into errors when you tried to access this.basketAddSuccess in that context).

Argument Passing

Another way of doing this would be passing this as an arg to your function through setTimeout's prototype using its setTimeout(callback, delay, arg1, arg2, ...) form:

    addToBasket() {
        item = this.photo;
        this.$http.post('/api/buy/addToBasket', item);
        this.basketAddSuccess = true;
        //Add scope argument to func, pass this after delay in setTimeout
        setTimeout(function(scope) {
             scope.basketAddSuccess = false;
        }, 2000, this);
    }

(It's worth noting that the arg passing syntax is incompatible with IE 9 and below, however.)

iPhone - Grand Central Dispatch main thread

Dispatching blocks to the main queue from the main thread can be useful. It gives the main queue a chance to handle other blocks that have been queued so that you're not simply blocking everything else from executing.

For example you could write an essentially single threaded server that nonetheless handles many concurrent connections. As long as no individual block in the queue takes too long the server stays responsive to new requests.

If your program does nothing but spend its whole life responding to events then this can be quite natural. You just set up your event handlers to run on the main queue and then call dispatch_main(), and you may not need to worry about thread safety at all.

How should I print types like off_t and size_t?

Looking at man 3 printf on Linux, OS X, and OpenBSD all show support for %z for size_t and %t for ptrdiff_t (for C99), but none of those mention off_t. Suggestions in the wild usually offer up the %u conversion for off_t, which is "correct enough" as far as I can tell (both unsigned int and off_t vary identically between 64-bit and 32-bit systems).

Difference between \n and \r?

Two different characters for different Operating Systems. Also this plays a role in data transmitted over TCP/IP which requires the use of \r\n.

\n Unix

\r Mac

\r\n Windows and DOS.

Writing a dictionary to a text file?

exDict = {1:1, 2:2, 3:3}
with open('file.txt', 'w+') as file:
    file.write(str(exDict))

Custom date format with jQuery validation plugin

nickf's answer is good, but note that the validation plug-in already includes validators for several other date formats, in the additional-methods.js file. Before you write your own, make sure that someone hasn't already done it.

Check if all values in list are greater than a certain number

Use the all() function with a generator expression:

>>> my_list1 = [30, 34, 56]
>>> my_list2 = [29, 500, 43]
>>> all(i >= 30 for i in my_list1)
True
>>> all(i >= 30 for i in my_list2)
False

Note that this tests for greater than or equal to 30, otherwise my_list1 would not pass the test either.

If you wanted to do this in a function, you'd use:

def all_30_or_up(ls):
    for i in ls:
        if i < 30:
            return False
    return True

e.g. as soon as you find a value that proves that there is a value below 30, you return False, and return True if you found no evidence to the contrary.

Similarly, you can use the any() function to test if at least 1 value matches the condition.

MySQL - Replace Character in Columns

Replace below characters

~ ! @ # $ % ^ & * ( ) _ +
` - = 
{ } |
[ ] \
: " 
; '

< > ?
, . 

with this SQL

SELECT note as note_original, 

    REPLACE(
        REPLACE(
            REPLACE(
                REPLACE(
                    REPLACE(
                        REPLACE(
                            REPLACE(
                                REPLACE(
                                    REPLACE(
                                        REPLACE(
                                            REPLACE(
                                                REPLACE(
                                                    REPLACE(
                                                        REPLACE(
                                                            REPLACE(
                                                                REPLACE(
                                                                    REPLACE(
                                                                        REPLACE(
                                                                            REPLACE(
                                                                                REPLACE(
                                                                                    REPLACE(
                                                                                        REPLACE(
                                                                                            REPLACE(
                                                                                                REPLACE(
                                                                                                    REPLACE(
                                                                                                        REPLACE(
                                                                    REPLACE(
                                                                        REPLACE(
                                                                            REPLACE(
                                                                                REPLACE(
                                                                                    REPLACE(
                                                                                        REPLACE(
                                                                                            REPLACE(note, '\"', ''),
                                                                                        '.', ''),
                                                                                    '?', ''),
                                                                                '`', ''),
                                                                            '<', ''),
                                                                        '=', ''),
                                                                    '{', ''),
                                                                                                        '}', ''),
                                                                                                    '[', ''),
                                                                                                ']', ''),
                                                                                            '|', ''),
                                                                                        '\'', ''),
                                                                                    ':', ''),
                                                                                ';', ''),
                                                                            '~', ''),
                                                                        '!', ''),
                                                                    '@', ''),
                                                                '#', ''),
                                                            '$', ''),
                                                        '%', ''),
                                                    '^', ''),
                                                '&', ''),
                                            '*', ''),
                                        '_', ''),
                                    '+', ''),
                                ',', ''),
                            '/', ''),
                        '(', ''),
                    ')', ''),
                '-', ''),
            '>', ''),
        ' ', '-'),
    '--', '-') as note_changed FROM invheader

How to copy a huge table data into another table in SQL Server

If it's a 1 time import, the Import/Export utility in SSMS will probably work the easiest and fastest. SSIS also seems to work better for importing large data sets than a straight INSERT.

BULK INSERT or BCP can also be used to import large record sets.

Another option would be to temporarily remove all indexes and constraints on the table you're importing into and add them back once the import process completes. A straight INSERT that previously failed might work in those cases.

If you're dealing with timeouts or locking/blocking issues when going directly from one database to another, you might consider going from one db into TEMPDB and then going from TEMPDB into the other database as it minimizes the effects of locking and blocking processes on either side. TempDB won't block or lock the source and it won't hold up the destination.

Those are a few options to try.

-Eric Isaacs

What is the shortest function for reading a cookie by name in JavaScript?

To truly remove as much bloat as possible, consider not using a wrapper function at all:

try {
    var myCookie = document.cookie.match('(^|;) *myCookie=([^;]*)')[2]
} catch (_) {
    // handle missing cookie
}

As long as you're familiar with RegEx, that code is reasonably clean and easy to read.

How to Empty Caches and Clean All Targets Xcode 4 and later

I have been pulling out hair from my head because I thought that I had the same problem. When building the app I didn't get the same result on my iPhone as on the simulator.

The problem was that I had somehow made a localized version of the MainStoryboard.storyboard file. So when I ran the app on my phone it showed the danish version... and the simulator showed the english version.

Yeah I'm new! :)

Password masking console application

This masks the password with a red square, then reverts back to the original colours once the password has been entered.

It doesn't stop the user from using copy/paste to get the password, but if it's more just about stopping someone looking over your shoulder, this is a good quick solution.

Console.Write("Password ");
ConsoleColor origBG = Console.BackgroundColor; // Store original values
ConsoleColor origFG = Console.ForegroundColor;

Console.BackgroundColor = ConsoleColor.Red; // Set the block colour (could be anything)
Console.ForegroundColor = ConsoleColor.Red;

string Password = Console.ReadLine(); // read the password

Console.BackgroundColor= origBG; // revert back to original
Console.ForegroundColor= origFG;

How to detect if a stored procedure already exists

From SQL Server 2016 CTP3 you can use new DIE statements instead of big IF wrappers

Syntax:

DROP { PROC | PROCEDURE } [ IF EXISTS ] { [ schema_name. ] procedure } [ ,...n ]

Query:

DROP PROCEDURE IF EXISTS usp_name

More info here

Should I use .done() and .fail() for new jQuery AJAX code instead of success and error

In simple words

$.ajax("info.txt").done(function(data) {
  alert(data);
}).fail(function(data){
  alert("Try again champ!");
});

if its get the info.text then it will alert and whatever function you add or if any how unable to retrieve info.text from the server then alert or error function.

Checking for a null object in C++

You can use a special designated object as the null object in case of references as follows:

class SomeClass
{
    public:

        int operator==(SomeClass &object)
        {
            if(this == &object) 
            {
                    return true;
            }

            return false;
        }


    static SomeClass NullObject;
};

SomeClass SomeClass::NullObject;

void print(SomeClass &val)
{
    if(val == SomeClass::NullObject)
    {
        printf("\nNULL");
    }
    else
    {
        printf("\nNOT NULL");
    }
}

Can I get a patch-compatible output from git-diff?

A useful trick to avoid creating temporary patch files:

git diff | patch -p1 -d [dst-dir]

Error 1920 service failed to start. Verify that you have sufficient privileges to start system services

In my case I had to delete the services in my installshield project and start from square one. My original service components were added manually and I couldn't get them working, the only error I was getting was the same "Error 1920 service failed to start. Verify that you have sufficient privileges to start system services." that you were getting. After deleting my components, I re-added them using the component wizard.
enter image description here

Component Wizard looks like this

I actually had to create two new components. One was of type "Install Service".

Service Component type shown here

enter image description here

The other component I had to add was of "Control Service" type.

enter image description here

I had to choose the service that I had setup when I added the Install Service component.enter image description here

After that it worked, even though nothing looked differently from the components I had added manually. Installshield must do something behind the scenes when it wires up the service components with the component wizard.

All of this was with Install Shield 2016.

Linking to an external URL in Javadoc?

Javadocs don't offer any special tools for external links, so you should just use standard html:

See <a href="http://groversmill.com/">Grover's Mill</a> for a history of the
Martian invasion.

or

@see <a href="http://groversmill.com/">Grover's Mill</a> for a history of 
the Martian invasion.

Don't use {@link ...} or {@linkplain ...} because these are for links to the javadocs of other classes and methods.

Android Activity without ActionBar

Default style you getting in res/value/style.xml like

  <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
  </style>

And just the below like in your activity tag,

android:theme="@style/AppTheme.NoActionBar"

Where to get "UTF-8" string literal in Java?

This constant is available (among others as: UTF-16, US-ASCII, etc.) in the class org.apache.commons.codec.CharEncoding as well.

Can we call the function written in one JavaScript in another JS file?

The function could be called as if it was in the same JS File as long as the file containing the definition of the function has been loaded before the first use of the function.

I.e.

File1.js

function alertNumber(number) {
    alert(number);
}

File2.js

function alertOne() {
     alertNumber("one");
}

HTML

<head>
....
    <script src="File1.js" type="text/javascript"></script> 
    <script src="File2.js" type="text/javascript"></script> 
....
</head>
<body>
....
    <script type="text/javascript">
       alertOne();
    </script>
....
</body>

The other way won't work. As correctly pointed out by Stuart Wakefield. The other way will also work.

HTML

<head>
....
    <script src="File2.js" type="text/javascript"></script> 
    <script src="File1.js" type="text/javascript"></script> 
....
</head>
<body>
....
    <script type="text/javascript">
       alertOne();
    </script>
....
</body>

What will not work would be:

HTML

<head>
....
    <script src="File2.js" type="text/javascript"></script> 
    <script type="text/javascript">
       alertOne();
    </script>
    <script src="File1.js" type="text/javascript"></script> 
....
</head>
<body>
....
</body>

Although alertOne is defined when calling it, internally it uses a function that is still not defined (alertNumber).

Git: force user and password prompt

Since the question was labeled with Github, adding another remote like https_origin and add the https connection can force you always to enter the password:

git remote add https_origin https://github.com/.../...

How to create an HTTPS server in Node.js?

You can use also archive this with the Fastify framework:

const { readFileSync } = require('fs')
const Fastify = require('fastify')

const fastify = Fastify({
  https: {
    key: readFileSync('./test/asset/server.key'),
    cert: readFileSync('./test/asset/server.cert')
  },
  logger: { level: 'debug' }
})

fastify.listen(8080)

(and run openssl req -nodes -new -x509 -keyout server.key -out server.cert to create the files if you need to write tests)

Git add and commit in one command

This works for me always please run following commands:

1.git add .
2.git commit -m "no bugs please"
3.git push origin *

where * is based off the branch you are pushing to, and also commit messages can always be changed to suit the context.

Making a drop down list using swift?

Using UIPickerview is the right way to go to implement it according to Apple's Human Interface Guidelines

If you select drop down in mobile safari it will show UIPickerview to let the use choose drop down items.

Alternatively

you can use UIPopoverController till iOS 9 as its deprecated but its better to stick with UIModalPresentationPopover of view you want o show as well

you can use UIActionsheet to show the items but it's better to use UIAlertViewController and choose UIActionSheetstyle to show as the former is deprecated in latest versions

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

Create an Android GPS tracking application

The source code for the Android mobile application open-gpstracker which you appreciated is available here.

You can checkout the code using SVN client application or via Git:

Debugging the source code will surely help you.

What does "implements" do on a class?

An interface defines a simple contract of methods all implementing classes must implement. When a class implements an interface, it must provide implementations for all its methods.

I guess the poster assumes a certain level of knowledge about the language.

Is there a way to compile node.js source files?

There was an answer here: Secure distribution of NodeJS applications. Raynos said: V8 allows you to pre-compile JavaScript.

Label on the left side instead above an input field

You can create such form where label and form control are side using two method -

1. Inline form layout

<form class="form-inline" role="form">
    <div class="form-group">
        <label for="inputEmail">Email</label>
        <input type="email" class="form-control" id="inputEmail" placeholder="Email">
    </div>
    <div class="form-group">
        <label for="inputPassword">Password</label>
        <input type="password" class="form-control" id="inputPassword" placeholder="Password">
    </div>
    <button type="reset" class="btn btn-default">Reset</button>
    <button type="submit" class="btn btn-primary">Login</button>
</form>

2. Horizontal Form Layout

<form class="form-horizontal">
    <div class="row">
        <div class="col-sm-4">
            <div class="form-group">
                <label for="inputEmail" class="control-label col-xs-3">Email</label>
                <div class="col-xs-9">
                    <input type="email" class="form-control" id="inputEmail" placeholder="Email">
                </div>
            </div>
        </div>
        <div class="col-sm-5">
            <div class="form-group">
                <label for="inputPassword" class="control-label col-xs-3">Password</label>
                <div class="col-xs-9">
                    <input type="password" class="form-control" id="inputPassword" placeholder="Password">
                </div>
            </div>
        </div>
        <div class="col-sm-3">
            <button type="reset" class="btn btn-default">Reset</button>
            <button type="submit" class="btn btn-primary">Login</button>
        </div>
    </div>
</form>

You can check out this page for more information and live demo - http://www.tutorialrepublic.com/twitter-bootstrap-tutorial/bootstrap-forms.php

Why is it faster to check if dictionary contains the key, rather than catch the exception in case it doesn't?

On the one hand, throwing exceptions is inherently expensive, because the stack has to be unwound etc.
On the other hand, accessing a value in a dictionary by its key is cheap, because it's a fast, O(1) operation.

BTW: The correct way to do this is to use TryGetValue

obj item;
if(!dict.TryGetValue(name, out item))
    return null;
return item;

This accesses the dictionary only once instead of twice.
If you really want to just return null if the key doesn't exist, the above code can be simplified further:

obj item;
dict.TryGetValue(name, out item);
return item;

This works, because TryGetValue sets item to null if no key with name exists.

How do I convert an array object to a string in PowerShell?

I found that piping the array to the Out-String cmdlet works well too.

For example:

PS C:\> $a  | out-string

This
Is
a
cat

It depends on your end goal as to which method is the best to use.

How to get first/top row of the table in Sqlite via Sql Query

LIMIT 1 is what you want. Just keep in mind this returns the first record in the result set regardless of order (unless you specify an order clause in an outer query).

How to increase executionTimeout for a long-running query?

You can set executionTimeout in web.config to support the longer execution time.

executionTimeout specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET. MSDN

<httpRuntime  executionTimeout = "300" />

This make execution timeout to five minutes.

Optional Int32 attribute.

Specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET.

This time-out applies only if the debug attribute in the compilation element is False. Therefore, if the debug attribute is True, you do not have to set this attribute to a large value in order to avoid application shutdown while you are debugging. The default is 110 seconds, Reference.

How to add new contacts in android

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

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

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

Intent contactIntent = new Intent(ContactsContract.Intents.Insert.ACTION);
contactIntent.setType(ContactsContract.RawContacts.CONTENT_TYPE);

contactIntent
        .putExtra(ContactsContract.Intents.Insert.NAME, "Contact Name")
        .putExtra(ContactsContract.Intents.Insert.PHONE, "5555555555");

startActivityForResult(contactIntent, 1);

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

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

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

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

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    if (requestCode == 1)
    {
        if (resultCode == Activity.RESULT_OK) {
            Toast.makeText(this, "Added Contact", Toast.LENGTH_SHORT).show();
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            Toast.makeText(this, "Cancelled Added Contact", Toast.LENGTH_SHORT).show();
        }
    }
}

Dynamically add event listener

Here's my workaround:

I created a library with Angular 6. I added a common component commonlib-header which is used like this in an external application.

Note the serviceReference which is the class (injected in the component constructor(public serviceReference: MyService) that uses the commonlib-header) that holds the stringFunctionName method:

<commonlib-header
    [logo]="{ src: 'assets/img/logo.svg', alt: 'Logo', href: '#' }"
    [buttons]="[{ index: 0, innerHtml: 'Button', class: 'btn btn-primary', onClick: [serviceReference, 'stringFunctionName', ['arg1','arg2','arg3']] }]">
    </common-header>

The library component is programmed like this. The dynamic event is added in the onClick(fn: any) method:

export class HeaderComponent implements OnInit {

 _buttons: Array<NavItem> = []

 @Input()
  set buttons(buttons: Array<any>) {
    buttons.forEach(navItem => {
      let _navItem = new NavItem(navItem.href, navItem.innerHtml)

      _navItem.class = navItem.class

      _navItem.onClick = navItem.onClick // this is the array from the component @Input properties above

      this._buttons[navItem.index] = _navItem
    })
  }

  constructor() {}

  ngOnInit() {}

  onClick(fn: any){
    let ref = fn[0]
    let fnName = fn[1]
    let args = fn[2]

    ref[fnName].apply(ref, args)
  }

The reusable header.component.html:

<div class="topbar-right">
  <button *ngFor="let btn of _buttons"
    class="{{ btn.class }}"
    (click)="onClick(btn.onClick)"
    [innerHTML]="btn.innerHtml | keepHtml"></button>
</div>

Obtain form input fields using jQuery?

$("#form-id").submit(function (e) { 
  e.preventDefault();
  inputs={};
  input_serialized =  $(this).serializeArray();
  input_serialized.forEach(field => {
    inputs[field.name] = field.value;
  })
  console.log(inputs)
});

Page redirect with successful Ajax request

// Create lag time before redirecting 
setTimeout(function() {
  window.location.href = "thankyou.php";
}, 2000);

$errors=null; 

if ( ($name == "Name") ) {
    $errors = $nameError; // no name entered
}
if ( ($email == "E-mail address") ) {
    $errors .= $emailError; // no email address entered
}
if ( !(preg_match($match,$email)) ) {
    $errors .= $invalidEmailError; // checks validity of email
}
if ( $spam != "10" ) {
    $errors .= $spamError; // spam error
}

if ( !($errors) ) {
    mail ($to, $subject, $message, $headers);
    echo "Your message was successfully sent!";
    //instead of echoing this message, I want a page redirect to thankyou.html
    // redirect
    setTimeout();
} else {
    echo "<p id='errors'>";
    echo $errors;
    echo "</p>";
}

How is Pythons glob.glob ordered?

At least in Python3 you also can do this:

import os, re, glob

path = '/home/my/path'
files = glob.glob(os.path.join(path, '*.png'))
files.sort(key=lambda x:[int(c) if c.isdigit() else c for c in re.split(r'(\d+)', x)])
for infile in files:
    print(infile)

This should lexicographically order your input array of strings (e.g. respect numbers in strings while ordering).

HTML 5 video or audio playlist

You should take a look at Popcorn.js - a javascript framework for interacting with Html5 : http://popcornjs.org/documentation

How to find Oracle Service Name

Connect to the server as "system" using SID. Execute this query:

select value from v$parameter where name like '%service_name%';

It worked for me.

Showing an image from console in Python

Why not just display it in the user's web browser?

How to create a QR code reader in a HTML5 website?

The jsqrcode library by Lazarsoft is now working perfectly using just HTML5, i.e. getUserMedia (WebRTC). You can find it on GitHub.

I also found a great fork which is much simplified. Just one file (plus jQuery) and one call of a method: see html5-qrcode on GitHub.

When should I use a table variable vs temporary table in sql server?

I totally agree with Abacus (sorry - don't have enough points to comment).

Also, keep in mind it doesn't necessarily come down to how many records you have, but the size of your records.

For instance, have you considered the performance difference between 1,000 records with 50 columns each vs 100,000 records with only 5 columns each?

Lastly, maybe you're querying/storing more data than you need? Here's a good read on SQL optimization strategies. Limit the amount of data you're pulling, especially if you're not using it all (some SQL programmers do get lazy and just select everything even though they only use a tiny subset). Don't forget the SQL query analyzer may also become your best friend.

How do I get a UTC Timestamp in JavaScript?

EDIT: The code below does NOT work. I was always assuming that new Date().getTime() returned the number of seconds since the 1st of January 1970 IN THE CURRENT TIMEZONE. This is not the case: getTime() returns the number of seconds in UTC. So, the code below does gross over-adjusting. Thank you everybody!]

First of all, thank you for your fantastic insights. I guess my question had the wrong title... it should have been "Get the UTC Unix Timestamp for an existing date".

So, if I have a date object:

var d = new Date(2009,01,31)

I was after a function that would tell me "The UTC Unix Timestamp".

This function seems to be the real trick:

Date.prototype.getUTCUnixTime =  function (){
  return Math.floor( new Date(
    this.getUTCFullYear(),
    this.getUTCMonth(),
    this.getUTCDate(),
    this.getUTCHours(),
    this.getUTCMinutes(), 
    this.getUTCSeconds()
  ).getTime() / 1000); 
}

Note that it works on "this" This means that I can do:

var n = new Date(2008,10,10)
...
...

n.getUTCUnixTime();

And get the number of seconds since the 1st of Jan 1970 in Unix time. Right?

It's a little insane, to me, that Javascript stores everything in UTC times, but then in order to get that number I have to create a new Date object passing the individual UTC getters and then finally call getTime() for that...

Merc.

How to check a string for specific characters?

Quick comparison of timings in response to the post by Abbafei:

import timeit

def func1():
    phrase = 'Lucky Dog'
    return any(i in 'LD' for i in phrase)

def func2():
    phrase = 'Lucky Dog'
    if ('L' in phrase) or ('D' in phrase):
        return True
    else:
        return False

if __name__ == '__main__': 
    func1_time = timeit.timeit(func1, number=100000)
    func2_time = timeit.timeit(func2, number=100000)
    print('Func1 Time: {0}\nFunc2 Time: {1}'.format(func1_time, func2_time))

Output:

Func1 Time: 0.0737484362111
Func2 Time: 0.0125144964371

So the code is more compact with any, but faster with the conditional.


EDIT : TL;DR -- For long strings, if-then is still much faster than any!

I decided to compare the timing for a long random string based on some of the valid points raised in the comments:

# Tested in Python 2.7.14

import timeit
from string import ascii_letters
from random import choice

def create_random_string(length=1000):
    random_list = [choice(ascii_letters) for x in range(length)]
    return ''.join(random_list)

def function_using_any(phrase):
    return any(i in 'LD' for i in phrase)

def function_using_if_then(phrase):
    if ('L' in phrase) or ('D' in phrase):
        return True
    else:
        return False

if __name__ == '__main__':
    random_string = create_random_string(length=2000)
    func1_time = timeit.timeit(stmt="function_using_any(random_string)",
                               setup="from __main__ import function_using_any, random_string",
                               number=200000)
    func2_time = timeit.timeit(stmt="function_using_if_then(random_string)",
                               setup="from __main__ import function_using_if_then, random_string",
                               number=200000)
    print('Time for function using any: {0}\nTime for function using if-then: {1}'.format(func1_time, func2_time))

Output:

Time for function using any: 0.1342546
Time for function using if-then: 0.0201827

If-then is almost an order of magnitude faster than any!

VBA Macro On Timer style to run code every set number of seconds, i.e. 120 seconds

Yes, you can use Application.OnTime for this and then put it in a loop. It's sort of like an alarm clock where you keep hittig the snooze button for when you want it to ring again. The following updates Cell A1 every three seconds with the time.

Dim TimerActive As Boolean
Sub StartTimer()
    Start_Timer
End Sub

Private Sub Start_Timer()
    TimerActive = True
    Application.OnTime Now() + TimeValue("00:00:03"), "Timer"
End Sub

Private Sub Stop_Timer()
    TimerActive = False
End Sub

Private Sub Timer()
    If TimerActive Then
        ActiveSheet.Cells(1, 1).Value = Time
        Application.OnTime Now() + TimeValue("00:00:03"), "Timer"
    End If
End Sub

You can put the StartTimer procedure in your Auto_Open event and change what is done in the Timer proceedure (right now it is just updating the time in A1 with ActiveSheet.Cells(1, 1).Value = Time).

Note: you'll want the code (besides StartTimer) in a module, not a worksheet module. If you have it in a worksheet module, the code requires slight modification.

' << ' operator in verilog

1 << ADDR_WIDTH means 1 will be shifted 8 bits to the left and will be assigned as the value for RAM_DEPTH.

In addition, 1 << ADDR_WIDTH also means 2^ADDR_WIDTH.

Given ADDR_WIDTH = 8, then 2^8 = 256 and that will be the value for RAM_DEPTH

Bootstrap 3: Offset isn't working?

Which version of bootstrap are you using? The early versions of Bootstrap 3 (3.0, 3.0.1) didn't work with this functionality.

col-md-offset-0 should be working as seen in this bootstrap example found here (http://getbootstrap.com/css/#grid-responsive-resets):

<div class="row">
   <div class="col-sm-5 col-md-6">.col-sm-5 .col-md-6</div>
   <div class="col-sm-5 col-sm-offset-2 col-md-6 col-md-offset-0">.col-sm-5 .col-sm-offset-2 .col-md-6 .col-md-offset-0</div>
</div>