Programs & Examples On #Unaccent

Extension exists but uuid_generate_v4 fails

#1 Re-install uuid-ossp extention in an exact schema:

SET search_path TO public;
DROP EXTENSION IF EXISTS "uuid-ossp";

CREATE EXTENSION "uuid-ossp" SCHEMA public;

If this is a fresh installation you can skip SET and DROP. Credits to @atomCode (details)

After this, you should see uuid_generate_v4() function IN THE RIGHT SCHEMA (when execute \df query in psql command-line prompt).

#2 Use fully-qualified names (with schemaname. qualifier):

CREATE TABLE public.my_table (
    id uuid DEFAULT public.uuid_generate_v4() NOT NULL,

How to hide elements without having them take space on the page?

Try setting display:none to hide and set display:block to show.

Spring data jpa- No bean named 'entityManagerFactory' is defined; Injection of autowired dependencies failed

Had this issue when migrated spring boot 1.5.2 to 2.0.4. Instead of creating bean I've used @EnableAutoConfiguration in the main class and it solved my problem.

Call a stored procedure with another in Oracle

@Michael Lockwood - you don't need to use the keyword "CALL" anywhere. You just need to mention the procedure call directly.

That is

Begin
   proc1(input1, input2);
end;
/

instead of

Begin
   call proc1(input1, input2);
end;
/

What does '&' do in a C++ declaration?

One way to look at the & (reference) operator in c++ is that is merely a syntactic sugar to a pointer. For example, the following are roughly equivalent:

void foo(int &x)
{
    x = x + 1;
}

void foo(int *x)
{
    *x = *x + 1;
}

The more useful is when you're dealing with a class, so that your methods turn from x->bar() to x.bar().

The reason I said roughly is that using references imposes additional compile-time restrictions on what you can do with the reference, in order to protect you from some of the problems caused when dealing with pointers. For instance, you can't accidentally change the pointer, or use the pointer in any way other than to reference the singular object you've been passed.

How to increase MySQL connections(max_connections)?

If you need to increase MySQL Connections without MySQL restart do like below

mysql> show variables like 'max_connections';
+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| max_connections | 100   |
+-----------------+-------+
1 row in set (0.00 sec)

mysql> SET GLOBAL max_connections = 150;
Query OK, 0 rows affected (0.00 sec)

mysql> show variables like 'max_connections';
+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| max_connections | 150   |
+-----------------+-------+
1 row in set (0.00 sec)

These settings will change at MySQL Restart.


For permanent changes add below line in my.cnf and restart MySQL

max_connections = 150

How to convert a const char * to std::string

This page on string::string gives two potential constructors that would do what you want:

string ( const char * s, size_t n );
string ( const string& str, size_t pos, size_t n = npos );

Example:

#include<cstdlib>
#include<cstring>
#include<string>
#include<iostream>
using namespace std;

int main(){

    char* p= (char*)calloc(30, sizeof(char));
    strcpy(p, "Hello world");

    string s(p, 15);
    cout << s.size() << ":[" << s << "]" << endl;
    string t(p, 0, 15);
    cout << t.size() << ":[" << t << "]" << endl;

    free(p);
    return 0;
}

Output:

15:[Hello world]
11:[Hello world]

The first form considers p to be a simple array, and so will create (in our case) a string of length 15, which however prints as a 11-character null-terminated string with cout << .... Probably not what you're looking for.

The second form will implicitly convert the char* to a string, and then keep the maximum between its length and the n you specify. I think this is the simplest solution, in terms of what you have to write.

Is there any difference between GROUP BY and DISTINCT

GROUP BY lets you use aggregate functions, like AVG, MAX, MIN, SUM, and COUNT. On the other hand DISTINCT just removes duplicates.

For example, if you have a bunch of purchase records, and you want to know how much was spent by each department, you might do something like:

SELECT department, SUM(amount) FROM purchases GROUP BY department

This will give you one row per department, containing the department name and the sum of all of the amount values in all rows for that department.

Replace line break characters with <br /> in ASP.NET MVC Razor view

Applying the DRY principle to Omar's solution, here's an HTML Helper extension:

using System.Web.Mvc;
using System.Text.RegularExpressions;

namespace System.Web.Mvc.Html {
    public static class MyHtmlHelpers {
        public static MvcHtmlString EncodedReplace(this HtmlHelper helper, string input, string pattern, string replacement) {
            return new MvcHtmlString(Regex.Replace(helper.Encode(input), pattern, replacement));
        }
    }
}

Usage (with improved regex):

@Html.EncodedReplace(Model.CommentText, "[\n\r]+", "<br />")

This also has the added benefit of putting less onus on the Razor View developer to ensure security from XSS vulnerabilities.


My concern with Jacob's solution is that rendering the line breaks with CSS breaks the HTML semantics.

Effectively use async/await with ASP.NET Web API

It is correct, but perhaps not useful.

As there is nothing to wait on – no calls to blocking APIs which could operate asynchronously – then you are setting up structures to track asynchronous operation (which has overhead) but then not making use of that capability.

For example, if the service layer was performing DB operations with Entity Framework which supports asynchronous calls:

public Task<BackOfficeResponse<List<Country>>> ReturnAllCountries()
{
    using (db = myDBContext.Get()) {
      var list = await db.Countries.Where(condition).ToListAsync();

       return list;
    }
}

You would allow the worker thread to do something else while the db was queried (and thus able to process another request).

Await tends to be something that needs to go all the way down: it is very hard to retro-fit into an existing system.

Cannot kill Python script with Ctrl-C

I think it's best to call join() on your threads when you expect them to die. I've taken some liberty with your code to make the loops end (you can add whatever cleanup needs are required to there as well). The variable die is checked for truth on each pass and when it's True then the program exits.

import threading
import time

class MyThread (threading.Thread):
    die = False
    def __init__(self, name):
        threading.Thread.__init__(self)
        self.name = name

    def run (self):
        while not self.die:
            time.sleep(1)
            print (self.name)

    def join(self):
        self.die = True
        super().join()

if __name__ == '__main__':
    f = MyThread('first')
    f.start()
    s = MyThread('second')
    s.start()
    try:
        while True:
            time.sleep(2)
    except KeyboardInterrupt:
        f.join()
        s.join()

How do I perform query filtering in django templates

You can't do this, which is by design. The Django framework authors intended a strict separation of presentation code from data logic. Filtering models is data logic, and outputting HTML is presentation logic.

So you have several options. The easiest is to do the filtering, then pass the result to render_to_response. Or you could write a method in your model so that you can say {% for object in data.filtered_set %}. Finally, you could write your own template tag, although in this specific case I would advise against that.

Checkout subdirectories in Git?

git clone --filter from git 2.19 now works on GitHub (tested 2020-09-18, git 2.25.1)

This option was added together with an update to the remote protocol, and it truly prevents objects from being downloaded from the server.

To clone only objects required for d1 of this repository: https://github.com/cirosantilli/test-git-partial-clone I can do:

git clone \
  --depth 1 \
  --filter=blob:none \
  --no-checkout \
  https://github.com/cirosantilli/test-git-partial-clone \
;
cd test-git-partial-clone
git checkout master -- d1

I have covered this in more detail at: Git: How do I clone a subdirectory only of a Git repository?

Get folder up one level

You can try

echo realpath(__DIR__ . DIRECTORY_SEPARATOR . '..'); 

Use string.Contains() with switch()

Nope, switch statement requires compile time constants. The statement message.Contains("test") can evaluate true or false depending on the message so it is not a constant thus cannot be used as a 'case' for switch statement.

Object Dump JavaScript

Using console.log(object) will throw your object to the Javascript console, but that's not always what you want. Using JSON.stringify(object) will return most stuff to be stored in a variable, for example to send it to a textarea input and submit the content back to the server.

How to prevent scanf causing a buffer overflow in C?

Directly using scanf(3) and its variants poses a number of problems. Typically, users and non-interactive use cases are defined in terms of lines of input. It's rare to see a case where, if enough objects are not found, more lines will solve the problem, yet that's the default mode for scanf. (If a user didn't know to enter a number on the first line, a second and third line will probably not help.)

At least if you fgets(3) you know how many input lines your program will need, and you won't have any buffer overflows...

unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING error

Use { before $ sign. And also add addslashes function to escape special characters.

$sqlupdate1 = "UPDATE table SET commodity_quantity=".$qty."WHERE user=".addslashes($rows['user'])."'";

Converting string into datetime

Create a small utility function like:

def date(datestr="", format="%Y-%m-%d"):
    from datetime import datetime
    if not datestr:
        return datetime.today().date()
    return datetime.strptime(datestr, format).date()

This is versatile enough:

  • If you don't pass any arguments it will return today's date.
  • There's a date format as default that you can override.
  • You can easily modify it to return a datetime.

Normalizing a list of numbers in Python

Use :

norm = [float(i)/sum(raw) for i in raw]

to normalize against the sum to ensure that the sum is always 1.0 (or as close to as possible).

use

norm = [float(i)/max(raw) for i in raw]

to normalize against the maximum

What is going wrong when Visual Studio tells me "xcopy exited with code 4"

If any other solution is in the debug mode then first stop them all and after that restart the visual studio. It worked for me.

Why does sudo change the PATH?

Secure_path is your friend, but if you want to exempt yourself from secure_path just do

sudo visudo

And append

Defaults exempt_group=your_goup

If you want to exempt a bunch of users create a group, add all the users to it, and use that as your exempt_group. man 5 sudoers for more.

How to force keyboard with numbers in mobile website in Android

Some browsers igoners sending leading zero to the server when the input type is "number". So I use a mixing of jquery and html to load a numeric keypad and also make sure that the value is sent as a text not as a number:

_x000D_
_x000D_
$(document).ready(function(){_x000D_
$(".numberonly").focus(function(){$(this).attr("type","number")});_x000D_
$(".numberonly").blur(function(){$(this).attr("type","text")});_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" class="numberonly">
_x000D_
_x000D_
_x000D_

How do I use vim registers?

I use the default register to grep for text in my vim window without having to reach for the mouse.

  1. yank text
  2. :!grep "<CTRL-R>0"<CR>

List of <p:ajax> events

Unfortunatelly, Ajax events are poorly documented and I haven't found any comprehensive list. For example, User Guide v. 3.5 lists itemChange event for p:autoComplete, but forgets to mention change event.

If you want to find out which events are supported:

  1. Download and unpack primefaces source jar
  2. Find the JavaScript file, where your component is defined (for example, most form components such as SelectOneMenu are defined in forms.js)
  3. Search for this.cfg.behaviors references

For example, this section is responsible for launching toggleSelect event in SelectCheckboxMenu component:

fireToggleSelectEvent: function(checked) {
    if(this.cfg.behaviors) {
        var toggleSelectBehavior = this.cfg.behaviors['toggleSelect'];

        if(toggleSelectBehavior) {
            var ext = {
                params: [{name: this.id + '_checked', value: checked}]
            }
        }

        toggleSelectBehavior.call(this, null, ext);
    }
},

How to use source: function()... and AJAX in JQuery UI autocomplete

On the .ASPX page:

  <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <html xmlns="http://www.w3.org/1999/xhtml">
  <head id="Head1" runat="server">
        <title>AutoComplete Box with jQuery</title>
        <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>  
        <script type="text/javascript">
            $(document).ready(function() {
                SearchText();
            });
            function SearchText() {
                $(".autosuggest").autocomplete({
                    source: function(request, response) {
                        $.ajax({
                            type: "POST",
                            contentType: "application/json; charset=utf-8",
                            url: "Default.aspx/GetAutoCompleteData",
                            data: "{'username':'" + document.getElementById('txtSearch').value + "'}",
                            dataType: "json",
                            success: function (data) {
                                if (data != null) {

                                    response(data.d);
                                }
                            },
                            error: function(result) {
                                alert("Error");
                            }
                        });
                    }
                });
            }
        </script>
  </head>
  <body>
      <form id="form1" runat="server">
          <div class="demo">
           <div class="ui-widget">
            <label for="tbAuto">Enter UserName: </label>
       <input type="text" id="txtSearch" class="autosuggest" />
    </div>
        </form>
    </body>
    </html>    

In your .ASPX.CS code-behind file:

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web.Services;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    [WebMethod]
    public static List<string> GetAutoCompleteData(string username)
    {
        List<string> result = new List<string>();
            SqlConnection con = new SqlConnection("Data Source=YourDatasource;Initial Catalog=DatabseName;uid=sa;password=123");

            SqlCommand cmd = new SqlCommand("select DISTINCT Name from Address where Name LIKE '%'+@Name+'%'", con);
            con.Open();
                cmd.Parameters.AddWithValue("@Name", username);
                SqlDataReader dr = cmd.ExecuteReader();

                while (dr.Read())
                {
                    result.Add(dr["Name"].ToString());
                }
                return result;
        }
}

Generate random string/characters in JavaScript

Fast and improved algorithm. Does not guarantee uniform (see comments).

function getRandomId(length) {
    if (!length) {
        return '';
    }

    const possible =
        'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let array;

    if ('Uint8Array' in self && 'crypto' in self && length <= 65536) {
        array = new Uint8Array(length);
        self.crypto.getRandomValues(array);
    } else {
        array = new Array(length);

        for (let i = 0; i < length; i++) {
            array[i] = Math.floor(Math.random() * 62);
        }
    }

    let result = '';

    for (let i = 0; i < length; i++) {
        result += possible.charAt(array[i] % 62);
    }

    return result;
}

Run script with rc.local: script works, but not at boot

In this example of a rc.local script I use io redirection at the very first line of execution to my own log file:

#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

exec 2> /tmp/rc.local.log  # send stderr from rc.local to a log file
exec 1>&2                      # send stdout to the same log file
set -x                         # tell sh to display commands before execution

/opt/stuff/somefancy.error.script.sh

exit 0

How do you comment out code in PowerShell?

In PowerShell V1 there's only # to make the text after it a comment.

# This is a comment in Powershell

In PowerShell V2 <# #> can be used for block comments and more specifically for help comments.

#REQUIRES -Version 2.0

<#
.SYNOPSIS
    A brief description of the function or script. This keyword can be used
    only once in each topic.
.DESCRIPTION
    A detailed description of the function or script. This keyword can be
    used only once in each topic.
.NOTES
    File Name      : xxxx.ps1
    Author         : J.P. Blanc ([email protected])
    Prerequisite   : PowerShell V2 over Vista and upper.
    Copyright 2011 - Jean Paul Blanc/Silogix
.LINK
    Script posted over:
    http://silogix.fr
.EXAMPLE
    Example 1
.EXAMPLE
    Example 2
#>
Function blabla
{}

For more explanation about .SYNOPSIS and .* see about_Comment_Based_Help.

Remark: These function comments are used by the Get-Help CmdLet and can be put before the keyword Function, or inside the {} before or after the code itself.

Convert JavaScript string in dot notation into an object reference

Other proposals are a little cryptic, so I thought I'd contribute:

Object.prop = function(obj, prop, val){
    var props = prop.split('.')
      , final = props.pop(), p 
    while(p = props.shift()){
        if (typeof obj[p] === 'undefined')
            return undefined;
        obj = obj[p]
    }
    return val ? (obj[final] = val) : obj[final]
}

var obj = { a: { b: '1', c: '2' } }

// get
console.log(Object.prop(obj, 'a.c')) // -> 2
// set
Object.prop(obj, 'a.c', function(){})
console.log(obj) // -> { a: { b: '1', c: [Function] } }

Increasing nesting function calls limit

This error message comes specifically from the XDebug extension. PHP itself does not have a function nesting limit. Change the setting in your php.ini:

xdebug.max_nesting_level = 200

or in your PHP code:

ini_set('xdebug.max_nesting_level', 200);

As for if you really need to change it (i.e.: if there's a alternative solution to a recursive function), I can't tell without the code.

Install MySQL on Ubuntu without a password prompt

This should do the trick

export DEBIAN_FRONTEND=noninteractive
sudo -E apt-get -q -y install mysql-server

Of course, it leaves you with a blank root password - so you'll want to run something like

mysqladmin -u root password mysecretpasswordgoeshere

Afterwards to add a password to the account.

HTML5 Video // Completely Hide Controls

A simple solution is – just to ignore user interactions :-)

video {
  pointer-events: none;
}

Converting cv::Mat to IplImage*

Here is the recent fix for dlib users link

cv::Mat img = ...
IplImage iplImage = cvIplImage(img);

Printing Python version in output

Try

python --version 

or

python -V

This will return a current python version in terminal.

PHP $_FILES['file']['tmp_name']: How to preserve filename and extension?

$_FILES['file']['tmp_name']; will contain the temporary file name of the file on the server. This is just a placeholder on your server until you process the file

$_FILES['file']['name']; contains the original name of the uploaded file from the user's computer.

How do I create dynamic properties in C#?

If you need this for data-binding purposes, you can do this with a custom descriptor model... by implementing ICustomTypeDescriptor, TypeDescriptionProvider and/or TypeCoverter, you can create your own PropertyDescriptor instances at runtime. This is what controls like DataGridView, PropertyGrid etc use to display properties.

To bind to lists, you'd need ITypedList and IList; for basic sorting: IBindingList; for filtering and advanced sorting: IBindingListView; for full "new row" support (DataGridView): ICancelAddNew (phew!).

It is a lot of work though. DataTable (although I hate it) is cheap way of doing the same thing. If you don't need data-binding, just use a hashtable ;-p

Here's a simple example - but you can do a lot more...

Print commit message of a given commit in git

Not plumbing, but I have these in my .gitconfig:

lsum = log -n 1 --pretty=format:'%s'
lmsg = log -n 1 --pretty=format:'%s%n%n%b'

That's "last summary" and "last message". You can provide a commit to get the summary or message of that commit. (I'm using 1.7.0.5 so don't have %B.)

How to include JavaScript file or library in Chrome console?

If anyone, fails to load because hes script violates the script-src "Content Security Policy" or "because unsafe-eval' is not an allowed", I will advice using my pretty-small module-injector as a dev-tools snippet, then you'll be able to load like this:

_x000D_
_x000D_
imports('https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js')_x000D_
  .then(()=>alert(`today is ${moment().format('dddd')}`));
_x000D_
<script src="https://raw.githack.com/shmuelf/PowerJS/master/src/power-moduleInjector.js"></script>
_x000D_
_x000D_
_x000D_

this solution works because:

  1. It loades the library in xhr - which allows CORS from console, and avoids the script-src policy.
  2. It uses the synchronous option of xhr which allows you to stay at the console/snippet's context, so you'll have the permission to eval the script, and not to get-treated as an unsafe-eval.

Bootstrap: Position of dropdown menu relative to navbar item

If you want to display the menu up, just add the class "dropup"
and remove the class "dropdown" if exists from the same div.

<div class="btn-group dropup">

enter image description here

PHP Warning: Division by zero

A lot of the answers here do not work for (string)"0.00".

Try this:

if (isset($_POST['num1']) && (float)$_POST['num1'] != 0) {
  ...
}

Or even more strict:

if (isset($_POST['num1']) && is_numeric($_POST['num1']) && (float)$_POST['num1'] != 0) {
  ...
}

Eloquent Collection: Counting and Detect Empty

According to Laravel Documentation states you can use this way:

$result->isEmpty();

The isEmpty method returns true if the collection is empty; otherwise, false is returned.

How do I deal with certificates using cURL while trying to access an HTTPS url?

This worked for me

sudo apt-get install ca-certificates

then go into the certificates folder at

sudo cd /etc/ssl/certs

then you copy the ca-certificates.crt file into the /etc/pki/tls/certs

sudo cp ca-certificates.crt /etc/pki/tls/certs

if there is no tls/certs folder: create one and change permissions using chmod 777 -R folderNAME

How to add button in ActionBar(Android)?

An activity populates the ActionBar in its onCreateOptionsMenu() method.

Instead of using setcustomview(), just override onCreateOptionsMenu like this:

@Override    
public boolean onCreateOptionsMenu(Menu menu) {
  MenuInflater inflater = getMenuInflater();
  inflater.inflate(R.menu.mainmenu, menu);
  return true;
}

If an actions in the ActionBar is selected, the onOptionsItemSelected() method is called. It receives the selected action as parameter. Based on this information you code can decide what to do for example:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
  switch (item.getItemId()) {
    case R.id.menuitem1:
      Toast.makeText(this, "Menu Item 1 selected", Toast.LENGTH_SHORT).show();
      break;
    case R.id.menuitem2:
      Toast.makeText(this, "Menu item 2 selected", Toast.LENGTH_SHORT).show();
      break;
  }
  return true;
}

How can I enable cURL for an installed Ubuntu LAMP stack?

Try:

sudo apt-get install php-curl

It worked on a fresh Ubuntu 16.04 (Xenial Xerus) LTS, with lamp-server and php7. I tried with php7-curl - it didn't work and also didn't work with php5-curl.

Angular 2 Dropdown Options Default Value

Step: 1 Create Properties declare class

export class Task {
    title: string;
    priority: Array<any>;
    comment: string;

    constructor() {
        this.title      = '';
        this.priority   = [];
        this.comment    = '';
     }
}

Stem: 2 Your Component Class

import { Task } from './task';

export class TaskComponent implements OnInit {
  priorityList: Array<any> = [
    { value: 0, label: '?' },
    { value: 1, label: '?' },
    { value: 2, label: '??' },
    { value: 3, label: '???' },
    { value: 4, label: '????' },
    { value: 5, label: '?????' }
  ];
  taskModel: Task           = new Task();

  constructor(private taskService: TaskService) { }
  ngOnInit() {
    this.taskModel.priority     = [3]; // index number
  }
}

Step: 3 View File .html

<select class="form-control" name="priority" [(ngModel)]="taskModel.priority"  required>
    <option *ngFor="let list of priorityList" [value]="list.value">
      {{list.label}}
    </option>
</select>

Output:

enter image description here

Which tool to build a simple web front-end to my database

The most rapid option is to hand out MS Access or SQL Sever Management Studio (there's a free express edition) along with a read only account.

PHP is simple and has a well earned reputation for getting stuff done. PHP is excellent for copying and pasting code, and you can iterate insanely fast in PHP. PHP can lead to hard-to-maintain applications, and it can be difficult to set up a visual debugger.

Given that you use SQL Server, ASP.NET is also a good option. This is somewhat harder to setup; you'll need an IIS server, with a configured application. Iterations are a bit slower. ASP.NET is easier to maintain and Visual Studio is the best visual debugger around.

How to set Navigation Drawer to be opened from right to left

Making it open from rtl isn't good for user experience, to make it responsive to the user locale I just added the following line to my DrawerLayout parameters:

android:layoutDirection="locale"

Added it to my AppBarLayout to make the hamburger layout match the drawer opening direction too.

C# 30 Days From Todays Date

A bit late to this question, but I created a class with all the handy methods needed to create a fully functional time trial in C#. Rather than your application config, I write the expiry time to the Windows Application Data path, and that will also remain persistent even after the program has closed (it's also tricky to find the path for the average user).

Fully documented and simple to use, I hope someone finds it useful!

public class TimeTrialManager
{
    private long expiryTime=0;
    private string softwareName = "";
    private string userPath="";
    private bool useSeconds = false;

    public TimeTrialManager(string softwareName) {
        this.softwareName = softwareName;
        // Create folder in Windows Application Data folder for persistence:
        userPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString() + "\\" + softwareName + "_prefs\\";
        if (!Directory.Exists(userPath)) Directory.CreateDirectory(Path.GetDirectoryName(userPath));
        userPath += "expiryinfo.txt";
    }

    // Use this method to check if the expiry has already been created. If
    // it has, you don't need to call the setExpiryDate() method ever again.
    public bool expiryHasBeenStored(){
        return File.Exists(userPath);
    }

    // Use this to set expiry as the number of days from the current time.
    // This should be called just once in the program's lifetime for that user.
    public void setExpiryDate(double days)  {
        DateTime time = DateTime.Now.AddDays(days);
        expiryTime = time.ToFileTimeUtc();
        storeExpiry(expiryTime.ToString() );
        useSeconds = false;
    }

    // Like above, but set the number of seconds. This should be just used for testing
    // as no sensible time trial would allow the user seconds to test the trial out:
    public void setExpiryTime(double seconds)   {
        DateTime time = DateTime.Now.AddSeconds(seconds);
        expiryTime = time.ToFileTimeUtc();
        storeExpiry(expiryTime.ToString());
        useSeconds = true;
    }

    // Check for this in a background timer or whenever else you wish to check if the time has run out
    public bool trialHasExpired()   {
        if(!File.Exists(userPath)) return false;
        if (expiryTime == 0)    expiryTime = Convert.ToInt64(File.ReadAllText(userPath));
        if (DateTime.Now.ToFileTimeUtc() >= expiryTime) return true; else return false;
    }

    // This method is optional and isn't required to use the core functionality of the class
    // Perhaps use it to tell the user how long he has left to trial the software
    public string expiryAsHumanReadableString(bool remaining=false) {
        DateTime dt = new DateTime();
        dt = DateTime.FromFileTimeUtc(expiryTime);
        if (remaining == false) return dt.ToShortDateString() + " " + dt.ToLongTimeString();
        else {
            if (useSeconds) return dt.Subtract(DateTime.Now).TotalSeconds.ToString();
            else return (dt.Subtract(DateTime.Now).TotalDays ).ToString();
        }
    }

    // This method is private to the class, so no need to worry about it
    private void storeExpiry(string value)  {
        try { File.WriteAllText(userPath, value); }
        catch (Exception ex) { MessageBox.Show(ex.Message); }
    }

}

Here is a typical usage of the above class. Couldn't be simpler!

TimeTrialManager ttm;
private void Form1_Load(object sender, EventArgs e)
{
    ttm = new TimeTrialManager("TestTime");
    if (!ttm.expiryHasBeenStored()) ttm.setExpiryDate(30); // Expires in 30 days time
}

private void timer1_Tick(object sender, EventArgs e)
{
    if (ttm.trialHasExpired()) { MessageBox.Show("Trial over! :("); Environment.Exit(0); }
}

How to split long commands over multiple lines in PowerShell

Splat Method with Calculations

If you choose splat method, beware calculations that are made using other parameters. In practice, sometimes I have to set variables first then create the hash table. Also, the format doesn't require single quotes around the key value or the semi-colon (as mentioned above).

Example of a call to a function that creates an Excel spreadsheet

$title = "Cut-off File Processing on $start_date_long_str"
$title_row = 1
$header_row = 2
$data_row_start = 3
$data_row_end = $($data_row_start + $($file_info_array.Count) - 1)

# use parameter hash table to make code more readable
$params = @{
    title = $title
    title_row = $title_row
    header_row = $header_row
    data_row_start = $data_row_start
    data_row_end = $data_row_end
}
$xl_wksht = Create-Excel-Spreadsheet @params

Note: The file array contains information that will affect how the spreadsheet is populated.

Matplotlib transparent line plots

After I plotted all the lines, I was able to set the transparency of all of them as follows:

for l in fig_field.gca().lines:
    l.set_alpha(.7)

EDIT: please see Joe's answer in the comments.

How can I control Chromedriver open window size?

Use this for your custom size:

driver.manage().window().setSize(new Dimension(1024,768));

you can change your dimensions as per your requirements.

Multiple ping script in Python

Try subprocess.call. It saves the return value of the program that was used.

According to my ping manual, it returns 0 on success, 2 when pings were sent but no reply was received and any other value indicates an error.

# typo error in import
import subprocess

for ping in range(1,10):
    address = "127.0.0." + str(ping)
    res = subprocess.call(['ping', '-c', '3', address])
    if res == 0:
        print "ping to", address, "OK"
    elif res == 2:
        print "no response from", address
    else:
        print "ping to", address, "failed!"

How to get index of object by its property in JavaScript?

Alternatively to German Attanasio Ruiz's answer, you can eliminate the 2nd loop by using Array.reduce() instead of Array.map();

var Data = [
    { name: 'hypno7oad' }
]
var indexOfTarget = Data.reduce(function (indexOfTarget, element, currentIndex) {
    return (element.name === 'hypno7oad') ? currentIndex : indexOfTarget;
}, -1);

"Char cannot be dereferenced" error

If Character.isLetter(ch) looks a bit wordy/ugly you can use a static import.

import static java.lang.Character.*;


if(isLetter(ch)) {

} else if(isDigit(ch)) {

} 

How can I check if PostgreSQL is installed or not via Linux script?

If it is debian based.

aptitude show postgresql | grep State

But I guess you can just try to launch it with some flag like --version, that simply prints some info and exits.

Updated using "service postgres status". Try:

service postgres status
if [ "$?" -gt "0" ]; then
  echo "Not installed".
else
  echo "Intalled"
fi

Getting only response header from HTTP POST using curl

For long response bodies (and various other similar situations), the solution I use is always to pipe to less, so

curl -i https://api.github.com/users | less

or

curl -s -D - https://api.github.com/users | less

will do the job.

An example of how to use getopts in bash

POSIX 7 example

It is also worth checking the example from the standard: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html

aflag=
bflag=
while getopts ab: name
do
    case $name in
    a)    aflag=1;;
    b)    bflag=1
          bval="$OPTARG";;
    ?)   printf "Usage: %s: [-a] [-b value] args\n" $0
          exit 2;;
    esac
done
if [ ! -z "$aflag" ]; then
    printf "Option -a specified\n"
fi
if [ ! -z "$bflag" ]; then
    printf 'Option -b "%s" specified\n' "$bval"
fi
shift $(($OPTIND - 1))
printf "Remaining arguments are: %s\n" "$*"

And then we can try it out:

$ sh a.sh
Remaining arguments are: 
$ sh a.sh -a
Option -a specified
Remaining arguments are: 
$ sh a.sh -b
No arg for -b option
Usage: a.sh: [-a] [-b value] args
$ sh a.sh -b myval
Option -b "myval" specified
Remaining arguments are: 
$ sh a.sh -a -b myval
Option -a specified
Option -b "myval" specified
Remaining arguments are: 
$ sh a.sh remain
Remaining arguments are: remain
$ sh a.sh -- -a remain
Remaining arguments are: -a remain

Tested in Ubuntu 17.10, sh is dash 0.5.8.

Javascript - How to detect if document has loaded (IE 7/Firefox 3)

If you actually want this code to run at load, not at domready (ie you need the images to be loaded as well), then unfortunately the ready function doesn't do it for you. I generally just do something like this:

Include in document javascript (ie always called before onload fired):

var pageisloaded=0;
window.addEvent('load',function(){
 pageisloaded=1;
});

Then your code:

if (pageisloaded) {
 DoStuffFunction();
} else {
 window.addEvent('load',DoStuffFunction);
}

(Or the equivalent in your framework of preference.) I use this code to do precaching of javascript and images for future pages. Since the stuff I'm getting isn't used for this page at all, I don't want it to take precedence over the speedy download of images.

There may be a better way, but I've yet to find it.

Android Studio - Failed to apply plugin [id 'com.android.application']

I faced the same issue in Android Studio version 3.5.3. This is how i fixed it.

I updated the dependecy com.android.tools.build:gradle in my project level build.gradle file from a lower version to 3.5.3 as below.

classpath 'com.android.tools.build:gradle:3.5.3'

I then went ahead and edited the value of distributionUrl in gradle-wrapper.properties file as below. This file is in the directory /gradle/wrapper/ from the root of your project folder.

distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip

How to destroy JWT Tokens on logout?

You can add "issue time" to token and maintain "last logout time" for each user on the server. When you check token validity, also check "issue time" be after "last logout time".

Event listener for when element becomes visible?

There is at least one way, but it's not a very good one. You could just poll the element for changes like this:

var previous_style,
    poll = window.setInterval(function()
{
    var current_style = document.getElementById('target').style.display;
    if (previous_style != current_style) {
        alert('style changed');
        window.clearInterval(poll);
    } else {
        previous_style = current_style;
    }
}, 100);

The DOM standard also specifies mutation events, but I've never had the chance to use them, and I'm not sure how well they're supported. You'd use them like this:

target.addEventListener('DOMAttrModified', function()
{
    if (e.attrName == 'style') {
        alert('style changed');
    }
}, false);

This code is off the top of my head, so I'm not sure if it'd work.

The best and easiest solution would be to have a callback in the function displaying your target.

Install php-zip on php 5.6 on Ubuntu

Try either

  • sudo apt-get install php-zip or
  • sudo apt-get install php5.6-zip

Then, you might have to restart your web server.

  • sudo service apache2 restart or
  • sudo service nginx restart

If you are installing on centos or fedora OS then use yum in place of apt-get. example:-

sudo yum install php-zip or sudo yum install php5.6-zip and sudo service httpd restart

How to create a temporary directory/folder in Java?

This is what I decided to do for my own code:

/**
 * Create a new temporary directory. Use something like
 * {@link #recursiveDelete(File)} to clean this directory up since it isn't
 * deleted automatically
 * @return  the new directory
 * @throws IOException if there is an error creating the temporary directory
 */
public static File createTempDir() throws IOException
{
    final File sysTempDir = new File(System.getProperty("java.io.tmpdir"));
    File newTempDir;
    final int maxAttempts = 9;
    int attemptCount = 0;
    do
    {
        attemptCount++;
        if(attemptCount > maxAttempts)
        {
            throw new IOException(
                    "The highly improbable has occurred! Failed to " +
                    "create a unique temporary directory after " +
                    maxAttempts + " attempts.");
        }
        String dirName = UUID.randomUUID().toString();
        newTempDir = new File(sysTempDir, dirName);
    } while(newTempDir.exists());

    if(newTempDir.mkdirs())
    {
        return newTempDir;
    }
    else
    {
        throw new IOException(
                "Failed to create temp dir named " +
                newTempDir.getAbsolutePath());
    }
}

/**
 * Recursively delete file or directory
 * @param fileOrDir
 *          the file or dir to delete
 * @return
 *          true iff all files are successfully deleted
 */
public static boolean recursiveDelete(File fileOrDir)
{
    if(fileOrDir.isDirectory())
    {
        // recursively delete contents
        for(File innerFile: fileOrDir.listFiles())
        {
            if(!FileUtilities.recursiveDelete(innerFile))
            {
                return false;
            }
        }
    }

    return fileOrDir.delete();
}

How to convert seconds to HH:mm:ss in moment.js

My solution for changing seconds (number) to string format (for example: 'mm:ss'):

const formattedSeconds = moment().startOf('day').seconds(S).format('mm:ss');

Write your seconds instead 'S' in example. And just use the 'formattedSeconds' where you need.

How to put a symbol above another in LaTeX?

Use \overset{above}{main} in math mode. In your case, \overset{a}{\#}.

How do I dump the data of some SQLite3 tables?

The best method would be to take the code the sqlite3 db dump would do, excluding schema parts.

Example pseudo code:

SELECT 'INSERT INTO ' || tableName || ' VALUES( ' || 
  {for each value} ' quote(' || value || ')'     (+ commas until final)
|| ')' FROM 'tableName' ORDER BY rowid DESC

See: src/shell.c:838 (for sqlite-3.5.9) for actual code

You might even just take that shell and comment out the schema parts and use that.

Facebook share link without JavaScript

In case you want to share on more forums, here is the solution.. https://github.com/bradvin/social-share-urls

How to disable a button when an input is empty?

Using constants allows to combine multiple fields for verification:

_x000D_
_x000D_
class LoginFrm extends React.Component {_x000D_
  constructor() {_x000D_
    super();_x000D_
    this.state = {_x000D_
      email: '',_x000D_
      password: '',_x000D_
    };_x000D_
  }_x000D_
  _x000D_
  handleEmailChange = (evt) => {_x000D_
    this.setState({ email: evt.target.value });_x000D_
  }_x000D_
  _x000D_
  handlePasswordChange = (evt) => {_x000D_
    this.setState({ password: evt.target.value });_x000D_
  }_x000D_
  _x000D_
  handleSubmit = () => {_x000D_
    const { email, password } = this.state;_x000D_
    alert(`Welcome ${email} password: ${password}`);_x000D_
  }_x000D_
  _x000D_
  render() {_x000D_
    const { email, password } = this.state;_x000D_
    const enabled =_x000D_
          email.length > 0 &&_x000D_
          password.length > 0;_x000D_
    return (_x000D_
      <form onSubmit={this.handleSubmit}>_x000D_
        <input_x000D_
          type="text"_x000D_
          placeholder="Email"_x000D_
          value={this.state.email}_x000D_
          onChange={this.handleEmailChange}_x000D_
        />_x000D_
        _x000D_
        <input_x000D_
          type="password"_x000D_
          placeholder="Password"_x000D_
          value={this.state.password}_x000D_
          onChange={this.handlePasswordChange}_x000D_
        />_x000D_
        <button disabled={!enabled}>Login</button>_x000D_
      </form>_x000D_
    )_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<LoginFrm />, document.body);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<body>_x000D_
_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_

Replacement for deprecated sizeWithFont: in iOS 7?

Create a function that takes a UILabel instance. and returns CGSize

CGSize constraint = CGSizeMake(label.frame.size.width , 2000.0);
// Adjust according to requirement

CGSize size;
if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0){

    NSRange range = NSMakeRange(0, [label.attributedText length]);

    NSDictionary *attributes = [label.attributedText attributesAtIndex:0 effectiveRange:&range];
    CGSize boundingBox = [label.text boundingRectWithSize:constraint options: NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;

    size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));
}
else{
    size = [label.text sizeWithFont:label.font constrainedToSize:constraint lineBreakMode:label.lineBreakMode];
}

return size;

HTML if image is not found

its works for me that if you dont want to use alt attribute if image break then you can use this piece of code and set accordingly.

<h1>
  <a> 
   <object data="~/img/Logo.jpg" type="image/png">
     Your Custom Text Here
   </object>
  </a>
</h1>

Remove pattern from string with gsub

Just to point out that there is an approach using functions from the tidyverse, which I find more readable than gsub:

a %>% stringr::str_remove(pattern = ".*_")

How do I erase an element from std::vector<> by index?

If you have an unordered vector you can take advantage of the fact that it's unordered and use something I saw from Dan Higgins at CPPCON

template< typename TContainer >
static bool EraseFromUnorderedByIndex( TContainer& inContainer, size_t inIndex )
{
    if ( inIndex < inContainer.size() )
    {
        if ( inIndex != inContainer.size() - 1 )
            inContainer[inIndex] = inContainer.back();
        inContainer.pop_back();
        return true;
    }
    return false;
}

Since the list order doesn't matter, just take the last element in the list and copy it over the top of the item you want to remove, then pop and delete the last item.

HTML Tags in Javascript Alert() method

You can use all Unicode characters and the escape characters \n and \t. An example:

_x000D_
_x000D_
document.getElementById("test").onclick = function() {_x000D_
  alert(_x000D_
    'This is an alert with basic formatting\n\n' _x000D_
    + "\t• list item 1\n" _x000D_
    + '\t• list item 2\n' _x000D_
    + '\t• list item 3\n\n' _x000D_
    + '???????????????????????\n\n' _x000D_
    + 'Simple table\n\n' _x000D_
    + 'Char\t| Result\n' _x000D_
    + '\\n\t| line break\n' _x000D_
    + '\\t\t| tab space'_x000D_
  );_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<title>Alert formatting</title>_x000D_
<meta charset=utf-8>_x000D_
<button id=test>Click</button>
_x000D_
_x000D_
_x000D_

Result in Firefox:

screenshot Firefox

You get the same look in almost all browsers.

JavaScript Chart.js - Custom data formatting to display on tooltip

This works perfectly fine with me. It takes label and format the value.

options: {
        tooltips: {
            callbacks: {
                label: function(tooltipItem, data) {

                    let label = data.labels[tooltipItem.index];
                    let value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
                    return ' ' + label + ': ' + value + ' %';

                }
            }
        }
    }

Resize a large bitmap file to scaled output file on Android

This worked for me. The function gets a path to a file on the sd card and returns a Bitmap in the maximum displayable size. The code is from Ofir with some changes like image file on sd instead a Ressource and the witdth and heigth are get from the Display Object.

private Bitmap makeBitmap(String path) {

    try {
        final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
        //resource = getResources();

        // Decode image size
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);

        int scale = 1;
        while ((options.outWidth * options.outHeight) * (1 / Math.pow(scale, 2)) >
                IMAGE_MAX_SIZE) {
            scale++;
        }
        Log.d("TAG", "scale = " + scale + ", orig-width: " + options.outWidth + ", orig-height: " + options.outHeight);

        Bitmap pic = null;
        if (scale > 1) {
            scale--;
            // scale to max possible inSampleSize that still yields an image
            // larger than target
            options = new BitmapFactory.Options();
            options.inSampleSize = scale;
            pic = BitmapFactory.decodeFile(path, options);

            // resize to desired dimensions

            Display display = getWindowManager().getDefaultDisplay();
            Point size = new Point();
            display.getSize(size);
            int width = size.y;
            int height = size.x;

            //int height = imageView.getHeight();
            //int width = imageView.getWidth();
            Log.d("TAG", "1th scale operation dimenions - width: " + width + ", height: " + height);

            double y = Math.sqrt(IMAGE_MAX_SIZE
                    / (((double) width) / height));
            double x = (y / height) * width;

            Bitmap scaledBitmap = Bitmap.createScaledBitmap(pic, (int) x, (int) y, true);
            pic.recycle();
            pic = scaledBitmap;

            System.gc();
        } else {
            pic = BitmapFactory.decodeFile(path);
        }

        Log.d("TAG", "bitmap size - width: " +pic.getWidth() + ", height: " + pic.getHeight());
        return pic;

    } catch (Exception e) {
        Log.e("TAG", e.getMessage(),e);
        return null;
    }

}

How to determine if binary tree is balanced?

public int height(Node node){
    if(node==null)return 0;
    else{
        int l=height(node.leftChild);
        int r=height(node.rightChild);
       return(l>r?l+1:r+1);

}}
public boolean balanced(Node n){

    int l= height(n.leftChild);
    int r= height(n.rightChild);

    System.out.println(l + " " +r);
    if(Math.abs(l-r)>1)
        return false;
    else 
        return true;
    }

Git for Windows: .bashrc or equivalent configuration files for Git Bash shell

In your home directory, you should edit .bash_profile if you have Git for Windows 2.21.0 or later (as of this writing).

You could direct .bash_profile to just source .bashrc, but if something happens to your .bash_profile, then it will be unclear why your .bashrc is again not working.

I put all my aliases and other environment stuff in .bash_profile, and I also added this line:

echo "Sourcing ~/.bash_profile - this version of Git Bash doesn't use .bashrc"

And THEN, in .bashrc I have

echo "This version of Git Bash doesn't use .bashrc. Use .bash_profile instead"

(Building on @harsel's response. I woulda commented, but I have no points yet.)

The iOS Simulator deployment targets is set to 7.0, but the range of supported deployment target version for this platform is 8.0 to 12.1

Try these steps:

  1. Delete your Podfile.lock
  2. Delete your Podfile
  3. Build Project
  4. Add initialization code from firebase
  5. cd /ios
  6. pod install
  7. run Project

This was what worked for me.

Mounting multiple volumes on a docker container?

You can use -v option multiple times in docker run command to mount multiple directory in container:

docker run -t -i \
  -v '/on/my/host/test1:/on/the/container/test1' \
  -v '/on/my/host/test2:/on/the/container/test2' \
  ubuntu /bin/bash

How can I format the output of a bash command in neat columns

Found this by searching for "linux output formatted columns".

http://www.unix.com/shell-programming-scripting/117543-formatting-output-columns.html

For your needs, it's like:

awk '{ printf "%-20s %-40s\n", $1, $2}'

A JNI error has occurred, please check your installation and try again in Eclipse x86 Windows 8.1

The accepted answer did not resolve the issue, hence posting what worked for me.

Error/Issue: While trying to run my application as a Java application or as a Spring boot application, I am getting below error

A JNI error has occurred, please check your installation and try again. A Java exception has occured.

as well as getting this error on console Exception in thread "main" java.lang.UnsupportedClassVersionError: com/example/demo/IocApplication has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0

What is the Root cause?

The reason for this error is that

  • the Code is getting compiled on a higher version, in my case, it is version 11.. and
  • the code is getting executed on a lower version, in my case it is version 8.
  • ie: Java(JDK) compiled code on 11 , where as JRE version is 8.

Where did I configure JDK 11 and JRE 8 ?

  • I am using SpringToolSuite (STS). When I created the project, the JRE System library in the build path, which got added is the default JRE library version of 8 (1.8) But When I go to Project -> properties -> Java Compiler -> Compiler Compliance Level, it is by default having a selected version of 11

Solution:

Project -> properties -> Java Compiler -> Compiler Compliance Level

  • Set the Compiler Compliance Level to 1.8 That's it. Now you are compiling your code in 1.8 and executing the compiled code with a JRE 1.8.

How to copy data from one HDFS to another HDFS?

distcp is used for copying data to and from the hadoop filesystems in parallel. It is similar to the generic hadoop fs -cp command. In the background process, distcp is implemented as a MapReduce job where mappers are only implemented for copying in parallel across the cluster.

Usage:

  • copy one file to another

    % hadoop distcp file1 file2

  • copy directories from one location to another

    % hadoop distcp dir1 dir2

If dir2 doesn't exist then it will create that folder and copy the contents. If dir2 already exists, then dir1 will be copied under it. -overwrite option forces the files to be overwritten within the same folder. -update option updates only the files that are changed.

  • transferring data between two HDFS clusters

    % hadoop distcp -update -delete hdfs://nn1/dir1 hdfs://nn2/dir2

-delete option deletes the files or directories from the destination that are not present in the source.

BACKUP LOG cannot be performed because there is no current database backup

Originally, I created a database and then restored the backup file to my new empty database:

Right click on Databases > Restore Database > General : Device: [the path of back up file] ? OK

This was wrong. I shouldn't have first created the database.

Now, instead, I do this:

Right click on Databases > Restore Database > General : Device: [the path of back up file] ? OK

What is move semantics?

My first answer was an extremely simplified introduction to move semantics, and many details were left out on purpose to keep it simple. However, there is a lot more to move semantics, and I thought it was time for a second answer to fill the gaps. The first answer is already quite old, and it did not feel right to simply replace it with a completely different text. I think it still serves well as a first introduction. But if you want to dig deeper, read on :)

Stephan T. Lavavej took the time to provide valuable feedback. Thank you very much, Stephan!

Introduction

Move semantics allows an object, under certain conditions, to take ownership of some other object's external resources. This is important in two ways:

  1. Turning expensive copies into cheap moves. See my first answer for an example. Note that if an object does not manage at least one external resource (either directly, or indirectly through its member objects), move semantics will not offer any advantages over copy semantics. In that case, copying an object and moving an object means the exact same thing:

    class cannot_benefit_from_move_semantics
    {
        int a;        // moving an int means copying an int
        float b;      // moving a float means copying a float
        double c;     // moving a double means copying a double
        char d[64];   // moving a char array means copying a char array
    
        // ...
    };
    
  2. Implementing safe "move-only" types; that is, types for which copying does not make sense, but moving does. Examples include locks, file handles, and smart pointers with unique ownership semantics. Note: This answer discusses std::auto_ptr, a deprecated C++98 standard library template, which was replaced by std::unique_ptr in C++11. Intermediate C++ programmers are probably at least somewhat familiar with std::auto_ptr, and because of the "move semantics" it displays, it seems like a good starting point for discussing move semantics in C++11. YMMV.

What is a move?

The C++98 standard library offers a smart pointer with unique ownership semantics called std::auto_ptr<T>. In case you are unfamiliar with auto_ptr, its purpose is to guarantee that a dynamically allocated object is always released, even in the face of exceptions:

{
    std::auto_ptr<Shape> a(new Triangle);
    // ...
    // arbitrary code, could throw exceptions
    // ...
}   // <--- when a goes out of scope, the triangle is deleted automatically

The unusual thing about auto_ptr is its "copying" behavior:

auto_ptr<Shape> a(new Triangle);

      +---------------+
      | triangle data |
      +---------------+
        ^
        |
        |
        |
  +-----|---+
  |   +-|-+ |
a | p | | | |
  |   +---+ |
  +---------+

auto_ptr<Shape> b(a);

      +---------------+
      | triangle data |
      +---------------+
        ^
        |
        +----------------------+
                               |
  +---------+            +-----|---+
  |   +---+ |            |   +-|-+ |
a | p |   | |          b | p | | | |
  |   +---+ |            |   +---+ |
  +---------+            +---------+

Note how the initialization of b with a does not copy the triangle, but instead transfers the ownership of the triangle from a to b. We also say "a is moved into b" or "the triangle is moved from a to b". This may sound confusing because the triangle itself always stays at the same place in memory.

To move an object means to transfer ownership of some resource it manages to another object.

The copy constructor of auto_ptr probably looks something like this (somewhat simplified):

auto_ptr(auto_ptr& source)   // note the missing const
{
    p = source.p;
    source.p = 0;   // now the source no longer owns the object
}

Dangerous and harmless moves

The dangerous thing about auto_ptr is that what syntactically looks like a copy is actually a move. Trying to call a member function on a moved-from auto_ptr will invoke undefined behavior, so you have to be very careful not to use an auto_ptr after it has been moved from:

auto_ptr<Shape> a(new Triangle);   // create triangle
auto_ptr<Shape> b(a);              // move a into b
double area = a->area();           // undefined behavior

But auto_ptr is not always dangerous. Factory functions are a perfectly fine use case for auto_ptr:

auto_ptr<Shape> make_triangle()
{
    return auto_ptr<Shape>(new Triangle);
}

auto_ptr<Shape> c(make_triangle());      // move temporary into c
double area = make_triangle()->area();   // perfectly safe

Note how both examples follow the same syntactic pattern:

auto_ptr<Shape> variable(expression);
double area = expression->area();

And yet, one of them invokes undefined behavior, whereas the other one does not. So what is the difference between the expressions a and make_triangle()? Aren't they both of the same type? Indeed they are, but they have different value categories.

Value categories

Obviously, there must be some profound difference between the expression a which denotes an auto_ptr variable, and the expression make_triangle() which denotes the call of a function that returns an auto_ptr by value, thus creating a fresh temporary auto_ptr object every time it is called. a is an example of an lvalue, whereas make_triangle() is an example of an rvalue.

Moving from lvalues such as a is dangerous, because we could later try to call a member function via a, invoking undefined behavior. On the other hand, moving from rvalues such as make_triangle() is perfectly safe, because after the copy constructor has done its job, we cannot use the temporary again. There is no expression that denotes said temporary; if we simply write make_triangle() again, we get a different temporary. In fact, the moved-from temporary is already gone on the next line:

auto_ptr<Shape> c(make_triangle());
                                  ^ the moved-from temporary dies right here

Note that the letters l and r have a historic origin in the left-hand side and right-hand side of an assignment. This is no longer true in C++, because there are lvalues that cannot appear on the left-hand side of an assignment (like arrays or user-defined types without an assignment operator), and there are rvalues which can (all rvalues of class types with an assignment operator).

An rvalue of class type is an expression whose evaluation creates a temporary object. Under normal circumstances, no other expression inside the same scope denotes the same temporary object.

Rvalue references

We now understand that moving from lvalues is potentially dangerous, but moving from rvalues is harmless. If C++ had language support to distinguish lvalue arguments from rvalue arguments, we could either completely forbid moving from lvalues, or at least make moving from lvalues explicit at call site, so that we no longer move by accident.

C++11's answer to this problem is rvalue references. An rvalue reference is a new kind of reference that only binds to rvalues, and the syntax is X&&. The good old reference X& is now known as an lvalue reference. (Note that X&& is not a reference to a reference; there is no such thing in C++.)

If we throw const into the mix, we already have four different kinds of references. What kinds of expressions of type X can they bind to?

            lvalue   const lvalue   rvalue   const rvalue
---------------------------------------------------------              
X&          yes
const X&    yes      yes            yes      yes
X&&                                 yes
const X&&                           yes      yes

In practice, you can forget about const X&&. Being restricted to read from rvalues is not very useful.

An rvalue reference X&& is a new kind of reference that only binds to rvalues.

Implicit conversions

Rvalue references went through several versions. Since version 2.1, an rvalue reference X&& also binds to all value categories of a different type Y, provided there is an implicit conversion from Y to X. In that case, a temporary of type X is created, and the rvalue reference is bound to that temporary:

void some_function(std::string&& r);

some_function("hello world");

In the above example, "hello world" is an lvalue of type const char[12]. Since there is an implicit conversion from const char[12] through const char* to std::string, a temporary of type std::string is created, and r is bound to that temporary. This is one of the cases where the distinction between rvalues (expressions) and temporaries (objects) is a bit blurry.

Move constructors

A useful example of a function with an X&& parameter is the move constructor X::X(X&& source). Its purpose is to transfer ownership of the managed resource from the source into the current object.

In C++11, std::auto_ptr<T> has been replaced by std::unique_ptr<T> which takes advantage of rvalue references. I will develop and discuss a simplified version of unique_ptr. First, we encapsulate a raw pointer and overload the operators -> and *, so our class feels like a pointer:

template<typename T>
class unique_ptr
{
    T* ptr;

public:

    T* operator->() const
    {
        return ptr;
    }

    T& operator*() const
    {
        return *ptr;
    }

The constructor takes ownership of the object, and the destructor deletes it:

    explicit unique_ptr(T* p = nullptr)
    {
        ptr = p;
    }

    ~unique_ptr()
    {
        delete ptr;
    }

Now comes the interesting part, the move constructor:

    unique_ptr(unique_ptr&& source)   // note the rvalue reference
    {
        ptr = source.ptr;
        source.ptr = nullptr;
    }

This move constructor does exactly what the auto_ptr copy constructor did, but it can only be supplied with rvalues:

unique_ptr<Shape> a(new Triangle);
unique_ptr<Shape> b(a);                 // error
unique_ptr<Shape> c(make_triangle());   // okay

The second line fails to compile, because a is an lvalue, but the parameter unique_ptr&& source can only be bound to rvalues. This is exactly what we wanted; dangerous moves should never be implicit. The third line compiles just fine, because make_triangle() is an rvalue. The move constructor will transfer ownership from the temporary to c. Again, this is exactly what we wanted.

The move constructor transfers ownership of a managed resource into the current object.

Move assignment operators

The last missing piece is the move assignment operator. Its job is to release the old resource and acquire the new resource from its argument:

    unique_ptr& operator=(unique_ptr&& source)   // note the rvalue reference
    {
        if (this != &source)    // beware of self-assignment
        {
            delete ptr;         // release the old resource

            ptr = source.ptr;   // acquire the new resource
            source.ptr = nullptr;
        }
        return *this;
    }
};

Note how this implementation of the move assignment operator duplicates logic of both the destructor and the move constructor. Are you familiar with the copy-and-swap idiom? It can also be applied to move semantics as the move-and-swap idiom:

    unique_ptr& operator=(unique_ptr source)   // note the missing reference
    {
        std::swap(ptr, source.ptr);
        return *this;
    }
};

Now that source is a variable of type unique_ptr, it will be initialized by the move constructor; that is, the argument will be moved into the parameter. The argument is still required to be an rvalue, because the move constructor itself has an rvalue reference parameter. When control flow reaches the closing brace of operator=, source goes out of scope, releasing the old resource automatically.

The move assignment operator transfers ownership of a managed resource into the current object, releasing the old resource. The move-and-swap idiom simplifies the implementation.

Moving from lvalues

Sometimes, we want to move from lvalues. That is, sometimes we want the compiler to treat an lvalue as if it were an rvalue, so it can invoke the move constructor, even though it could be potentially unsafe. For this purpose, C++11 offers a standard library function template called std::move inside the header <utility>. This name is a bit unfortunate, because std::move simply casts an lvalue to an rvalue; it does not move anything by itself. It merely enables moving. Maybe it should have been named std::cast_to_rvalue or std::enable_move, but we are stuck with the name by now.

Here is how you explicitly move from an lvalue:

unique_ptr<Shape> a(new Triangle);
unique_ptr<Shape> b(a);              // still an error
unique_ptr<Shape> c(std::move(a));   // okay

Note that after the third line, a no longer owns a triangle. That's okay, because by explicitly writing std::move(a), we made our intentions clear: "Dear constructor, do whatever you want with a in order to initialize c; I don't care about a anymore. Feel free to have your way with a."

std::move(some_lvalue) casts an lvalue to an rvalue, thus enabling a subsequent move.

Xvalues

Note that even though std::move(a) is an rvalue, its evaluation does not create a temporary object. This conundrum forced the committee to introduce a third value category. Something that can be bound to an rvalue reference, even though it is not an rvalue in the traditional sense, is called an xvalue (eXpiring value). The traditional rvalues were renamed to prvalues (Pure rvalues).

Both prvalues and xvalues are rvalues. Xvalues and lvalues are both glvalues (Generalized lvalues). The relationships are easier to grasp with a diagram:

        expressions
          /     \
         /       \
        /         \
    glvalues   rvalues
      /  \       /  \
     /    \     /    \
    /      \   /      \
lvalues   xvalues   prvalues

Note that only xvalues are really new; the rest is just due to renaming and grouping.

C++98 rvalues are known as prvalues in C++11. Mentally replace all occurrences of "rvalue" in the preceding paragraphs with "prvalue".

Moving out of functions

So far, we have seen movement into local variables, and into function parameters. But moving is also possible in the opposite direction. If a function returns by value, some object at call site (probably a local variable or a temporary, but could be any kind of object) is initialized with the expression after the return statement as an argument to the move constructor:

unique_ptr<Shape> make_triangle()
{
    return unique_ptr<Shape>(new Triangle);
}          \-----------------------------/
                  |
                  | temporary is moved into c
                  |
                  v
unique_ptr<Shape> c(make_triangle());

Perhaps surprisingly, automatic objects (local variables that are not declared as static) can also be implicitly moved out of functions:

unique_ptr<Shape> make_square()
{
    unique_ptr<Shape> result(new Square);
    return result;   // note the missing std::move
}

How come the move constructor accepts the lvalue result as an argument? The scope of result is about to end, and it will be destroyed during stack unwinding. Nobody could possibly complain afterward that result had changed somehow; when control flow is back at the caller, result does not exist anymore! For that reason, C++11 has a special rule that allows returning automatic objects from functions without having to write std::move. In fact, you should never use std::move to move automatic objects out of functions, as this inhibits the "named return value optimization" (NRVO).

Never use std::move to move automatic objects out of functions.

Note that in both factory functions, the return type is a value, not an rvalue reference. Rvalue references are still references, and as always, you should never return a reference to an automatic object; the caller would end up with a dangling reference if you tricked the compiler into accepting your code, like this:

unique_ptr<Shape>&& flawed_attempt()   // DO NOT DO THIS!
{
    unique_ptr<Shape> very_bad_idea(new Square);
    return std::move(very_bad_idea);   // WRONG!
}

Never return automatic objects by rvalue reference. Moving is exclusively performed by the move constructor, not by std::move, and not by merely binding an rvalue to an rvalue reference.

Moving into members

Sooner or later, you are going to write code like this:

class Foo
{
    unique_ptr<Shape> member;

public:

    Foo(unique_ptr<Shape>&& parameter)
    : member(parameter)   // error
    {}
};

Basically, the compiler will complain that parameter is an lvalue. If you look at its type, you see an rvalue reference, but an rvalue reference simply means "a reference that is bound to an rvalue"; it does not mean that the reference itself is an rvalue! Indeed, parameter is just an ordinary variable with a name. You can use parameter as often as you like inside the body of the constructor, and it always denotes the same object. Implicitly moving from it would be dangerous, hence the language forbids it.

A named rvalue reference is an lvalue, just like any other variable.

The solution is to manually enable the move:

class Foo
{
    unique_ptr<Shape> member;

public:

    Foo(unique_ptr<Shape>&& parameter)
    : member(std::move(parameter))   // note the std::move
    {}
};

You could argue that parameter is not used anymore after the initialization of member. Why is there no special rule to silently insert std::move just as with return values? Probably because it would be too much burden on the compiler implementors. For example, what if the constructor body was in another translation unit? By contrast, the return value rule simply has to check the symbol tables to determine whether or not the identifier after the return keyword denotes an automatic object.

You can also pass the parameter by value. For move-only types like unique_ptr, it seems there is no established idiom yet. Personally, I prefer to pass by value, as it causes less clutter in the interface.

Special member functions

C++98 implicitly declares three special member functions on demand, that is, when they are needed somewhere: the copy constructor, the copy assignment operator, and the destructor.

X::X(const X&);              // copy constructor
X& X::operator=(const X&);   // copy assignment operator
X::~X();                     // destructor

Rvalue references went through several versions. Since version 3.0, C++11 declares two additional special member functions on demand: the move constructor and the move assignment operator. Note that neither VC10 nor VC11 conforms to version 3.0 yet, so you will have to implement them yourself.

X::X(X&&);                   // move constructor
X& X::operator=(X&&);        // move assignment operator

These two new special member functions are only implicitly declared if none of the special member functions are declared manually. Also, if you declare your own move constructor or move assignment operator, neither the copy constructor nor the copy assignment operator will be declared implicitly.

What do these rules mean in practice?

If you write a class without unmanaged resources, there is no need to declare any of the five special member functions yourself, and you will get correct copy semantics and move semantics for free. Otherwise, you will have to implement the special member functions yourself. Of course, if your class does not benefit from move semantics, there is no need to implement the special move operations.

Note that the copy assignment operator and the move assignment operator can be fused into a single, unified assignment operator, taking its argument by value:

X& X::operator=(X source)    // unified assignment operator
{
    swap(source);            // see my first answer for an explanation
    return *this;
}

This way, the number of special member functions to implement drops from five to four. There is a tradeoff between exception-safety and efficiency here, but I am not an expert on this issue.

Forwarding references (previously known as Universal references)

Consider the following function template:

template<typename T>
void foo(T&&);

You might expect T&& to only bind to rvalues, because at first glance, it looks like an rvalue reference. As it turns out though, T&& also binds to lvalues:

foo(make_triangle());   // T is unique_ptr<Shape>, T&& is unique_ptr<Shape>&&
unique_ptr<Shape> a(new Triangle);
foo(a);                 // T is unique_ptr<Shape>&, T&& is unique_ptr<Shape>&

If the argument is an rvalue of type X, T is deduced to be X, hence T&& means X&&. This is what anyone would expect. But if the argument is an lvalue of type X, due to a special rule, T is deduced to be X&, hence T&& would mean something like X& &&. But since C++ still has no notion of references to references, the type X& && is collapsed into X&. This may sound confusing and useless at first, but reference collapsing is essential for perfect forwarding (which will not be discussed here).

T&& is not an rvalue reference, but a forwarding reference. It also binds to lvalues, in which case T and T&& are both lvalue references.

If you want to constrain a function template to rvalues, you can combine SFINAE with type traits:

#include <type_traits>

template<typename T>
typename std::enable_if<std::is_rvalue_reference<T&&>::value, void>::type
foo(T&&);

Implementation of move

Now that you understand reference collapsing, here is how std::move is implemented:

template<typename T>
typename std::remove_reference<T>::type&&
move(T&& t)
{
    return static_cast<typename std::remove_reference<T>::type&&>(t);
}

As you can see, move accepts any kind of parameter thanks to the forwarding reference T&&, and it returns an rvalue reference. The std::remove_reference<T>::type meta-function call is necessary because otherwise, for lvalues of type X, the return type would be X& &&, which would collapse into X&. Since t is always an lvalue (remember that a named rvalue reference is an lvalue), but we want to bind t to an rvalue reference, we have to explicitly cast t to the correct return type. The call of a function that returns an rvalue reference is itself an xvalue. Now you know where xvalues come from ;)

The call of a function that returns an rvalue reference, such as std::move, is an xvalue.

Note that returning by rvalue reference is fine in this example, because t does not denote an automatic object, but instead an object that was passed in by the caller.

Difference between RegisterStartupScript and RegisterClientScriptBlock?

Here's an old discussion thread where I listed the main differences and the conditions in which you should use each of these methods. I think you may find it useful to go through the discussion.

To explain the differences as relevant to your posted example:

a. When you use RegisterStartupScript, it will render your script after all the elements in the page (right before the form's end tag). This enables the script to call or reference page elements without the possibility of it not finding them in the Page's DOM.

Here is the rendered source of the page when you invoke the RegisterStartupScript method:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
        <div>
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        </div>
        <div> <span id="lblDisplayDate">Label</span>
            <br />
            <input type="submit" name="btnPostback" value="Register Startup Script" id="btnPostback" />
            <br />
            <input type="submit" name="btnPostBack2" value="Register" id="btnPostBack2" />
        </div>
        <div>
            <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="someViewstategibberish" />
        </div>
        <!-- Note this part -->
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
            lbl.style.color = 'red';
        </script>
    </form>
    <!-- Note this part -->
</body>
</html>

b. When you use RegisterClientScriptBlock, the script is rendered right after the Viewstate tag, but before any of the page elements. Since this is a direct script (not a function that can be called, it will immediately be executed by the browser. But the browser does not find the label in the Page's DOM at this stage and hence you should receive an "Object not found" error.

Here is the rendered source of the page when you invoke the RegisterClientScriptBlock method:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
        <div>
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        </div>
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
            // Error is thrown in the next line because lbl is null.
            lbl.style.color = 'green';

Therefore, to summarize, you should call the latter method if you intend to render a function definition. You can then render the call to that function using the former method (or add a client side attribute).

Edit after comments:


For instance, the following function would work:

protected void btnPostBack2_Click(object sender, EventArgs e) 
{ 
  System.Text.StringBuilder sb = new System.Text.StringBuilder(); 
  sb.Append("<script language='javascript'>function ChangeColor() {"); 
  sb.Append("var lbl = document.getElementById('lblDisplayDate');"); 
  sb.Append("lbl.style.color='green';"); 
  sb.Append("}</script>"); 

  //Render the function definition. 
  if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock")) 
  {
    ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock", sb.ToString()); 
  }

  //Render the function invocation. 
  string funcCall = "<script language='javascript'>ChangeColor();</script>"; 

  if (!ClientScript.IsStartupScriptRegistered("JSScript"))
  { 
    ClientScript.RegisterStartupScript(this.GetType(), "JSScript", funcCall); 
  } 
} 

How to capitalize the first letter in a String in Ruby

Well, just so we know how to capitalize only the first letter and leave the rest of them alone, because sometimes that is what is desired:

['NASA', 'MHz', 'sputnik'].collect do |word|
  letters = word.split('')
  letters.first.upcase!
  letters.join
end

 => ["NASA", "MHz", "Sputnik"]

Calling capitalize would result in ["Nasa", "Mhz", "Sputnik"].

Submitting a form on 'Enter' with jQuery?

Return false to prevent the keystroke from continuing.

Python Pandas iterate over rows and access column names

I also like itertuples()

for row in df.itertuples():
    print(row.A)
    print(row.Index)

since row is a named tuples, if you meant to access values on each row this should be MUCH faster

speed run :

df = pd.DataFrame([x for x in range(1000*1000)], columns=['A'])
st=time.time()
for index, row in df.iterrows():
    row.A
print(time.time()-st)
45.05799984931946

st=time.time()
for row in df.itertuples():
    row.A
print(time.time() - st)
0.48400020599365234

Vue template or render function not defined yet I am using neither?

The reason you're receiving that error is that you're using the runtime build which doesn't support templates in HTML files as seen here vuejs.org

In essence what happens with vue loaded files is that their templates are compile time converted into render functions where as your base function was trying to compile from your html element.

How to chain scope queries with OR instead of AND?

Rails 4 + Scope + Arel

class Creature < ActiveRecord::Base
    scope :is_good_pet, -> {
        where(
            arel_table[:is_cat].eq(true)
            .or(arel_table[:is_dog].eq(true))
            .or(arel_table[:eats_children].eq(false))
        )
    }
end

I tried chaining named scopes with .or and no luck, but this worked for finding anything with those booleans set. Generates SQL like

SELECT 'CREATURES'.* FROM 'CREATURES' WHERE ((('CREATURES'.'is_cat' = 1 OR 'CREATURES'.'is_dog' = 1) OR 'CREATURES'.'eats_children' = 0))

Javascript how to split newline

Just

var ks = $('#keywords').val().split(/\r\n|\n|\r/);

will work perfectly.

Be sure \r\n is placed at the leading of the RegExp string, cause it will be tried first.

Replace duplicate spaces with a single space in T-SQL

Here is a simple function I created for cleaning any spaces before or after, and multiple spaces within a string. It gracefully handles up to about 108 spaces in a single stretch and as many blocks as there are in the string. You can increase that by factors of 8 by adding additional lines with larger chunks of spaces if you need to. It seems to perform quickly and has not caused any problems in spite of it's generalized use in a large application.

CREATE FUNCTION [dbo].[fnReplaceMultipleSpaces] (@StrVal AS VARCHAR(4000)) 
RETURNS VARCHAR(4000) 
AS 
BEGIN

    SET @StrVal = Ltrim(@StrVal)
    SET @StrVal = Rtrim(@StrVal)

    SET @StrVal = REPLACE(@StrVal, '                ', ' ')  -- 16 spaces
    SET @StrVal = REPLACE(@StrVal, '        ', ' ')  -- 8 spaces
    SET @StrVal = REPLACE(@StrVal, '    ', ' ')  -- 4 spaces
    SET @StrVal = REPLACE(@StrVal, '  ', ' ')  -- 2 spaces
    SET @StrVal = REPLACE(@StrVal, '  ', ' ')  -- 2 spaces (for odd leftovers)

RETURN @StrVal

END

How do I fix a NoSuchMethodError?

I was having your problem, and this is how I fixed it. The following steps are a working way to add a library. I had done the first two steps right, but I hadn't done the last one by dragging the ".jar" file direct from the file system into the "lib" folder on my eclipse project. Additionally, I had to remove the previous version of the library from both the build path and the "lib" folder.

Step 1 - Add .jar to build path

enter image description here

Step 2 - Associate sources and javadocs (optional)

enter image description here

Step 3 - Actually drag .jar file into "lib" folder (not optional)

enter image description here

TypeError: '<=' not supported between instances of 'str' and 'int'

input() by default takes the input in form of strings.

if (0<= vote <=24):

vote takes a string input (suppose 4,5,etc) and becomes uncomparable.

The correct way is: vote = int(input("Enter your message")will convert the input to integer (4 to 4 or 5 to 5 depending on the input)

how to calculate percentage in python

You're performing an integer division. Append a .0 to the number literals:

per=float(tota)*(100.0/500.0)

In Python 2.7 the division 100/500==0.

As pointed out by @unwind, the float() call is superfluous since a multiplication/division by a float returns a float:

per= tota*100.0 / 500

Split comma separated column data into additional columns

If the number of fields in the CSV is constant then you could do something like this:

select a[1], a[2], a[3], a[4]
from (
    select regexp_split_to_array('a,b,c,d', ',')
) as dt(a)

For example:

=> select a[1], a[2], a[3], a[4] from (select regexp_split_to_array('a,b,c,d', ',')) as dt(a);
 a | a | a | a 
---+---+---+---
 a | b | c | d
(1 row)

If the number of fields in the CSV is not constant then you could get the maximum number of fields with something like this:

select max(array_length(regexp_split_to_array(csv, ','), 1))
from your_table

and then build the appropriate a[1], a[2], ..., a[M] column list for your query. So if the above gave you a max of 6, you'd use this:

select a[1], a[2], a[3], a[4], a[5], a[6]
from (
    select regexp_split_to_array(csv, ',')
    from your_table
) as dt(a)

You could combine those two queries into a function if you wanted.

For example, give this data (that's a NULL in the last row):

=> select * from csvs;
     csv     
-------------
 1,2,3
 1,2,3,4
 1,2,3,4,5,6

(4 rows)

=> select max(array_length(regexp_split_to_array(csv, ','), 1)) from csvs;
 max 
-----
   6
(1 row)

=> select a[1], a[2], a[3], a[4], a[5], a[6] from (select regexp_split_to_array(csv, ',') from csvs) as dt(a);
 a | a | a | a | a | a 
---+---+---+---+---+---
 1 | 2 | 3 |   |   | 
 1 | 2 | 3 | 4 |   | 
 1 | 2 | 3 | 4 | 5 | 6
   |   |   |   |   | 
(4 rows)

Since your delimiter is a simple fixed string, you could also use string_to_array instead of regexp_split_to_array:

select ...
from (
    select string_to_array(csv, ',')
    from csvs
) as dt(a);

Thanks to Michael for the reminder about this function.

You really should redesign your database schema to avoid the CSV column if at all possible. You should be using an array column or a separate table instead.

ERROR 1396 (HY000): Operation CREATE USER failed for 'jack'@'localhost'

I faced this issue today, and I resolved it by doing the following steps:

1) manually inserting that troubling user providing value of mandatory fields into mysql.user

mysql> insert into user(Host, User, Password, ssl_type) 
   values ('localhost', 'jack', 'jack', 'ANY');

2)

mysql> select * from user where User = 'jack';
   1 row in set (0.00 sec)

3) A.

mysql> drop user jack;
Query OK, 0 rows affected (0.00 sec)

B. mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

C. mysql> create user 'jack' identified by 'jack';
Query OK, 0 rows affected (0.00 sec)

D. mysql> select Host, User, Password, ssl_type  from user where User = 'jack';
+-----------+-----------+-------------------------------------------+----------+
| Host      | User      | Password                                  | ssl_type |
+-----------+-----------+-------------------------------------------+----------+
| localhost | jack      | jack                                      | ANY      |
| %         | jack      | *45BB7035F11303D8F09B2877A00D2510DCE4D758 |          |
+-----------+-----------+-------------------------------------------+----------+
2 rows in set (0.00 sec)

4) A.

mysql> delete from user 
 where User = 'nyse_user' and 
       Host = 'localhost' and 
       Password ='nyse';
Query OK, 1 row affected (0.00 sec)

B.

mysql> select Host, User, Password, ssl_type  from user where User = 'jack';
+------+-----------+-------------------------------------------+----------+
| Host | User      | Password                                  | ssl_type |
+------+-----------+-------------------------------------------+----------+
| %    | jack      | *45BB7035F11303D8F09B2877A00D2510DCE4D758 |          |
+------+-----------+-------------------------------------------+----------+
1 row in set (0.00 sec)

Hope this helps.

Is it possible to make an HTML anchor tag not clickable/linkable using CSS?

The answer is:

<a href="page.html" onclick="return false">page link</a>

get name of a variable or parameter

Pre C# 6.0 solution

You can use this to get a name of any provided member:

public static class MemberInfoGetting
{
    public static string GetMemberName<T>(Expression<Func<T>> memberExpression)
    {
        MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
        return expressionBody.Member.Name;
    }
}

To get name of a variable:

string testVariable = "value";
string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => testVariable);

To get name of a parameter:

public class TestClass
{
    public void TestMethod(string param1, string param2)
    {
        string nameOfParam1 = MemberInfoGetting.GetMemberName(() => param1);
    }
}

C# 6.0 and higher solution

You can use the nameof operator for parameters, variables and properties alike:

string testVariable = "value";
string nameOfTestVariable = nameof(testVariable);

Add left/right horizontal padding to UILabel

Sometimes it's convenient to use UNICODE partial spaces to achieve alignment while prototyping. This can be handy in prototyping, proof-of-concept, or just to defer implementation of graphics algorithms.

If you use UNICODE spaces for convenience, be aware that at least one of the UNICODE spaces has a size based on the font it is displayed from, specifically the actual space character itself (U+0020, ASCII 32)

If you're using the default iOS system font in a UILabel, the default System font characteristics could change in a subsequent iOS release and suddenly introduce an unwanted misalignment by changing your app's precise spacing. This can and does happen, for example the "San Francisco" font replaced a previous iOS system font in an iOS release.

UNICODE easy to specify in Swift, for example:

let six_per_em_space = "\u{2006}"

Alternatively, cut/paste the space from an HTML page directly into the UILabel's text field in Interface Builder.

Note: Attached pic is a screenshot, not HTML, so visit the linked page if you want to cut/paste the space.

UNICODE spaces

init-param and context-param

Consider the below definition in web.xml

<servlet>
    <servlet-name>HelloWorld</servlet-name>
    <servlet-class>TestServlet</servlet-class>
    <init-param>
        <param-name>myprop</param-name>
        <param-value>value</param-value>
    </init-param>
</servlet>

You can see that init-param is defined inside a servlet element. This means it is only available to the servlet under declaration and not to other parts of the web application. If you want this parameter to be available to other parts of the application say a JSP this needs to be explicitly passed to the JSP. For instance passed as request.setAttribute(). This is highly inefficient and difficult to code.

So if you want to get access to global values from anywhere within the application without explicitly passing those values, you need to use Context Init parameters.

Consider the following definition in web.xml

 <web-app>
      <context-param>
           <param-name>myprop</param-name>
           <param-value>value</param-value>
      </context-param>
 </web-app>

This context param is available to all parts of the web application and it can be retrieved from the Context object. For instance, getServletContext().getInitParameter(“dbname”);

From a JSP you can access the context parameter using the application implicit object. For example, application.getAttribute(“dbname”);

SQL - Create view from multiple tables

Union is not what you want. You want to use joins to create single rows. It's a little unclear what constitutes a unique row in your tables and how they really relate to each other and it's also unclear if one table will have rows for every country in every year. But I think this will work:

CREATE VIEW V AS (

  SELECT i.country,i.year,p.pop,f.food,i.income FROM
    INCOME i
  LEFT JOIN 
    POP p 
  ON
    i.country=p.country
  LEFT JOIN
    Food f
  ON 
    i.country=f.country
  WHERE 
    i.year=p.year
  AND
    i.year=f.year
);

The left (outer) join will return rows from the first table even if there are no matches in the second. I've written this assuming you would have a row for every country for every year in the income table. If you don't things get a bit hairy as MySQL does not have built in support for FULL OUTER JOINs last I checked. There are ways to simulate it, and they would involve unions. This article goes into some depth on the subject: http://www.xaprb.com/blog/2006/05/26/how-to-write-full-outer-join-in-mysql/

Git says remote ref does not exist when I delete remote branch

git branch -a will list the branches in your local and not the branches in your remote.

And the error error: unable to delete 'remotes/origin/test': remote ref does not exist means you don't have a branch in that name in your remote but the branch exists in your local.

Convert XmlDocument to String

you can use xmlDoc.InnerXml property to get xml in string

What is the function of FormulaR1C1?

I find the most valuable feature of .FormulaR1C1 is sheer speed. Versus eg a couple of very large loops filling some data into a sheet, If you can convert what you are doing into a .FormulaR1C1 form. Then a single operation eg myrange.FormulaR1C1 = "my particular formuala" is blindingly fast (can be a thousand times faster). No looping and counting - just fill the range at high speed.

How to refresh app upon shaking the device?

I have tried several implementations, but would like to share my own. It uses G-force as unit for the threshold calculation. It makes it a bit easier to understand what is going on, and also with setting a good threshold.

It simply registers a increase in G force and triggers the listener if it exceeds the threshold. It doesn't use any direction thresholds, cause you don't really need that if you just want to register a good shake.

Of-course you need the standard registering and UN-registering of this listener in the Activity.

Also, to check what threshold you need, I recommend the following app (I am not in any way connected to that app)

    public class UmitoShakeEventListener implements SensorEventListener {

    /**
     * The gforce that is necessary to register as shake. (Must include 1G
     * gravity)
     */
    private final float shakeThresholdInGForce = 2.25F;

    private final float gravityEarth = SensorManager.GRAVITY_EARTH;

    private OnShakeListener listener;

    public void setOnShakeListener(OnShakeListener listener) {
        this.listener = listener;
    }

    public interface OnShakeListener {
        public void onShake();
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // ignore

    }

    @Override
    public void onSensorChanged(SensorEvent event) {

        if (listener != null) {
            float x = event.values[0];
            float y = event.values[1];
            float z = event.values[2];

            float gX = x / gravityEarth;
            float gY = y / gravityEarth;
            float gZ = z / gravityEarth;

            //G-Force will be 1 when there is no movement. (gravity)
            float gForce = FloatMath.sqrt(gX * gX + gY * gY + gZ * gZ); 



            if (gForce > shakeThresholdInGForce) {
                listener.onShake();

            }
        }

    }

}

What's the difference between HEAD, working tree and index, in Git?

Your working tree is what is actually in the files that you are currently working on.

HEAD is a pointer to the branch or commit that you last checked out, and which will be the parent of a new commit if you make it. For instance, if you're on the master branch, then HEAD will point to master, and when you commit, that new commit will be a descendent of the revision that master pointed to, and master will be updated to point to the new commit.

The index is a staging area where the new commit is prepared. Essentially, the contents of the index are what will go into the new commit (though if you do git commit -a, this will automatically add all changes to files that Git knows about to the index before committing, so it will commit the current contents of your working tree). git add will add or update files from the working tree into your index.

How to check if an integer is within a range?

There is no builtin function, but you can easily achieve it by calling the functions min() and max() appropriately.

// Limit integer between 1 and 100000
$var = max(min($var, 100000), 1);

Best way to pass parameters to jQuery's .load()

As Davide Gualano has been told. This one

$("#myDiv").load("myScript.php?var=x&var2=y&var3=z")

use GET method for sending the request, and this one

$("#myDiv").load("myScript.php", {var:x, var2:y, var3:z})

use POST method for sending the request. But any limitation that is applied to each method (post/get) is applied to the alternative usages that has been mentioned in the question.

For example: url length limits the amount of sending data in GET method.

Detect changes in the DOM

Ultimate approach so far, with smallest code:

(IE9+, FF, Webkit)

Using MutationObserver and falling back to the deprecated Mutation events if needed:
(Example below if only for DOM changes concerning nodes appended or removed)

_x000D_
_x000D_
var observeDOM = (function(){
  var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

  return function( obj, callback ){
    if( !obj || obj.nodeType !== 1 ) return; 

    if( MutationObserver ){
      // define a new observer
      var mutationObserver = new MutationObserver(callback)

      // have the observer observe foo for changes in children
      mutationObserver.observe( obj, { childList:true, subtree:true })
      return mutationObserver
    }
    
    // browser support fallback
    else if( window.addEventListener ){
      obj.addEventListener('DOMNodeInserted', callback, false)
      obj.addEventListener('DOMNodeRemoved', callback, false)
    }
  }
})()


//------------< DEMO BELOW >----------------

// add item
var itemHTML = "<li><button>list item (click to delete)</button></li>",
    listElm = document.querySelector('ol');

document.querySelector('body > button').onclick = function(e){
  listElm.insertAdjacentHTML("beforeend", itemHTML);
}

// delete item
listElm.onclick = function(e){
  if( e.target.nodeName == "BUTTON" )
    e.target.parentNode.parentNode.removeChild(e.target.parentNode);
}
    
// Observe a specific DOM element:
observeDOM( listElm, function(m){ 
   var addedNodes = [], removedNodes = [];

   m.forEach(record => record.addedNodes.length & addedNodes.push(...record.addedNodes))
   
   m.forEach(record => record.removedNodes.length & removedNodes.push(...record.removedNodes))

  console.clear();
  console.log('Added:', addedNodes, 'Removed:', removedNodes);
});


// Insert 3 DOM nodes at once after 3 seconds
setTimeout(function(){
   listElm.removeChild(listElm.lastElementChild);
   listElm.insertAdjacentHTML("beforeend", Array(4).join(itemHTML));
}, 3000);
_x000D_
<button>Add Item</button>
<ol>
  <li><button>list item (click to delete)</button></li>
  <li><button>list item (click to delete)</button></li>
  <li><button>list item (click to delete)</button></li>
  <li><button>list item (click to delete)</button></li>
  <li><em>&hellip;More will be added after 3 seconds&hellip;</em></li>
</ol>
_x000D_
_x000D_
_x000D_

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

I know this is old but this answer still applies to newer Core releases.

If by chance your DbContext implementation is in a different project than your startup project and you run ef migrations, you'll see this error because the command will not be able to invoke the application's startup code leaving your database provider without a configuration. To fix it, you have to let ef migrations know where they're at.

dotnet ef migrations add MyMigration [-p <relative path to DbContext project>, -s <relative path to startup project>]

Both -s and -p are optionals that default to the current folder.

Execute php file from another php

exec('wget http://<url to the php script>') worked for me.

It enable me to integrate two php files that were designed as web pages and run them as code to do work without affecting the calling page

If you can decode JWT, how are they secure?

The contents in a json web token (JWT) are not inherently secure, but there is a built-in feature for verifying token authenticity. A JWT is three hashes separated by periods. The third is the signature. In a public/private key system, the issuer signs the token signature with a private key which can only be verified by its corresponding public key.

It is important to understand the distinction between issuer and verifier. The recipient of the token is responsible for verifying it.

There are two critical steps in using JWT securely in a web application: 1) send them over an encrypted channel, and 2) verify the signature immediately upon receiving it. The asymmetric nature of public key cryptography makes JWT signature verification possible. A public key verifies a JWT was signed by its matching private key. No other combination of keys can do this verification, thus preventing impersonation attempts. Follow these two steps and we can guarantee with mathematical certainty the authenticity of a JWT.

More reading: How does a public key verify a signature?

DB2 Timestamp select statement

@bhamby is correct. By leaving the microseconds off of your timestamp value, your query would only match on a usagetime of 2012-09-03 08:03:06.000000

If you don't have the complete timestamp value captured from a previous query, you can specify a ranged predicate that will match on any microsecond value for that time:

...WHERE id = 1 AND usagetime BETWEEN '2012-09-03 08:03:06' AND '2012-09-03 08:03:07'

or

...WHERE id = 1 AND usagetime >= '2012-09-03 08:03:06' 
   AND usagetime < '2012-09-03 08:03:07'

How set background drawable programmatically in Android

Try this code:

Drawable thumb = ContextCompat.getDrawable(getActivity(), R.mipmap.cir_32);
mSeekBar.setThumb(thumb);

Excel function to make SQL-like queries on worksheet data?

If you want run formula on worksheet by function that execute SQL statement then use Add-in A-Tools

Example, function BS_SQL("SELECT ..."):

enter image description here

PHP ini file_get_contents external url

The setting you are looking for is allow_url_fopen.

You have two ways of getting around it without changing php.ini, one of them is to use fsockopen(), and the other is to use cURL.

I recommend using cURL over file_get_contents() anyways, since it was built for this.

What is “2's Complement”?

To bitwise complement a number is to flip all the bits in it. To two’s complement it, we flip all the bits and add one.

Using 2’s complement representation for signed integers, we apply the 2’s complement operation to convert a positive number to its negative equivalent and vice versa. So using nibbles for an example, 0001 (1) becomes 1111 (-1) and applying the op again, returns to 0001.

The behaviour of the operation at zero is advantageous in giving a single representation for zero without special handling of positive and negative zeroes. 0000 complements to 1111, which when 1 is added. overflows to 0000, giving us one zero, rather than a positive and a negative one.

A key advantage of this representation is that the standard addition circuits for unsigned integers produce correct results when applied to them. For example adding 1 and -1 in nibbles: 0001 + 1111, the bits overflow out of the register, leaving behind 0000.

For a gentle introduction, the wonderful Computerphile have produced a video on the subject.

Decoding a Base64 string in Java

Modify the package you're using:

import org.apache.commons.codec.binary.Base64;

And then use it like this:

byte[] decoded = Base64.decodeBase64("YWJjZGVmZw==");
System.out.println(new String(decoded, "UTF-8") + "\n");

How to delete an element from a Slice in Golang

Minor point (code golf), but in the case where order does not matter you don't need to swap the values. Just overwrite the array position being removed with a duplicate of the last position and then return a truncated array.

func remove(s []int, i int) []int {
    s[i] = s[len(s)-1]
    return s[:len(s)-1]
}

Same result.

SQL Server principal "dbo" does not exist,

After restoring a Database from SQL2016 to SQL2019, I had the same issue when I try to access Database Diagrams. I had the correct Database owner already but owner of Files was empty. Once I set that, it worked properly...

enter image description here

Conditionally formatting cells if their value equals any value of another column

Another simpler solution is to use this formula in the conditional formatting (apply to column A):

=COUNTIF(B:B,A1)

Regards!

module.exports vs. export default in Node.js and ES6

You need to configure babel correctly in your project to use export default and export const foo

npm install --save-dev @babel/plugin-proposal-export-default-from

then add below configration in .babelrc

"plugins": [ 
       "@babel/plugin-proposal-export-default-from"
      ]

clk'event vs rising_edge()

The linked comment is incorrect : 'L' to '1' will produce a rising edge.

In addition, if your clock signal transitions from 'H' to '1', rising_edge(clk) will (correctly) not trigger while (clk'event and clk = '1') (incorrectly) will.

Granted, that may look like a contrived example, but I have seen clock waveforms do that in real hardware, due to failures elsewhere.

Remove secure warnings (_CRT_SECURE_NO_WARNINGS) from projects by default in Visual Studio

my two cents for VS 2017:

I can confirm it works in stdafx.h both in these styles:

a)

#pragma once
#define _CRT_SECURE_NO_WARNINGS 1 
#define _WINSOCK_DEPRECATED_NO_WARNINGS 1 

b)

#define _CRT_SECURE_NO_WARNINGS 1 
#define _WINSOCK_DEPRECATED_NO_WARNINGS 1 
#pragma once

(I have added another define for MSDN network calls..) Of course I do prefer a).

I can confirm that: #define _CRT_SECURE_NO_WARNINGS (without a value) DOES NOT WORK.

PS the real point is to put these defines BEFORE declarations of functions, i.e. before *.h

Convert json to a C# array?

Old question but worth adding an answer if using .NET Core 3.0 or later. JSON serialization/deserialization is built into the framework (System.Text.Json), so you don't have to use third party libraries any more. Here's an example based off the top answer given by @Icarus

using System;
using System.Collections.Generic;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var json = "[{\"Name\":\"John Smith\", \"Age\":35}, {\"Name\":\"Pablo Perez\", \"Age\":34}]";

            // use the built in Json deserializer to convert the string to a list of Person objects
            var people = System.Text.Json.JsonSerializer.Deserialize<List<Person>>(json);

            foreach (var person in people)
            {
                Console.WriteLine(person.Name + " is " + person.Age + " years old.");
            }
        }

        public class Person
        {
            public int Age { get; set; }
            public string Name { get; set; }
        }
    }
}

Convert unix time to readable date in pandas dataframe

These appear to be seconds since epoch.

In [20]: df = DataFrame(data['values'])

In [21]: df.columns = ["date","price"]

In [22]: df
Out[22]: 
<class 'pandas.core.frame.DataFrame'>
Int64Index: 358 entries, 0 to 357
Data columns (total 2 columns):
date     358  non-null values
price    358  non-null values
dtypes: float64(1), int64(1)

In [23]: df.head()
Out[23]: 
         date  price
0  1349720105  12.08
1  1349806505  12.35
2  1349892905  12.15
3  1349979305  12.19
4  1350065705  12.15
In [25]: df['date'] = pd.to_datetime(df['date'],unit='s')

In [26]: df.head()
Out[26]: 
                 date  price
0 2012-10-08 18:15:05  12.08
1 2012-10-09 18:15:05  12.35
2 2012-10-10 18:15:05  12.15
3 2012-10-11 18:15:05  12.19
4 2012-10-12 18:15:05  12.15

In [27]: df.dtypes
Out[27]: 
date     datetime64[ns]
price           float64
dtype: object

warning: control reaches end of non-void function [-Wreturn-type]

You can also use EXIT_SUCCESS instead of return 0;. The macro EXIT_SUCCESS is actually defined as zero, but makes your program more readable.

INSTALL_FAILED_NO_MATCHING_ABIS when install apk

In my case, in a xamarin project, in visual studio error removed by selecting properties --> Android Options and check Use Share run Times and Use Fast Deployment, in some cases one of them enter image description here

Prevent form redirect OR refresh on submit?

An alternative solution would be to not use form tag and handle click event on submit button through jquery. This way there wont be any page refresh but at the same time there is a downside that "enter" button for submission wont work and also on mobiles you wont get a go button( a style in some mobiles). So stick to use of form tag and use the accepted answer.

Converting a datetime string to timestamp in Javascript

Date.parse() isn't a constructor, its a static method.

So, just use

var timeInMillis = Date.parse(s);

instead of

var timeInMillis = new Date.parse(s);

In-place edits with sed on OS X

You can use:

sed -i -e 's/<string-to-find>/<string-to-replace>/' <your-file-path>

Example:

sed -i -e 's/Hello/Bye/' file.txt

This works flawless in Mac.

Tracking Google Analytics Page Views with AngularJS

In your index.html, copy and paste the ga snippet but remove the line ga('send', 'pageview');

<!-- Google Analytics: change UA-XXXXX-X to be your site's ID -->
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-XXXXXXXX-X');
</script>

I like to give it it's own factory file my-google-analytics.js with self injection:

angular.module('myApp')
  .factory('myGoogleAnalytics', [
    '$rootScope', '$window', '$location', 
    function ($rootScope, $window, $location) {

      var myGoogleAnalytics = {};

      /**
       * Set the page to the current location path
       * and then send a pageview to log path change.
       */
      myGoogleAnalytics.sendPageview = function() {
        if ($window.ga) {
          $window.ga('set', 'page', $location.path());
          $window.ga('send', 'pageview');
        }
      }

      // subscribe to events
      $rootScope.$on('$viewContentLoaded', myGoogleAnalytics.sendPageview);

      return myGoogleAnalytics;
    }
  ])
  .run([
    'myGoogleAnalytics', 
    function(myGoogleAnalytics) {
        // inject self
    }
  ]);

How can I get a JavaScript stack trace when I throw an exception?

Here is an answer that gives you max performance (IE 6+) and max compatibility. Compatible with IE 6!

_x000D_
_x000D_
    function stacktrace( log_result ) {_x000D_
     var trace_result;_x000D_
    // IE 6 through 9 compatibility_x000D_
    // this is NOT an all-around solution because_x000D_
    // the callee property of arguments is depredicated_x000D_
    /*@cc_on_x000D_
     // theese fancy conditinals make this code only run in IE_x000D_
     trace_result = (function st2(fTmp) {_x000D_
      // credit to Eugene for this part of the code_x000D_
      return !fTmp ? [] :_x000D_
       st2(fTmp.caller).concat([fTmp.toString().split('(')[0].substring(9) + '(' + fTmp.arguments.join(',') + ')']);_x000D_
     })(arguments.callee.caller);_x000D_
     if (log_result) // the ancient way to log to the console_x000D_
      Debug.write( trace_result );_x000D_
     return trace_result;_x000D_
    @*/_x000D_
     console = console || Console; // just in case_x000D_
     if (!(console && console.trace) || !log_result){_x000D_
      // for better performance in IE 10_x000D_
      var STerror=new Error();_x000D_
      var unformated=(STerror.stack || STerror.stacktrace);_x000D_
      trace_result = "\u25BC console.trace" + unformated.substring(unformated.indexOf('\n',unformated.indexOf('\n'))); _x000D_
     } else {_x000D_
      // IE 11+ and everyone else compatibility_x000D_
      trace_result = console.trace();_x000D_
     }_x000D_
     if (log_result)_x000D_
      console.log( trace_result );_x000D_
     _x000D_
     return trace_result;_x000D_
    }_x000D_
// test code_x000D_
(function testfunc(){_x000D_
 document.write( "<pre>" + stacktrace( false ) + "</pre>" );_x000D_
})();
_x000D_
_x000D_
_x000D_

Stacked Bar Plot in R

The dataset:

dat <- read.table(text = "A   B   C   D   E   F    G
1 480 780 431 295 670 360  190
2 720 350 377 255 340 615  345
3 460 480 179 560  60 735 1260
4 220 240 876 789 820 100   75", header = TRUE)

Now you can convert the data frame into a matrix and use the barplot function.

barplot(as.matrix(dat))

enter image description here

How to format current time using a yyyyMMddHHmmss format?

import("time")

layout := "2006-01-02T15:04:05.000Z"
str := "2014-11-12T11:45:26.371Z"
t, err := time.Parse(layout, str)
if err != nil {
    fmt.Println(err)
}
fmt.Println(t)

gives:

>> 2014-11-12 11:45:26.371 +0000 UTC

How to combine two vectors into a data frame

This should do the trick, to produce the data frame you asked for, using only base R:

df <- data.frame(cond=c(rep("x", times=length(x)), 
                        rep("y", times=length(y))), 
                 rating=c(x, y))

df
  cond rating
1    x      1
2    x      2
3    x      3
4    y    100
5    y    200
6    y    300

However, from your initial description, I'd say that this is perhaps a more likely usecase:

df2 <- data.frame(x, y)
colnames(df2) <- c(x_name, y_name)

df2
  cond rating
1    1    100
2    2    200
3    3    300

[edit: moved parentheses in example 1]

How to close off a Git Branch?

Yes, just delete the branch by running git push origin :branchname. To fix a new issue later, branch off from master again.

How to darken an image on mouseover?

Create black png with lets say 50% transparency. Overlay this on mouseover.

Removing body margin in CSS

You can use body or * to make margin and padding 0px;

*{
margin: 0px;
padding:0px;
}

Listing files in a directory matching a pattern in Java

See File#listFiles(FilenameFilter).

File dir = new File(".");
File [] files = dir.listFiles(new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
        return name.endsWith(".xml");
    }
});

for (File xmlfile : files) {
    System.out.println(xmlfile);
}

Jquery .on('scroll') not firing the event while scrolling

I know that this is quite old thing, but I solved issue like that: I had parent and child element was scrollable.

   if ($('#parent > *').length == 0 ){
        var wait = setInterval(function() {
            if($('#parent > *').length != 0 ) {
                $('#parent .child').bind('scroll',function() {
                  //do staff
                });
                clearInterval(wait);
            },1000);
        }

The issue I had is that I didn't know when the child is loaded to DOM, but I kept checking for it every second.

NOTE:this is useful if it happens soon but not right after document load, otherwise it will use clients computing power for no reason.

Print all properties of a Python Class

try ppretty:

from ppretty import ppretty


class Animal(object):
    def __init__(self):
        self.legs = 2
        self.name = 'Dog'
        self.color= 'Spotted'
        self.smell= 'Alot'
        self.age  = 10
        self.kids = 0


print ppretty(Animal(), seq_length=10)

Output:

__main__.Animal(age = 10, color = 'Spotted', kids = 0, legs = 2, name = 'Dog', smell = 'Alot')

T-SQL split string based on delimiter

ALTER FUNCTION [dbo].[split_string](
          @delimited NVARCHAR(MAX),
          @delimiter NVARCHAR(100)
        ) RETURNS @t TABLE (id INT IDENTITY(1,1), val NVARCHAR(MAX))
AS
BEGIN
  DECLARE @xml XML
  SET @xml = N'<t>' + REPLACE(@delimited,@delimiter,'</t><t>') + '</t>'

  INSERT INTO @t(val)
  SELECT  r.value('.','varchar(MAX)') as item
  FROM  @xml.nodes('/t') as records(r)
  RETURN
END

R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph

First off, your code is a bit off. aes() is an argument in ggplot(), you don't use ggplot(...) + aes(...) + layers

Second, from the help file ?geom_bar:

By default, geom_bar uses stat="count" which makes the height of the bar proportion to the number of cases in each group (or if the weight aethetic is supplied, the sum of the weights). If you want the heights of the bars to represent values in the data, use stat="identity" and map a variable to the y aesthetic.

You want the second case, where the height of the bar is equal to the conversion_rate So what you want is...

data_country <- data.frame(country = c("China", "Germany", "UK", "US"), 
            conversion_rate = c(0.001331558,0.062428188, 0.052612025, 0.037800687))
ggplot(data_country, aes(x=country,y = conversion_rate)) +geom_bar(stat = "identity")

Result:

enter image description here

Difference between string object and string literal

The long answer is available here, so I'll give you the short one.

When you do this:

String str = "abc";

You are calling the intern() method on String. This method references an internal pool of String objects. If the String you called intern() on already resides in the pool, then a reference to that String is assigned to str. If not, then the new String is placed in the pool, and a reference to it is then assigned to str.

Given the following code:

String str = "abc";
String str2 = "abc";
boolean identity = str == str2;

When you check for object identity by doing == (you are literally asking: do these two references point to the same object?), you get true.

However, you don't need to intern() Strings. You can force the creation on a new Object on the Heap by doing this:

String str = new String("abc");
String str2 = new String("abc");
boolean identity = str == str2;

In this instance, str and str2 are references to different Objects, neither of which have been interned, so that when you test for Object identity using ==, you will get false.

In terms of good coding practice: do not use == to check for String equality, use .equals() instead.

What is the difference between "SMS Push" and "WAP Push"?

An SMS Push is a message to tell the terminal to initiate the session. This happens because you can't initiate an IP session simply because you don't know the IP Adress of the mobile terminal. Mostly used to send a few lines of data to end recipient, to the effect of sending information, or reminding of events.

WAP Push is an SMS within the header of which is included a link to a WAP address. On receiving a WAP Push, the compatible mobile handset automatically gives the user the option to access the WAP content on his handset. The WAP Push directs the end-user to a WAP address where content is stored ready for viewing or downloading onto the handset. This wap address may be a page or a WAP site.

The user may “take action” by using a developer-defined soft-key to immediately activate an application to accomplish a specific task, such as downloading a picture, making a purchase, or responding to a marketing offer.

Extracting columns from text file with different delimiters in Linux

You can use cut with a delimiter like this:

with space delim:

cut -d " " -f1-100,1000-1005 infile.csv > outfile.csv

with tab delim:

cut -d$'\t' -f1-100,1000-1005 infile.csv > outfile.csv

I gave you the version of cut in which you can extract a list of intervals...

Hope it helps!

Django model "doesn't declare an explicit app_label"

I had exactly the same error when running tests with PyCharm. I've fixed it by explicitly setting DJANGO_SETTINGS_MODULE environment variable. If you're using PyCharm, just hit Edit Configurations button and choose Environment Variables.

Set the variable to your_project_name.settings and that should fix the thing.

It seems like this error occurs, because PyCharm runs tests with its own manage.py.

How to import a jar in Eclipse

Just a comment on importing jars into Eclipse (plug-in development) projects:

In case you are developing Eclipse plug-ins, it makes sense to use Eclipse's native bundling mechanism instead of just importing the jar into a plug-in project. Eclipse (or better its underlying OSGi runtime, Equinox) uses so-called bundles which contain some more information than plain jars (e.g., version infos, dependencies to other bundles, exported packages; see the MANIFEST.MF file). Because of this information, OSGi bundles can be dynamically loaded/unloaded and there is automatic dependency resolution available in an OSGi/Eclipse runtime. Hence, using OSGi bundles instead of plain jars (contained inside another OSGi bundle) has some advantages.

(BTW: Eclipse plug-ins are the same thing as OSGi bundles.)

There is a good chance that somebody already bundled a certain (3rd party) library as an OSGi bundle. You might want to take a look at the following bundle repositories:

How to merge every two lines into one from the command line?

Try the following line:

while read line1; do read line2; echo "$line1 $line2"; done <old.txt>new_file

Put delimiter in-between

"$line1 $line2";

e.g. if the delimiter is |, then:

"$line1|$line2";

How do I clone a generic List in Java?

This is the code I use for that:

ArrayList copy = new ArrayList (original.size());
Collections.copy(copy, original);

Hope is usefull for you

How can I output the value of an enum class in C++11

To write simpler,

enum class Color
{
    Red = 1,
    Green = 11,
    Blue = 111
};

int value = static_cast<int>(Color::Blue); // 111

Change the Right Margin of a View Programmatically?

EDIT: A more generic way of doing this that doesn't rely on the layout type (other than that it is a layout type which supports margins):

public static void setMargins (View v, int l, int t, int r, int b) {
    if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
        ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
        p.setMargins(l, t, r, b);
        v.requestLayout();
    }
}

You should check the docs for TextView. Basically, you'll want to get the TextView's LayoutParams object, and modify the margins, then set it back to the TextView. Assuming it's in a LinearLayout, try something like this:

TextView tv = (TextView)findViewById(R.id.my_text_view);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)tv.getLayoutParams();
params.setMargins(0, 0, 10, 0); //substitute parameters for left, top, right, bottom
tv.setLayoutParams(params);

I can't test it right now, so my casting may be off by a bit, but the LayoutParams are what need to be modified to change the margin.

NOTE

Don't forget that if your TextView is inside, for example, a RelativeLayout, one should use RelativeLayout.LayoutParams instead of LinearLayout.LayoutParams

Encode URL in JavaScript?

To encode a URL, as has been said before, you have two functions:

encodeURI()

and

encodeURIComponent()

The reason both exist is that the first preserves the URL with the risk of leaving too many things unescaped, while the second encodes everything needed.

With the first, you could copy the newly escaped URL into address bar (for example) and it would work. However your unescaped '&'s would interfere with field delimiters, the '='s would interfere with field names and values, and the '+'s would look like spaces. But for simple data when you want to preserve the URL nature of what you are escaping, this works.

The second is everything you need to do to make sure nothing in your string interfers with a URL. It leaves various unimportant characters unescaped so that the URL remains as human readable as possible without interference. A URL encoded this way will no longer work as a URL without unescaping it.

So if you can take the time, you always want to use encodeURIComponent() -- before adding on name/value pairs encode both the name and the value using this function before adding it to the query string.

I'm having a tough time coming up with reasons to use the encodeURI() -- I'll leave that to the smarter people.

How do I add a border to an image in HTML?

Two ways:

<img src="..." border="1" />

or

<img style='border:1px solid #000000' src="..." />

rsync error: failed to set times on "/foo/bar": Operation not permitted

If /foo/bar is on NFS (or possibly some FUSE filesystem), that might be the problem.

Either way, adding -O / --omit-dir-times to your command line will avoid it trying to set modification times on directories.

Array of char* should end at '\0' or "\0"?

The termination of an array of characters with a null character is just a convention that is specifically for strings in C. You are dealing with something completely different -- an array of character pointers -- so it really has no relation to the convention for C strings. Sure, you could choose to terminate it with a null pointer; that perhaps could be your convention for arrays of pointers. There are other ways to do it. You can't ask people how it "should" work, because you're assuming some convention that isn't there.

How to initialize all the elements of an array to any specific value in java

If it's a primitive type, you can use Arrays.fill():

Arrays.fill(array, -1);

[Incidentally, memset in C or C++ is only of any real use for arrays of char.]

Why doesn't java.io.File have a close method?

Say suppose, you have

File f  = new File("SomeFile");
f.length();

You need not close the Files, because its just the representation of a path.

You should always consider to close only reader/writers and in fact streams.

Branch from a previous commit using Git

If you are not sure which commit you want to branch from in advance you can check commits out and examine their code (see source, compile, test) by

git checkout <sha1-of-commit>

once you find the commit you want to branch from you can do that from within the commit (i.e. without going back to the master first) just by creating a branch in the usual way:

git checkout -b <branch_name>

groovy: safely find a key in a map and return its value

Groovy maps can be used with the property property, so you can just do:

def x = mymap.likes

If the key you are looking for (for example 'likes.key') contains a dot itself, then you can use the syntax:

def x = mymap.'likes.key'

How do I minimize the command prompt from my bat file

Yet another free 3rd party tool that is capable of minimizing the console window at any time (not only when starting the script) is Tcl with the TWAPI extension:

echo package require twapi;twapi::minimize_window [twapi::get_console_window] | tclkitsh -

here tclkitsh.exe is in the PATH and is one of the tclkit-cli-*-twapi-*.exe files downloadable from sourceforge.net/projects/twapi/files/Tcl binaries/Tclkits with TWAPI/. I prefer it to the much lighter min.exe mentioned in Bernard Chen's answer because I use TWAPI for countless other purposes already.

Python - List of unique dictionaries

Well all the answers mentioned here are good, but in some answers one can face error if the dictionary items have nested list or dictionary, so I propose simple answer

a = [str(i) for i in a]
a = list(set(a))
a = [eval(i) for i in a]

How to set the LDFLAGS in CMakeLists.txt?

Look at:

CMAKE_EXE_LINKER_FLAGS
CMAKE_MODULE_LINKER_FLAGS
CMAKE_SHARED_LINKER_FLAGS
CMAKE_STATIC_LINKER_FLAGS

Java constructor/method with optional parameters?

Java doesn't have the concept of optional parameters with default values either in constructors or in methods. You're basically stuck with overloading. However, you chain constructors easily so you don't need to repeat the code:

public Foo(int param1, int param2)
{
    this.param1 = param1;
    this.param2 = param2;
}

public Foo(int param1)
{
    this(param1, 2);
}

How do I set an absolute include path in PHP?

There is nothing in include/require that prohibits you from using absolute an path. so your example

include('/includes/header.php'); 

should work just fine. Assuming the path and file are corect and have the correct permissions set.
(and thereby allow you to include whatever file you like, in- or outside your document root)

This behaviour is however considered to be a possible security risk. Therefore, the system administrator can set the open_basedir directive.

This directive configures where you can include/require your files from and it might just be your problem.
Some control panels (plesk for example) set this directive to be the same as the document root by default.

as for the '.' syntax:

/home/username/public_html <- absolute path  
public_html <- relative path  
./public_html <- same as the path above  
../username/public_html <- another relative path  

However, I usually use a slightly different option:

require_once(__DIR__ . '/Factories/ViewFactory.php');

With this edition, you specify an absolute path, relative to the file that contains the require_once() statement.

Split Java String by New Line

If you don’t want empty lines:

String.split("[\\r\\n]+")

How to add a named sheet at the end of all Excel sheets?

ThisWorkbook.Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "XYZ"

(when you add a worksheet, anyway it'll be the active sheet)

Filtering Pandas DataFrames on dates

And if your dates are standardized by importing datetime package, you can simply use:

df[(df['date']>datetime.date(2016,1,1)) & (df['date']<datetime.date(2016,3,1))]  

For standarding your date string using datetime package, you can use this function:

import datetime
datetime.datetime.strptime

python: creating list from string

If you need to convert some of them to numbers and don't know in advance which ones, some additional code will be needed. Try something like this:

b = []
for x in a:
    temp = []
    items = x.split(",")
    for item in items:
        try:
            n = int(item)
        except ValueError:
            temp.append(item)
        else:
            temp.append(n)
    b.append(temp)

This is longer than the other answers, but it's more versatile.

How to use pip with Python 3.x alongside Python 2.x

In Windows, first installed Python 3.7 and then Python 2.7. Then, use command prompt:

pip install python2-module-name

pip3 install python3-module-name

That's all

react-router (v4) how to go back?

Here is the cleanest and simplest way you can handle this problem, which also nullifies the probable pitfalls of the this keyword. Use functional components:

import { withRouter } from "react-router-dom"; wrap your component or better App.js with the withRouter() HOC this makes history to be available "app-wide". wrapping your component only makes history available for that specific component``` your choice.

So you have:

  1. export default withRouter(App);

  2. In a Redux environment export default withRouter( connect(mapStateToProps, { <!-- your action creators -->})(App), ); you should even be able to user history from your action creators this way.

in your component do the following:

import {useHistory} from "react-router-dom";

const history = useHistory(); // do this inside the component

goBack = () => history.goBack();

<btn btn-sm btn-primary onclick={goBack}>Go Back</btn>

export default DemoComponent;

Gottcha useHistory is only exported from the latest v5.1 react-router-dom so be sure to update the package. However, you should not have to worry. about the many snags of the this keyword.

You can also make this a reusable component to use across your app.


function BackButton({ children }) {
  let history = useHistory()
  return (
    <button type="button" onClick={() => history.goBack()}>
      {children}
    </button>
  )
}```
Cheers.

How do I programmatically "restart" an Android app?

My solution doesn't restart the process/application. It only lets the app "restart" the home activity (and dismiss all other activities). It looks like a restart to users, but the process is the same. I think in some cases people want to achieve this effect, so I just leave it here FYI.

public void restart(){
    Intent intent = new Intent(this, YourHomeActivity.class);
    this.startActivity(intent);
    this.finishAffinity();
}

Removing "bullets" from unordered list <ul>

Try this it works

<ul class="sub-menu" type="none">
           <li class="sub-menu-list" ng-repeat="menu in list.components">
               <a class="sub-menu-link">
                   {{ menu.component }}
               </a>
           </li>
        </ul>

What is the correct XPath for choosing attributes that contain "foo"?

Have you tried something like:

//a[contains(@prop, "Foo")]

I've never used the contains function before but suspect that it should work as advertised...

How to loop through a plain JavaScript object with the objects as members?

for (var key in validation_messages) {
    // skip loop if the property is from prototype
    if (!validation_messages.hasOwnProperty(key)) continue;

    var obj = validation_messages[key];
    for (var prop in obj) {
        // skip loop if the property is from prototype
        if (!obj.hasOwnProperty(prop)) continue;

        // your code
        alert(prop + " = " + obj[prop]);
    }
}

How to disable text selection using jQuery?

I found this answer ( Prevent Highlight of Text Table ) most helpful, and perhaps it can be combined with another way of providing IE compatibility.

#yourTable
{
  -moz-user-select: none;
  -khtml-user-select: none;
  -webkit-user-select: none;
  user-select: none;
}

Qt - reading from a text file

You have to replace string line

QString line = in.readLine();

into while:

QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
    QMessageBox::information(0, "error", file.errorString());
}

QTextStream in(&file);

while(!in.atEnd()) {
    QString line = in.readLine();    
    QStringList fields = line.split(",");    
    model->appendRow(fields);    
}

file.close();

Rendering partial view on button click in ASP.NET MVC

So here is the controller code.

public IActionResult AddURLTest()
{
    return ViewComponent("AddURL");
}

You can load it using JQuery load method.

$(document).ready (function(){
    $("#LoadSignIn").click(function(){
        $('#UserControl').load("/Home/AddURLTest");
    });
});

source code link

how can the textbox width be reduced?

<input type='text' 
       name='t1'
       id='t1'
       maxlength=10
       placeholder='typing some text' >
<p></p>

This is the text box, it has a fixed length of 10 characters, and if you can try but this text box does not contain maximum length 10 character

What is the best way to compare floats for almost-equality in Python?

In terms of absolute error, you can just check

if abs(a - b) <= error:
    print("Almost equal")

Some information of why float act weird in Python https://youtu.be/v4HhvoNLILk?t=1129

You can also use math.isclose for relative errors

Try-Catch-End Try in VBScript doesn't seem to work

Handling Errors

A sort of an "older style" of error handling is available to us in VBScript, that does make use of On Error Resume Next. First we enable that (often at the top of a file; but you may use it in place of the first Err.Clear below for their combined effect), then before running our possibly-error-generating code, clear any errors that have already occurred, run the possibly-error-generating code, and then explicitly check for errors:

On Error Resume Next
' ...
' Other Code Here (that may have raised an Error)
' ...
Err.Clear      ' Clear any possible Error that previous code raised
Set myObj = CreateObject("SomeKindOfClassThatDoesNotExist")
If Err.Number <> 0 Then
    WScript.Echo "Error: " & Err.Number
    WScript.Echo "Error (Hex): " & Hex(Err.Number)
    WScript.Echo "Source: " &  Err.Source
    WScript.Echo "Description: " &  Err.Description
    Err.Clear             ' Clear the Error
End If
On Error Goto 0           ' Don't resume on Error
WScript.Echo "This text will always print."

Above, we're just printing out the error if it occurred. If the error was fatal to the script, you could replace the second Err.clear with WScript.Quit(Err.Number).

Also note the On Error Goto 0 which turns off resuming execution at the next statement when an error occurs.

If you want to test behavior for when the Set succeeds, go ahead and comment that line out, or create an object that will succeed, such as vbscript.regexp.

The On Error directive only affects the current running scope (current Sub or Function) and does not affect calling or called scopes.


Raising Errors

If you want to check some sort of state and then raise an error to be handled by code that calls your function, you would use Err.Raise. Err.Raise takes up to five arguments, Number, Source, Description, HelpFile, and HelpContext. Using help files and contexts is beyond the scope of this text. Number is an error number you choose, Source is the name of your application/class/object/property that is raising the error, and Description is a short description of the error that occurred.

If MyValue <> 42 Then
    Err.Raise(42, "HitchhikerMatrix", "There is no spoon!")
End If

You could then handle the raised error as discussed above.


Change Log

  • Edit #1: Added an Err.Clear before the possibly error causing line to clear any previous errors that may have been ignored.
  • Edit #2: Clarified.
  • Edit #3: Added comments in code block. Clarified that there was expected to be more code between On Error Resume Next and Err.Clear. Fixed some grammar to be less awkward. Added info on Err.Raise. Formatting.
  • Use jquery to set value of div tag

    if your value is a pure text (like 'test') you could use the text() method as well. like this:

    $('div.total-title').text('test');
    

    anyway, about the problem you are sharing, I think you might be calling the JavaScript code before the HTML code for the DIV is being sent to the browser. make sure you are calling the jQuery line in a <script> tag after the <div>, or in a statement like this:

    $(document).ready(
        function() {
            $('div.total-title').text('test');
        }
    );
    

    this way the script executes after the HTML of the div is parsed by the browser.

    Remove all constraints affecting a UIView

    In Swift:

    import UIKit
    
    extension UIView {
    
        /**
         Removes all constrains for this view
         */
        func removeConstraints() {
    
            let constraints = self.superview?.constraints.filter{
                $0.firstItem as? UIView == self || $0.secondItem as? UIView == self
            } ?? []
    
            self.superview?.removeConstraints(constraints)
            self.removeConstraints(self.constraints)
        }
    }
    

    Maven Modules + Building a Single Specific Module

    If you have previously run mvn install on project B it will have been installed to your local repository, so when you build package A Maven can resolve the dependency. So as long as you install project B each time you change it your builds for project A will be up to date.

    You can define a multi-module project with an aggregator pom to build a set of projects.

    It's also worthwhile mentioning m2eclipse, it integrates Maven into Eclipse and allows you to (optionally) resolve dependencies from the workspace. So if you are hacking away on multiple projects, the workspace content will be used for compilation. Once you are happy with your changes, run mvn install (on each project in turn, or using an aggregator) to put them in your local repository.

    How to join two tables by multiple columns in SQL?

    No, just include the different fields in the "ON" clause of 1 inner join statement:

    SELECT * from Evalulation e JOIN Value v ON e.CaseNum = v.CaseNum
        AND e.FileNum = v.FileNum AND e.ActivityNum = v.ActivityNum
    

    Do we need type="text/css" for <link> in HTML5

    You don't really need it today, because the current standard makes it optional -- and every useful browser currently assumes that a style sheet is CSS, even in versions of HTML that considered the attribute "required".

    With HTML being a "living standard" now, though -- and thus subject to change -- you can only guarantee so much. And there's no new DTD that you can point to and say the page was written for that version of HTML, and no reliable way even to say "HTML as of such-and-such a date". For forward-compatibility reasons, in my opinion, you should specify the type.

    REST API Login Pattern

    A big part of the REST philosophy is to exploit as many standard features of the HTTP protocol as possible when designing your API. Applying that philosophy to authentication, client and server would utilize standard HTTP authentication features in the API.

    Login screens are great for human user use cases: visit a login screen, provide user/password, set a cookie, client provides that cookie in all future requests. Humans using web browsers can't be expected to provide a user id and password with each individual HTTP request.

    But for a REST API, a login screen and session cookies are not strictly necessary, since each request can include credentials without impacting a human user; and if the client does not cooperate at any time, a 401 "unauthorized" response can be given. RFC 2617 describes authentication support in HTTP.

    TLS (HTTPS) would also be an option, and would allow authentication of the client to the server (and vice versa) in every request by verifying the public key of the other party. Additionally this secures the channel for a bonus. Of course, a keypair exchange prior to communication is necessary to do this. (Note, this is specifically about identifying/authenticating the user with TLS. Securing the channel by using TLS / Diffie-Hellman is always a good idea, even if you don't identify the user by its public key.)

    An example: suppose that an OAuth token is your complete login credentials. Once the client has the OAuth token, it could be provided as the user id in standard HTTP authentication with each request. The server could verify the token on first use and cache the result of the check with a time-to-live that gets renewed with each request. Any request requiring authentication returns 401 if not provided.

    How to use WinForms progress bar?

    Since .NET 4.5 you can use combination of async and await with Progress for sending updates to UI thread:

    private void Calculate(int i)
    {
        double pow = Math.Pow(i, i);
    }
    
    public void DoWork(IProgress<int> progress)
    {
        // This method is executed in the context of
        // another thread (different than the main UI thread),
        // so use only thread-safe code
        for (int j = 0; j < 100000; j++)
        {
            Calculate(j);
    
            // Use progress to notify UI thread that progress has
            // changed
            if (progress != null)
                progress.Report((j + 1) * 100 / 100000);
        }
    }
    
    private async void button1_Click(object sender, EventArgs e)
    {
        progressBar1.Maximum = 100;
        progressBar1.Step = 1;
    
        var progress = new Progress<int>(v =>
        {
            // This lambda is executed in context of UI thread,
            // so it can safely update form controls
            progressBar1.Value = v;
        });
    
        // Run operation in another thread
        await Task.Run(() => DoWork(progress));
    
        // TODO: Do something after all calculations
    }
    

    Tasks are currently the preferred way to implement what BackgroundWorker does.

    Tasks and Progress are explained in more detail here:

    In Python, what does dict.pop(a,b) mean?

    The pop method of dicts (like self.data, i.e. {'a':'aaa','b':'bbb','c':'ccc'}, here) takes two arguments -- see the docs

    The second argument, default, is what pop returns if the first argument, key, is absent. (If you call pop with just one argument, key, it raises an exception if that key's absent).

    In your example, print b.pop('a',{'b':'bbb'}), this is irrelevant because 'a' is a key in b.data. But if you repeat that line...:

    b=a()
    print b.pop('a',{'b':'bbb'})
    print b.pop('a',{'b':'bbb'})
    print b.data
    

    you'll see it makes a difference: the first pop removes the 'a' key, so in the second pop the default argument is actually returned (since 'a' is now absent from b.data).

    how to iterate through dictionary in a dictionary in django template?

    If you pass a variable data (dictionary type) as context to a template, then you code should be:

    {% for key, value in data.items %}
        <p>{{ key }} : {{ value }}</p> 
    {% endfor %}
    

    How to view the stored procedure code in SQL Server Management Studio

    exec sp_helptext 'your_sp_name' -- don't forget the quotes

    In management studio by default results come in grid view. If you would like to see it in text view go to:

    Query --> Results to --> Results to Text

    or CTRL + T and then Execute.