Programs & Examples On #Interrupted exception

When does Java's Thread.sleep throw InterruptedException?

The InterruptedException is usually thrown when a sleep is interrupted.

Handling InterruptedException in Java

I would say in some cases it's ok to do nothing. Probably not something you should be doing by default, but in case there should be no way for the interrupt to happen, I'm not sure what else to do (probably logging error, but that does not affect program flow).

One case would be in case you have a task (blocking) queue. In case you have a daemon Thread handling these tasks and you do not interrupt the Thread by yourself (to my knowledge the jvm does not interrupt daemon threads on jvm shutdown), I see no way for the interrupt to happen, and therefore it could be just ignored. (I do know that a daemon thread may be killed by the jvm at any time and therefore are unsuitable in some cases).

EDIT: Another case might be guarded blocks, at least based on Oracle's tutorial at: http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html

Android Layout Right Align

This is an example for a RelativeLayout:

RelativeLayout relativeLayout=(RelativeLayout)vi.findViewById(R.id.RelativeLayoutLeft);
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)relativeLayout.getLayoutParams();
                params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                relativeLayout.setLayoutParams(params);

With another kind of layout (example LinearLayout) you just simply has to change RelativeLayout for LinearLayout.

What should I set JAVA_HOME environment variable on macOS X 10.6?

Nowadays Java seems to be installed in /Library/Java/JavaVirtualMachines

How to remove all files from directory without removing directory in Node.js

Building on @Waterscroll's response, if you want to use async and await in node 8+:

const fs = require('fs');
const util = require('util');
const readdir = util.promisify(fs.readdir);
const unlink = util.promisify(fs.unlink);
const directory = 'test';

async function toRun() {
  try {
    const files = await readdir(directory);
    const unlinkPromises = files.map(filename => unlink(`${directory}/${filename}`));
    return Promise.all(unlinkPromises);
  } catch(err) {
    console.log(err);
  }
}

toRun();

Rails - Could not find a JavaScript runtime?

Install a Javascript runtime

The error is caused by the absence of a Javascript runtime on your local machine. To resolve this, you'll need to install NodeJS.

You can install NodeJS through the Node Version Manager or nvm:

First, install nvm:

$ curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.31.0/install.sh | bash

Install Node through nvm:

nvm install 5.9.1

This will install version 5.9.1 of Node.

How to calculate combination and permutation in R?

It might be that the package "Combinations" is not updated anymore and does not work with a recent version of R (I was also unable to install it on R 2.13.1 on windows). The package "combinat" installs without problem for me and might be a solution for you depending on what exactly you're trying to do.

How can I check if a checkbox is checked?

remember is undefined … and the checked property is a boolean not a number.

function validate(){
    var remember = document.getElementById('remember');
    if (remember.checked){
        alert("checked") ;
    }else{
        alert("You didn't check it! Let me check it for you.")
    }
}

Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

I had the same issue with Visual Studio 2019. Just Installed the following NuGet packages and the issue was solved.

1). xUnit

2). xunit.runner.visualstudio

3). Microsoft.TestPlatform.TestHost

4). Microsoft.NET.Test.Sdk

Resizing SVG in html?

Use the following code:

<g transform="scale(0.1)">
...
</g>

LDAP filter for blank (empty) attribute

The schema definition for an attribute determines whether an attribute must have a value. If the manager attribute in the example given is the attribute defined in RFC4524 with OID 0.9.2342.19200300.100.1.10, then that attribute has DN syntax. DN syntax is a sequence of relative distinguished names and must not be empty. The filter given in the example is used to cause the LDAP directory server to return only entries that do not have a manager attribute to the LDAP client in the search result.

Reload a DIV without reloading the whole page

The code you're using is also going to include a fadeout effect. Is this what you want to achieve? If not, it might make more sense to just add the following INSIDE "Small.php".

<meta http-equiv="refresh" content="15" >

This adds a refresh every 15seconds to the small.php page which should mean if called by PHP into another page, only that "frame" will reload.

Let us know if it worked/solved your problem!?

-Brad

Resize image proportionally with CSS?

Try

transform: scale(0.5, 0.5);
-ms-transform: scale(0.5, 0.5);
-webkit-transform: scale(0.5, 0.5);

Center image in table td in CSS

<table style="width:100%;">
<tbody ><tr><td align="center">
<img src="axe.JPG" />
</td>
</tr>
</tbody>
</table>

or

td
{
    text-align:center;
}

in the CSS file

VBA Convert String to Date

Looks like it could be throwing the error on the empty data row, have you tried to just make sure itemDate isn't empty before you run the CDate() function? I think this might be your problem.

Bootstrap: Collapse other sections when one is expanded

If you are using Bootstrap 4, and you don't want to change your markup:

var $myGroup = $('#myGroup');
$myGroup.on('show.bs.collapse','.collapse', function() {
$myGroup.find('.collapse.show').collapse('hide');
});

How to change the data type of a column without dropping the column with query?

MSDN says

ALTER TABLE mytable ALTER COLUMN mycolumn newtype

Beware of the limitations of the ALTER COLUMN clause listed in the article

Get ID from URL with jQuery

My url is like this http://www.default-search.net/?sid=503 . I want to get 503 . I wrote the following code .

var baseUrl = (window.location).href; // You can also use document.URL
var koopId = baseUrl.substring(baseUrl.lastIndexOf('=') + 1);
alert(koopId)//503

If you use

var v = window.location.pathname;
console.log(v)

You will get only "/";

Android how to use Environment.getExternalStorageDirectory()

Environment.getExternalStorageDirectory().getAbsolutePath()

Gives you the full path the SDCard. You can then do normal File I/O operations using standard Java.

Here's a simple example for writing a file:

String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.txt";

// Not sure if the / is on the path or not
File f = new File(baseDir + File.separator + fileName);
f.write(...);
f.flush();
f.close();

Edit:

Oops - you wanted an example for reading ...

String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.txt";

// Not sure if the / is on the path or not
File f = new File(baseDir + File.Separator + fileName);
FileInputStream fiStream = new FileInputStream(f);

byte[] bytes;

// You might not get the whole file, lookup File I/O examples for Java
fiStream.read(bytes); 
fiStream.close();

What is the fastest way to create a checksum for large files in C#

I know that I am late to party but performed test before actually implement the solution.

I did perform test against inbuilt MD5 class and also md5sum.exe. In my case inbuilt class took 13 second where md5sum.exe too around 16-18 seconds in every run.

    DateTime current = DateTime.Now;
    string file = @"C:\text.iso";//It's 2.5 Gb file
    string output;
    using (var md5 = MD5.Create())
    {
        using (var stream = File.OpenRead(file))
        {
            byte[] checksum = md5.ComputeHash(stream);
            output = BitConverter.ToString(checksum).Replace("-", String.Empty).ToLower();
            Console.WriteLine("Total seconds : " + (DateTime.Now - current).TotalSeconds.ToString() + " " + output);
        }
    }

Define an alias in fish shell

If you add an abbr instead of an alias you'll get better auto-complete. In fish abbr more closely matches the behavior of a bash alias.

abbr -a gco git checkout

Will -add a new abbreviation gco that expands to git checkout.

Here's a video demo of the resulting auto-complete features

How to find the size of a table in SQL?

A query (modification of https://stackoverflow.com/a/7892349/1737819) to find a custom name table size in GB. You might try this, replace 'YourTableName' with the name of your table.

SELECT 
    t.NAME AS TableName,    
    p.rows AS RowCounts,
    CONVERT(DECIMAL,SUM(a.total_pages)) * 8 / 1024 / 1024 AS TotalSpaceGB, 
    SUM(a.used_pages)  * 8 / 1024 / 1024 AS UsedSpaceGB , 
    (SUM(a.total_pages) - SUM(a.used_pages)) * 8 / 1024 / 1024 AS UnusedSpaceGB
FROM 
    sys.tables t
INNER JOIN      
    sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN 
    sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN 
    sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN 
    sys.schemas s ON t.schema_id = s.schema_id
WHERE 
    t.NAME = 'YourTable'
    AND t.is_ms_shipped = 0
    AND i.OBJECT_ID > 255 
GROUP BY 
    t.Name, s.Name, p.Rows
ORDER BY 
    UsedSpaceGB DESC, t.Name

How to set a ripple effect on textview or imageview on Android?

try this. This is worked for me.

android:clickable="true"
    android:focusable="true"
    android:background="?android:attr/selectableItemBackground"

How to read single Excel cell value

You need to cast it to a string (not an array of string) since it's a single value.

var cellValue = (string)(excelWorksheet.Cells[10, 2] as Excel.Range).Value;

Docker: How to delete all local Docker images

docker rmi $(docker images -q) --force

How to find available directory objects on Oracle 11g system?

The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path

SELECT owner, directory_name, directory_path
  FROM all_directories

PHP Composer update "cannot allocate memory" error (using Laravel 4)

I had a same issue on vagrant. I fixed it by allcate more memory.

 config.vm.provider :virtualbox do |vb|
      vb.customize ["modifyvm", :id, "--memory", "1024"]
 end

Filter dict to contain only certain keys?

Given your original dictionary orig and the set of entries that you're interested in keys:

filtered = dict(zip(keys, [orig[k] for k in keys]))

which isn't as nice as delnan's answer, but should work in every Python version of interest. It is, however, fragile to each element of keys existing in your original dictionary.

How to generate keyboard events?

macOS

Here is the more complete version of @Phylliida answer in form of class with code example:

#!/usr/bin/python
# Script simulating keyboard events in macOS.
# See: https://stackoverflow.com/q/13564851/55075

import sys
import time
from Quartz.CoreGraphics import CGEventCreateKeyboardEvent
from Quartz.CoreGraphics import CGEventPost
from Quartz.CoreGraphics import kCGHIDEventTap
#from Quartz.CoreGraphics import CFRelease # Python releases things automatically.

class Keyboard():
    shiftChars = {
        '~': '`',
        '!': '1',
        '@': '2',
        '#': '3',
        '$': '4',
        '%': '5',
        '^': '6',
        '&': '7',
        '*': '8',
        '(': '9',
        ')': '0',
        '_': '-',
        '+': '=',
        '{': '[',
        '}': ']',
        '|': '\\',
        ':': ';',
        '"': '\'',
        '<': ',',
        '>': '.',
        '?': '/'
    }


    keyCodeMap = {
        'a'              : 0x00,
        's'              : 0x01,
        'd'              : 0x02,
        'f'              : 0x03,
        'h'              : 0x04,
        'g'              : 0x05,
        'z'              : 0x06,
        'x'              : 0x07,
        'c'              : 0x08,
        'v'              : 0x09,
        'b'              : 0x0B,
        'q'              : 0x0C,
        'w'              : 0x0D,
        'e'              : 0x0E,
        'r'              : 0x0F,
        'y'              : 0x10,
        't'              : 0x11,
        '1'              : 0x12,
        '2'              : 0x13,
        '3'              : 0x14,
        '4'              : 0x15,
        '6'              : 0x16,
        '5'              : 0x17,
        '='              : 0x18,
        '9'              : 0x19,
        '7'              : 0x1A,
        '-'              : 0x1B,
        '8'              : 0x1C,
        '0'              : 0x1D,
        ']'              : 0x1E,
        'o'              : 0x1F,
        'u'              : 0x20,
        '['              : 0x21,
        'i'              : 0x22,
        'p'              : 0x23,
        'l'              : 0x25,
        'j'              : 0x26,
        '\''             : 0x27,
        'k'              : 0x28,
        ';'              : 0x29,
        '\\'             : 0x2A,
        ','              : 0x2B,
        '/'              : 0x2C,
        'n'              : 0x2D,
        'm'              : 0x2E,
        '.'              : 0x2F,
        '`'              : 0x32,
        'k.'             : 0x41,
        'k*'             : 0x43,
        'k+'             : 0x45,
        'kclear'         : 0x47,
        'k/'             : 0x4B,
        'k\n'            : 0x4C,
        'k-'             : 0x4E,
        'k='             : 0x51,
        'k0'             : 0x52,
        'k1'             : 0x53,
        'k2'             : 0x54,
        'k3'             : 0x55,
        'k4'             : 0x56,
        'k5'             : 0x57,
        'k6'             : 0x58,
        'k7'             : 0x59,
        'k8'             : 0x5B,
        'k9'             : 0x5C,

        # keycodes for keys that are independent of keyboard layout
        '\n'             : 0x24,
        '\t'             : 0x30,
        ' '              : 0x31,
        'del'            : 0x33,
        'delete'         : 0x33,
        'esc'            : 0x35,
        'escape'         : 0x35,
        'cmd'            : 0x37,
        'command'        : 0x37,
        'shift'          : 0x38,
        'caps lock'      : 0x39,
        'option'         : 0x3A,
        'ctrl'           : 0x3B,
        'control'        : 0x3B,
        'right shift'    : 0x3C,
        'rshift'         : 0x3C,
        'right option'   : 0x3D,
        'roption'        : 0x3D,
        'right control'  : 0x3E,
        'rcontrol'       : 0x3E,
        'fun'            : 0x3F,
        'function'       : 0x3F,
        'f17'            : 0x40,
        'volume up'      : 0x48,
        'volume down'    : 0x49,
        'mute'           : 0x4A,
        'f18'            : 0x4F,
        'f19'            : 0x50,
        'f20'            : 0x5A,
        'f5'             : 0x60,
        'f6'             : 0x61,
        'f7'             : 0x62,
        'f3'             : 0x63,
        'f8'             : 0x64,
        'f9'             : 0x65,
        'f11'            : 0x67,
        'f13'            : 0x69,
        'f16'            : 0x6A,
        'f14'            : 0x6B,
        'f10'            : 0x6D,
        'f12'            : 0x6F,
        'f15'            : 0x71,
        'help'           : 0x72,
        'home'           : 0x73,
        'pgup'           : 0x74,
        'page up'        : 0x74,
        'forward delete' : 0x75,
        'f4'             : 0x76,
        'end'            : 0x77,
        'f2'             : 0x78,
        'page down'      : 0x79,
        'pgdn'           : 0x79,
        'f1'             : 0x7A,
        'left'           : 0x7B,
        'right'          : 0x7C,
        'down'           : 0x7D,
        'up'             : 0x7E
    }

    # See: https://stackoverflow.com/q/3202629/55075
    def toKeyCode(self, c):
        shiftKey = False
        # Letter
        if c.isalpha():
            if not c.islower():
                shiftKey = True
                c = c.lower()
        if c in Keyboard.shiftChars:
            shiftKey = True
            c = Keyboard.shiftChars[c]
        if c in Keyboard.keyCodeMap:
            keyCode = Keyboard.keyCodeMap[c]
        else:
            keyCode = ord(c)
        return keyCode, shiftKey

    def KeyDown(self, k):
        keyCode, shiftKey = self.toKeyCode(k)

        time.sleep(0.0001)

        if shiftKey:
            CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, True))
            time.sleep(0.0001)

        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, True))
        time.sleep(0.0001)

        if shiftKey:
            CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, False))
            time.sleep(0.0001)

    def KeyUp(self, k):
        keyCode, shiftKey = self.toKeyCode(k)

        time.sleep(0.0001)

        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, False))
        time.sleep(0.0001)

    def KeyPress(self, k):
        keyCode, shiftKey = self.toKeyCode(k)

        time.sleep(0.0001)

        if shiftKey:
            CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, True))
            time.sleep(0.0001)

        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, True))
        time.sleep(0.0001)

        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, False))
        time.sleep(0.0001)

        if shiftKey:
            CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, False))
            time.sleep(0.0001)

    def Type(self, text):
        for key in text:
            self.KeyDown(key)
            self.KeyUp(key)

Here is the demo code using above class:

# DEMO
if __name__ == '__main__':
    keyboard = Keyboard()
    if sys.platform == "darwin":
        keyboard.Type('Hello World!')
    elif sys.platform == "win32":
        print("Error: Platform not supported!")

which will simulate typing Hello World! text on the current window.

You can run above code as a shell script. Check the link to the keyboard.py file.

Easy way to convert a unicode list to a list containing python strings?

Just json.dumps will fix the problem

json.dumps function actually converts all the unicode literals to string literals and it will be easy for us to load the data either in json file or csv file.

sample code:

import json
EmployeeList =  [u'1001', u'Karick', u'14-12-2020', u'1$']
result_list = json.dumps(EmployeeList)
print result_list

output: ["1001", "Karick", "14-12-2020", "1$"]

Makefile: How to correctly include header file and its directory?

Try INC_DIR=../ ../StdCUtil.

Then, set CCFLAGS=-c -Wall $(addprefix -I,$(INC_DIR))

EDIT: Also, modify your #include to be #include <StdCUtil/split.h> so that the compiler knows to use -I rather than local path of the .cpp using the #include.

Change the background color in a twitter bootstrap modal?

For Bootstrap 4 you may have to use .modal-backdrop.show and play around with !important flag on both background-color and opacity.

E.g.

.modal-backdrop.show {
   background-color: #f00;
   opacity: 0.75;
}

How to generate java classes from WSDL file

Assuming that you have JAXB installed Go to the following directory C:\Program Files\jaxb\bin open command window here

> xjc -wsdl http://localhost/mywsdl/MyDWsdl.wsdl C:\Users\myname\Desktop

C:\Users\myname\Desktop is the ouput folder you can change that to your preference

http://localhost/mywsdl/MyDWsdl.wsdl is the link to the WSDL

No resource found that matches the given name '@style/ Theme.Holo.Light.DarkActionBar'

You can change this one parent attribute ="android:style/Theme.Holo.Light.DarkActionBar"

react hooks useEffect() cleanup for only componentWillUnmount?

useEffect are isolated within its own scope and gets rendered accordingly. Image from https://reactjs.org/docs/hooks-custom.html

enter image description here

How do I determine the size of my array in C?

Executive summary:

int a[17];
size_t n = sizeof(a)/sizeof(a[0]);

Full answer:

To determine the size of your array in bytes, you can use the sizeof operator:

int a[17];
size_t n = sizeof(a);

On my computer, ints are 4 bytes long, so n is 68.

To determine the number of elements in the array, we can divide the total size of the array by the size of the array element. You could do this with the type, like this:

int a[17];
size_t n = sizeof(a) / sizeof(int);

and get the proper answer (68 / 4 = 17), but if the type of a changed you would have a nasty bug if you forgot to change the sizeof(int) as well.

So the preferred divisor is sizeof(a[0]) or the equivalent sizeof(*a), the size of the first element of the array.

int a[17];
size_t n = sizeof(a) / sizeof(a[0]);

Another advantage is that you can now easily parameterize the array name in a macro and get:

#define NELEMS(x)  (sizeof(x) / sizeof((x)[0]))

int a[17];
size_t n = NELEMS(a);

Simulating ENTER keypress in bash script

You can just use yes.

# yes "" | someCommand

vbscript output to console

You only need to force cscript instead wscript. I always use this template. The function ForceConsole() will execute your vbs into cscript, also you have nice alias to print and scan text.

 Set oWSH = CreateObject("WScript.Shell")
 vbsInterpreter = "cscript.exe"

 Call ForceConsole()

 Function printf(txt)
    WScript.StdOut.WriteLine txt
 End Function

 Function printl(txt)
    WScript.StdOut.Write txt
 End Function

 Function scanf()
    scanf = LCase(WScript.StdIn.ReadLine)
 End Function

 Function wait(n)
    WScript.Sleep Int(n * 1000)
 End Function

 Function ForceConsole()
    If InStr(LCase(WScript.FullName), vbsInterpreter) = 0 Then
        oWSH.Run vbsInterpreter & " //NoLogo " & Chr(34) & WScript.ScriptFullName & Chr(34)
        WScript.Quit
    End If
 End Function

 Function cls()
    For i = 1 To 50
        printf ""
    Next
 End Function

 printf " _____ _ _           _____         _    _____         _     _   "
 printf "|  _  |_| |_ ___ ___|     |_ _ _ _| |  |   __|___ ___|_|___| |_ "
 printf "|     | | '_| . |   |   --| | | | . |  |__   |  _|  _| | . |  _|"
 printf "|__|__|_|_,_|___|_|_|_____|_____|___|  |_____|___|_| |_|  _|_|  "
 printf "                                                       |_|     v1.0"
 printl " Enter your name:"
 MyVar = scanf
 cls
 printf "Your name is: " & MyVar
 wait(5)

Which equals operator (== vs ===) should be used in JavaScript comparisons?

In the answers here, I didn't read anything about what equal means. Some will say that === means equal and of the same type, but that's not really true. It actually means that both operands reference the same object, or in case of value types, have the same value.

So, let's take the following code:

var a = [1,2,3];
var b = [1,2,3];
var c = a;

var ab_eq = (a === b); // false (even though a and b are the same type)
var ac_eq = (a === c); // true

The same here:

var a = { x: 1, y: 2 };
var b = { x: 1, y: 2 };
var c = a;

var ab_eq = (a === b); // false (even though a and b are the same type)
var ac_eq = (a === c); // true

Or even:

var a = { };
var b = { };
var c = a;

var ab_eq = (a === b); // false (even though a and b are the same type)
var ac_eq = (a === c); // true

This behavior is not always obvious. There's more to the story than being equal and being of the same type.

The rule is:

For value types (numbers):
a === b returns true if a and b have the same value and are of the same type

For reference types:
a === b returns true if a and b reference the exact same object

For strings:
a === b returns true if a and b are both strings and contain the exact same characters


Strings: the special case...

Strings are not value types, but in Javascript they behave like value types, so they will be "equal" when the characters in the string are the same and when they are of the same length (as explained in the third rule)

Now it becomes interesting:

var a = "12" + "3";
var b = "123";

alert(a === b); // returns true, because strings behave like value types

But how about this?:

var a = new String("123");
var b = "123";

alert(a === b); // returns false !! (but they are equal and of the same type)

I thought strings behave like value types? Well, it depends who you ask... In this case a and b are not the same type. a is of type Object, while b is of type string. Just remember that creating a string object using the String constructor creates something of type Object that behaves as a string most of the time.

How do operator.itemgetter() and sort() work?

a = []
a.append(["Nick", 30, "Doctor"])
a.append(["John",  8, "Student"])
a.append(["Paul",  8,"Car Dealer"])
a.append(["Mark", 66, "Retired"])
print a

[['Nick', 30, 'Doctor'], ['John', 8, 'Student'], ['Paul', 8, 'Car Dealer'], ['Mark', 66, 'Retired']]

def _cmp(a,b):     

    if a[1]<b[1]:
        return -1
    elif a[1]>b[1]:
        return 1
    else:
        return 0

sorted(a,cmp=_cmp)

[['John', 8, 'Student'], ['Paul', 8, 'Car Dealer'], ['Nick', 30, 'Doctor'], ['Mark', 66, 'Retired']]

def _key(list_ele):

    return list_ele[1]

sorted(a,key=_key)

[['John', 8, 'Student'], ['Paul', 8, 'Car Dealer'], ['Nick', 30, 'Doctor'], ['Mark', 66, 'Retired']]
>>> 

Android Get Application's 'Home' Data Directory

To get the path of file in application package;

ContextWrapper c = new ContextWrapper(this);
Toast.makeText(this, c.getFilesDir().getPath(), Toast.LENGTH_LONG).show();

How to loop over a Class attributes in Java?

Here is a solution which sorts the properties alphabetically and prints them all together with their values:

public void logProperties() throws IllegalArgumentException, IllegalAccessException {
  Class<?> aClass = this.getClass();
  Field[] declaredFields = aClass.getDeclaredFields();
  Map<String, String> logEntries = new HashMap<>();

  for (Field field : declaredFields) {
    field.setAccessible(true);

    Object[] arguments = new Object[]{
      field.getName(),
      field.getType().getSimpleName(),
      String.valueOf(field.get(this))
    };

    String template = "- Property: {0} (Type: {1}, Value: {2})";
    String logMessage = System.getProperty("line.separator")
            + MessageFormat.format(template, arguments);

    logEntries.put(field.getName(), logMessage);
  }

  SortedSet<String> sortedLog = new TreeSet<>(logEntries.keySet());

  StringBuilder sb = new StringBuilder("Class properties:");

  Iterator<String> it = sortedLog.iterator();
  while (it.hasNext()) {
    String key = it.next();
    sb.append(logEntries.get(key));
  }

  System.out.println(sb.toString());
}

How to list the properties of a JavaScript object?

Note that Object.keys and other ECMAScript 5 methods are supported by Firefox 4, Chrome 6, Safari 5, IE 9 and above.

For example:

var o = {"foo": 1, "bar": 2}; 
alert(Object.keys(o));

ECMAScript 5 compatibility table: http://kangax.github.com/es5-compat-table/

Description of new methods: http://markcaudill.com/index.php/2009/04/javascript-new-features-ecma5/

What is a good practice to check if an environmental variable exists or not?

I'd recommend the following solution.

It prints the env vars you didn't include, which lets you add them all at once. If you go for the for loop, you're going to have to rerun the program to see each missing var.

from os import environ

REQUIRED_ENV_VARS = {"A", "B", "C", "D"}
diff = REQUIRED_ENV_VARS.difference(environ)
if len(diff) > 0:
    raise EnvironmentError(f'Failed because {diff} are not set')

Make var_dump look pretty

I wrote a function (debug_display) which can print, arrays, objects, and file info in pretty way.

<?php
function debug_display($var,$show = false) {
    if($show) { $dis = 'block'; }else { $dis = 'none'; }
    ob_start();
    echo '<div style="display:'.$dis.';text-align:left; direction:ltr;"><b>Idea Debug Method : </b>
        <pre>';
    if(is_bool($var)) {
        echo $var === TRUE ? 'Boolean(TRUE)' : 'Boolean(FALSE)';
    }else {
        if(FALSE == empty($var) && $var !== NULL && $var != '0') {
            if(is_array($var)) {
                echo "Number of Indexes: " . count($var) . "\n";
                print_r($var);
            } elseif(is_object($var)) {
                print_r($var);
            } elseif(@is_file($var)){
                $stat = stat($var);
                $perm = substr(sprintf('%o',$stat['mode']), -4);
                $accesstime = gmdate('Y/m/d H:i:s', $stat['atime']);
                $modification = gmdate('Y/m/d H:i:s', $stat['mtime']);
                $change = gmdate('Y/m/d H:i:s', $stat['ctime']);
                echo "
    file path : $var
    file size : {$stat['size']} Byte
    device number : {$stat['dev']}
    permission : {$perm}
    last access time was : {$accesstime}
    last modified time was : {$modification}
    last change time was : {$change}
    ";
            }elseif(is_string($var)) {
                print_r(htmlentities(str_replace("\t", '  ', $var)));
            }  else {
                print_r($var);
            }
        }else {
            echo 'Undefined';
        }
    }
    echo '</pre>
    </div>';
    $output = ob_get_contents();
    ob_end_clean();
    echo $output;
    unset($output);
}

XML shape drawable not rendering desired color

I had a similar problem and found that if you remove the size definition, it works for some reason.

Remove:

<size
    android:width="60dp"
    android:height="40dp" />

from the shape.

Let me know if this works!

"Operation must use an updateable query" error in MS Access

I got this same error and using a primary key did not make a difference. The issue was that the table is a linked Excel table. I know there are settings to change this but my IT department has locked this so we cant change it. Instead, I created a make table from the linked table and used that instead in my Update Query and it worked. Note, any queries in your query that are also linked to the same Excel linked table will cause the same error so you will need to change these as well so they are not directly linked to the Excel linked table. HTH

Test file upload using HTTP PUT method

If you're using PHP you can test your PUT upload using the code below:

#Initiate cURL object
$curl = curl_init();
#Set your URL
curl_setopt($curl, CURLOPT_URL, 'https://local.simbiat.ru');
#Indicate, that you plan to upload a file
curl_setopt($curl, CURLOPT_UPLOAD, true);
#Indicate your protocol
curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
#Set flags for transfer
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
#Disable header (optional)
curl_setopt($curl, CURLOPT_HEADER, false);
#Set HTTP method to PUT
curl_setopt($curl, CURLOPT_PUT, 1);
#Indicate the file you want to upload
curl_setopt($curl, CURLOPT_INFILE, fopen('path_to_file', 'rb'));
#Indicate the size of the file (it does not look like this is mandatory, though)
curl_setopt($curl, CURLOPT_INFILESIZE, filesize('path_to_file'));
#Only use below option on TEST environment if you have a self-signed certificate!!! On production this can cause security issues
#curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
#Execute
curl_exec($curl);

How to remove symbols from a string with Python?

I often just open the console and look for the solution in the objects methods. Quite often it's already there:

>>> a = "hello ' s"
>>> dir(a)
[ (....) 'partition', 'replace' (....)]
>>> a.replace("'", " ")
'hello   s'

Short answer: Use string.replace().

jQuery check if attr = value

Just remove the .val(). Like:

if ( $('html').attr('lang') == 'fr-FR' ) {
    // do this
} else {
    // do that
}

How to resize a custom view programmatically?

This is what I did:

View myView;  
myView.getLayoutParams().height = 32;  
myView.getLayoutParams().width = 32;

If there is a view group that this view belongs to, you may also need to call yourViewGroup.requestLayout() for it to take effect.

getMinutes() 0-9 - How to display two digit numbers?

Another option:

var dateTime = new Date();
var minutesTwoDigitsWithLeadingZero = ("0" + dateTime.getMinutes()).substr(-2);

How can I parse a time string containing milliseconds in it with python?

To give the code that nstehr's answer refers to (from its source):

def timeparse(t, format):
    """Parse a time string that might contain fractions of a second.

    Fractional seconds are supported using a fragile, miserable hack.
    Given a time string like '02:03:04.234234' and a format string of
    '%H:%M:%S', time.strptime() will raise a ValueError with this
    message: 'unconverted data remains: .234234'.  If %S is in the
    format string and the ValueError matches as above, a datetime
    object will be created from the part that matches and the
    microseconds in the time string.
    """
    try:
        return datetime.datetime(*time.strptime(t, format)[0:6]).time()
    except ValueError, msg:
        if "%S" in format:
            msg = str(msg)
            mat = re.match(r"unconverted data remains:"
                           " \.([0-9]{1,6})$", msg)
            if mat is not None:
                # fractional seconds are present - this is the style
                # used by datetime's isoformat() method
                frac = "." + mat.group(1)
                t = t[:-len(frac)]
                t = datetime.datetime(*time.strptime(t, format)[0:6])
                microsecond = int(float(frac)*1e6)
                return t.replace(microsecond=microsecond)
            else:
                mat = re.match(r"unconverted data remains:"
                               " \,([0-9]{3,3})$", msg)
                if mat is not None:
                    # fractional seconds are present - this is the style
                    # used by the logging module
                    frac = "." + mat.group(1)
                    t = t[:-len(frac)]
                    t = datetime.datetime(*time.strptime(t, format)[0:6])
                    microsecond = int(float(frac)*1e6)
                    return t.replace(microsecond=microsecond)

        raise

Serialize an object to XML

You can use the function like below to get serialized XML from any object.

public static bool Serialize<T>(T value, ref string serializeXml)
{
    if (value == null)
    {
        return false;
    }
    try
    {
        XmlSerializer xmlserializer = new XmlSerializer(typeof(T));
        StringWriter stringWriter = new StringWriter();
        XmlWriter writer = XmlWriter.Create(stringWriter);

        xmlserializer.Serialize(writer, value);

        serializeXml = stringWriter.ToString();

        writer.Close();
        return true;
    }
    catch (Exception ex)
    {
        return false;
    }
}

You can call this from the client.

how to import csv data into django models

You want to use the csv module that is part of the python language and you should use Django's get_or_create method

 with open(path) as f:
        reader = csv.reader(f)
        for row in reader:
            _, created = Teacher.objects.get_or_create(
                first_name=row[0],
                last_name=row[1],
                middle_name=row[2],
                )
            # creates a tuple of the new object or
            # current object and a boolean of if it was created

In my example the model teacher has three attributes first_name, last_name and middle_name.

Django documentation of get_or_create method

How can I count the occurrences of a list item?

To count the number of diverse elements having a common type:

li = ['A0','c5','A8','A2','A5','c2','A3','A9']

print sum(1 for el in li if el[0]=='A' and el[1] in '01234')

gives

3 , not 6

How Do I 'git fetch' and 'git merge' from a Remote Tracking Branch (like 'git pull')

these are the commands:

git fetch origin
git merge origin/somebranch somebranch

if you do this on the second line:

git merge origin somebranch

it will try to merge the local master into your current branch.

The question, as I've understood it, was you fetched already locally and want to now merge your branch to the latest of the same branch.

Convert between UIImage and Base64 string

Swift 4.2 Extension method

extension UIImage {
    func toBase64() -> String? {
        guard let imageData = self.pngData() else { return nil }
        return imageData.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters)
    }
}

XCode 9.1 and Swift 4.0

//
// Convert UIImage to a base64 representation
//
class func convertImageToBase64(image: UIImage) -> String {
    let imageData = UIImagePNGRepresentation(image)!
    return imageData.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters)
}

//
// Convert a base64 representation to a UIImage
//
class func convertBase64ToImage(imageString: String) -> UIImage {
    let imageData = Data(base64Encoded: imageString, options: Data.Base64DecodingOptions.ignoreUnknownCharacters)!
    return UIImage(data: imageData)!
}

How to import multiple .csv files at once?

A speedy and succinct tidyverse solution: (more than twice as fast as Base R's read.csv)

tbl <-
    list.files(pattern = "*.csv") %>% 
    map_df(~read_csv(.))

and data.table's fread() can even cut those load times by half again. (for 1/4 the Base R times)

library(data.table)

tbl_fread <- 
    list.files(pattern = "*.csv") %>% 
    map_df(~fread(.))

The stringsAsFactors = FALSE argument keeps the dataframe factor free, (and as marbel points out, is the default setting for fread)

If the typecasting is being cheeky, you can force all the columns to be as characters with the col_types argument.

tbl <-
    list.files(pattern = "*.csv") %>% 
    map_df(~read_csv(., col_types = cols(.default = "c")))

If you are wanting to dip into subdirectories to construct your list of files to eventually bind, then be sure to include the path name, as well as register the files with their full names in your list. This will allow the binding work to go on outside of the current directory. (Thinking of the full pathnames as operating like passports to allow movement back across directory 'borders'.)

tbl <-
    list.files(path = "./subdirectory/",
               pattern = "*.csv", 
               full.names = T) %>% 
    map_df(~read_csv(., col_types = cols(.default = "c"))) 

As Hadley describes here (about halfway down):

map_df(x, f) is effectively the same as do.call("rbind", lapply(x, f))....

Bonus Feature - adding filenames to the records per Niks feature request in comments below:
* Add original filename to each record.

Code explained: make a function to append the filename to each record during the initial reading of the tables. Then use that function instead of the simple read_csv() function.

read_plus <- function(flnm) {
    read_csv(flnm) %>% 
        mutate(filename = flnm)
}

tbl_with_sources <-
    list.files(pattern = "*.csv", 
               full.names = T) %>% 
    map_df(~read_plus(.))

(The typecasting and subdirectory handling approaches can also be handled inside the read_plus() function in the same manner as illustrated in the second and third variants suggested above.)

### Benchmark Code & Results 
library(tidyverse)
library(data.table)
library(microbenchmark)

### Base R Approaches
#### Instead of a dataframe, this approach creates a list of lists
#### removed from analysis as this alone doubled analysis time reqd
# lapply_read.delim <- function(path, pattern = "*.csv") {
#     temp = list.files(path, pattern, full.names = TRUE)
#     myfiles = lapply(temp, read.delim)
# }

#### `read.csv()`
do.call_rbind_read.csv <- function(path, pattern = "*.csv") {
    files = list.files(path, pattern, full.names = TRUE)
    do.call(rbind, lapply(files, function(x) read.csv(x, stringsAsFactors = FALSE)))
}

map_df_read.csv <- function(path, pattern = "*.csv") {
    list.files(path, pattern, full.names = TRUE) %>% 
    map_df(~read.csv(., stringsAsFactors = FALSE))
}


### *dplyr()*
#### `read_csv()`
lapply_read_csv_bind_rows <- function(path, pattern = "*.csv") {
    files = list.files(path, pattern, full.names = TRUE)
    lapply(files, read_csv) %>% bind_rows()
}

map_df_read_csv <- function(path, pattern = "*.csv") {
    list.files(path, pattern, full.names = TRUE) %>% 
    map_df(~read_csv(., col_types = cols(.default = "c")))
}

### *data.table* / *purrr* hybrid
map_df_fread <- function(path, pattern = "*.csv") {
    list.files(path, pattern, full.names = TRUE) %>% 
    map_df(~fread(.))
}

### *data.table*
rbindlist_fread <- function(path, pattern = "*.csv") {
    files = list.files(path, pattern, full.names = TRUE)
    rbindlist(lapply(files, function(x) fread(x)))
}

do.call_rbind_fread <- function(path, pattern = "*.csv") {
    files = list.files(path, pattern, full.names = TRUE)
    do.call(rbind, lapply(files, function(x) fread(x, stringsAsFactors = FALSE)))
}


read_results <- function(dir_size){
    microbenchmark(
        # lapply_read.delim = lapply_read.delim(dir_size), # too slow to include in benchmarks
        do.call_rbind_read.csv = do.call_rbind_read.csv(dir_size),
        map_df_read.csv = map_df_read.csv(dir_size),
        lapply_read_csv_bind_rows = lapply_read_csv_bind_rows(dir_size),
        map_df_read_csv = map_df_read_csv(dir_size),
        rbindlist_fread = rbindlist_fread(dir_size),
        do.call_rbind_fread = do.call_rbind_fread(dir_size),
        map_df_fread = map_df_fread(dir_size),
        times = 10L) 
}

read_results_lrg_mid_mid <- read_results('./testFolder/500MB_12.5MB_40files')
print(read_results_lrg_mid_mid, digits = 3)

read_results_sml_mic_mny <- read_results('./testFolder/5MB_5KB_1000files/')
read_results_sml_tny_mod <- read_results('./testFolder/5MB_50KB_100files/')
read_results_sml_sml_few <- read_results('./testFolder/5MB_500KB_10files/')

read_results_med_sml_mny <- read_results('./testFolder/50MB_5OKB_1000files')
read_results_med_sml_mod <- read_results('./testFolder/50MB_5OOKB_100files')
read_results_med_med_few <- read_results('./testFolder/50MB_5MB_10files')

read_results_lrg_sml_mny <- read_results('./testFolder/500MB_500KB_1000files')
read_results_lrg_med_mod <- read_results('./testFolder/500MB_5MB_100files')
read_results_lrg_lrg_few <- read_results('./testFolder/500MB_50MB_10files')

read_results_xlg_lrg_mod <- read_results('./testFolder/5000MB_50MB_100files')


print(read_results_sml_mic_mny, digits = 3)
print(read_results_sml_tny_mod, digits = 3)
print(read_results_sml_sml_few, digits = 3)

print(read_results_med_sml_mny, digits = 3)
print(read_results_med_sml_mod, digits = 3)
print(read_results_med_med_few, digits = 3)

print(read_results_lrg_sml_mny, digits = 3)
print(read_results_lrg_med_mod, digits = 3)
print(read_results_lrg_lrg_few, digits = 3)

print(read_results_xlg_lrg_mod, digits = 3)

# display boxplot of my typical use case results & basic machine max load
par(oma = c(0,0,0,0)) # remove overall margins if present
par(mfcol = c(1,1)) # remove grid if present
par(mar = c(12,5,1,1) + 0.1) # to display just a single boxplot with its complete labels
boxplot(read_results_lrg_mid_mid, las = 2, xlab = "", ylab = "Duration (seconds)", main = "40 files @ 12.5MB (500MB)")
boxplot(read_results_xlg_lrg_mod, las = 2, xlab = "", ylab = "Duration (seconds)", main = "100 files @ 50MB (5GB)")

# generate 3x3 grid boxplots
par(oma = c(12,1,1,1)) # margins for the whole 3 x 3 grid plot
par(mfcol = c(3,3)) # create grid (filling down each column)
par(mar = c(1,4,2,1)) # margins for the individual plots in 3 x 3 grid
boxplot(read_results_sml_mic_mny, las = 2, xlab = "", ylab = "Duration (seconds)", main = "1000 files @ 5KB (5MB)", xaxt = 'n')
boxplot(read_results_sml_tny_mod, las = 2, xlab = "", ylab = "Duration (milliseconds)", main = "100 files @ 50KB (5MB)", xaxt = 'n')
boxplot(read_results_sml_sml_few, las = 2, xlab = "", ylab = "Duration (milliseconds)", main = "10 files @ 500KB (5MB)",)

boxplot(read_results_med_sml_mny, las = 2, xlab = "", ylab = "Duration (microseconds)        ", main = "1000 files @ 50KB (50MB)", xaxt = 'n')
boxplot(read_results_med_sml_mod, las = 2, xlab = "", ylab = "Duration (microseconds)", main = "100 files @ 500KB (50MB)", xaxt = 'n')
boxplot(read_results_med_med_few, las = 2, xlab = "", ylab = "Duration (seconds)", main = "10 files @ 5MB (50MB)")

boxplot(read_results_lrg_sml_mny, las = 2, xlab = "", ylab = "Duration (seconds)", main = "1000 files @ 500KB (500MB)", xaxt = 'n')
boxplot(read_results_lrg_med_mod, las = 2, xlab = "", ylab = "Duration (seconds)", main = "100 files @ 5MB (500MB)", xaxt = 'n')
boxplot(read_results_lrg_lrg_few, las = 2, xlab = "", ylab = "Duration (seconds)", main = "10 files @ 50MB (500MB)")

Middling Use Case

Boxplot Comparison of Elapsed Time my typical use case

Larger Use Case

Boxplot Comparison of Elapsed Time for Extra Large Load

Variety of Use Cases

Rows: file counts (1000, 100, 10)
Columns: final dataframe size (5MB, 50MB, 500MB)
(click on image to view original size) Boxplot Comparison of Directory Size Variations

The base R results are better for the smallest use cases where the overhead of bringing the C libraries of purrr and dplyr to bear outweigh the performance gains that are observed when performing larger scale processing tasks.

if you want to run your own tests you may find this bash script helpful.

for ((i=1; i<=$2; i++)); do 
  cp "$1" "${1:0:8}_${i}.csv";
done

bash what_you_name_this_script.sh "fileName_you_want_copied" 100 will create 100 copies of your file sequentially numbered (after the initial 8 characters of the filename and an underscore).

Attributions and Appreciations

With special thanks to:

  • Tyler Rinker and Akrun for demonstrating microbenchmark.
  • Jake Kaupp for introducing me to map_df() here.
  • David McLaughlin for helpful feedback on improving the visualizations and discussing/confirming the performance inversions observed in the small file, small dataframe analysis results.
  • marbel for pointing out the default behavior for fread(). (I need to study up on data.table.)

Spring Hibernate - Could not obtain transaction-synchronized Session for current thread

I had this error too because in the file where I used @Transactional annotation, I was importing the wrong class

import javax.transaction.Transactional; 

Instead of javax, use

import org.springframework.transaction.annotation.Transactional; 

Calculate summary statistics of columns in dataframe

describe may give you everything you want otherwise you can perform aggregations using groupby and pass a list of agg functions: http://pandas.pydata.org/pandas-docs/stable/groupby.html#applying-multiple-functions-at-once

In [43]:

df.describe()

Out[43]:

       shopper_num is_martian  number_of_items  count_pineapples
count      14.0000         14        14.000000                14
mean        7.5000          0         3.357143                 0
std         4.1833          0         6.452276                 0
min         1.0000      False         0.000000                 0
25%         4.2500          0         0.000000                 0
50%         7.5000          0         0.000000                 0
75%        10.7500          0         3.500000                 0
max        14.0000      False        22.000000                 0

[8 rows x 4 columns]

Note that some columns cannot be summarised as there is no logical way to summarise them, for instance columns containing string data

As you prefer you can transpose the result if you prefer:

In [47]:

df.describe().transpose()

Out[47]:

                 count      mean       std    min   25%  50%    75%    max
shopper_num         14       7.5    4.1833      1  4.25  7.5  10.75     14
is_martian          14         0         0  False     0    0      0  False
number_of_items     14  3.357143  6.452276      0     0    0    3.5     22
count_pineapples    14         0         0      0     0    0      0      0

[4 rows x 8 columns]

CSS scale height to match width - possibly with a formfactor

I need to do "fluid" rectangles not squares.... so THANKS to JOPL .... didn't take but a minute....

#map_container {
     position: relative;
     width: 100%;
     padding-bottom: 75%;
}


#map {
    position:absolute;
    width:100%;
    height:100%;
}

Pandas read in table without headers

In order to read a csv in that doesn't have a header and for only certain columns you need to pass params header=None and usecols=[3,6] for the 4th and 7th columns:

df = pd.read_csv(file_path, header=None, usecols=[3,6])

See the docs

Spring boot - Not a managed type

I am using spring boot 2.0 and I fixed this by replacing @ComponentScan with @EntityScan

Modifying a file inside a jar

As long as this file isn't .class, i.e. resource file or manifest file - you can.

What is a provisioning profile used for when developing iPhone applications?

You need it to install development iPhone applications on development devices.

Here's how to create one, and the reference for this answer:
http://www.wikihow.com/Create-a-Provisioning-Profile-for-iPhone

Another link: http://iphone.timefold.com/provisioning.html

Is there a simple way that I can sort characters in a string in alphabetical order

You can use this

string x = "ABCGH"

char[] charX = x.ToCharArray();

Array.Sort(charX);

This will sort your string.

Upgrade python in a virtualenv

Let's consider that the environment that one wants to update has the name venv.

1. Backup venv requirementes (optional)

First of all, backup the requirements of the virtual environment:

pip freeze > requirements.txt
deactivate
#Move the folder to a new one
mv venv venv_old

2. Install Python

Assuming that one doesn't have sudo access, pyenv is a reliable and fast way to install Python. For that, one should run

$ curl https://pyenv.run | bash

and then

$ exec $SHELL

As it is suggested here.

If, when one tries to update pyenv

pyenv update

And one gets the error

bash: pyenv: command not found

It is because pyenv path wasn't exported to .bashrc. It can be solved by executing the following commands:

echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n eval "$(pyenv init -)"\nfi' >> ~/.bashrc

Then restart the shell

exec "$SHELL"

Now one should install the Python version that one wants. Let's say version 3.8.3

pyenv install 3.8.3

One can confirm if it was properly installed by running

pyenv versions

The output should be the location and the versions (in this case 3.8.3)

3. Create the new virtual environment

Finally, with the new Python version installed, create a new virtual environment (let's call it venv)

python3.8 -m venv venv

Activate it

source venv/bin/activate

and install the requirements

pip install -r requirements.txt

Now one should be up and running with a new environment.

Formatting doubles for output in C#

Use

Console.WriteLine(String.Format("  {0:G17}", i));

That will give you all the 17 digits it have. By default, a Double value contains 15 decimal digits of precision, although a maximum of 17 digits is maintained internally. {0:R} will not always give you 17 digits, it will give 15 if the number can be represented with that precision.

which returns 15 digits if the number can be represented with that precision or 17 digits if the number can only be represented with maximum precision. There isn't any thing you can to do to make the the double return more digits that is the way it's implemented. If you don't like it do a new double class yourself...

.NET's double cant store any more digits than 17 so you cant see 6.89999999999999946709 in the debugger you would see 6.8999999999999995. Please provide an image to prove us wrong.

How to auto import the necessary classes in Android Studio with shortcut?

Go to File -> Settings -> Editor -> Auto Import -> Java and make the below things:

Select Insert imports on paste value to All

Do tick mark on Add unambigious imports on the fly option and "Optimize imports on the fly*

Screenshot

What is a typedef enum in Objective-C?

typedef enum {
kCircle,
kRectangle,
kOblateSpheroid
} ShapeType;

then you can use it like :-

 ShapeType shape;

and

 enum {
    kCircle,
    kRectangle,
    kOblateSpheroid
} 
ShapeType;

now you can use it like:-

enum ShapeType shape;

Is Eclipse the best IDE for Java?

I have experience with using JCreator LE. I like it because it is easy to use and it is free. Give it a try if it interests you.

React - clearing an input value after form submit

Since you input field is a controlled element, you cannot directly change the input field value without modifying the state.

Also in

onHandleSubmit(e) {
    e.preventDefault();
    const city = this.state.city;
    this.props.onSearchTermChange(city);
    this.mainInput.value = "";
  }

this.mainInput doesn't refer the input since mainInput is an id, you need to specify a ref to the input

<input
      ref={(ref) => this.mainInput= ref}
      onChange={this.onHandleChange}
      placeholder="Get current weather..."
      value={this.state.city}
      type="text"
    />

In you current state the best way is to clear the state to clear the input value

onHandleSubmit(e) {
    e.preventDefault();
    const city = this.state.city;
    this.props.onSearchTermChange(city);
    this.setState({city: ""});
  }

However if you still for some reason want to keep the value in state even if the form is submitted, you would rather make the input uncontrolled

<input
      id="mainInput"
      onChange={this.onHandleChange}
      placeholder="Get current weather..."
      type="text"
    />

and update the value in state onChange and onSubmit clear the input using ref

 onHandleChange(e) {
    this.setState({
      city: e.target.value
    });
  }

  onHandleSubmit(e) {
    e.preventDefault();
    const city = this.state.city;
    this.props.onSearchTermChange(city);
    this.mainInput.value = "";
  }

Having Said that, I don't see any point in keeping the state unchanged, so the first option should be the way to go.

Is it not possible to stringify an Error using JSON.stringify?

You can solve this with a one-liner( errStringified ) in plain javascript:

var error = new Error('simple error message');
var errStringified = (err => JSON.stringify(Object.getOwnPropertyNames(Object.getPrototypeOf(err)).reduce(function(accumulator, currentValue) { return accumulator[currentValue] = err[currentValue], accumulator}, {})))(error);
console.log(errStringified);

It works with DOMExceptions as well.

get name of a variable or parameter

Alternatively,

1) Without touching System.Reflection namespace,

GETNAME(new { myInput });

public static string GETNAME<T>(T myInput) where T : class
{
    if (myInput == null)
        return string.Empty;

    return myInput.ToString().TrimStart('{').TrimEnd('}').Split('=')[0].Trim();
}

2) The below one can be faster though (from my tests)

GETNAME(new { variable });
public static string GETNAME<T>(T myInput) where T : class
{
    if (myInput == null)
        return string.Empty;

    return typeof(T).GetProperties()[0].Name;
}

You can also extend this for properties of objects (may be with extension methods):

new { myClass.MyProperty1 }.GETNAME();

You can cache property values to improve performance further as property names don't change during runtime.

The Expression approach is going to be slower for my taste. To get parameter name and value together in one go see this answer of mine

Why does Python code use len() function instead of a length method?

There are some great answers here, and so before I give my own I'd like to highlight a few of the gems (no ruby pun intended) I've read here.

  • Python is not a pure OOP language -- it's a general purpose, multi-paradigm language that allows the programmer to use the paradigm they are most comfortable with and/or the paradigm that is best suited for their solution.
  • Python has first-class functions, so len is actually an object. Ruby, on the other hand, doesn't have first class functions. So the len function object has it's own methods that you can inspect by running dir(len).

If you don't like the way this works in your own code, it's trivial for you to re-implement the containers using your preferred method (see example below).

>>> class List(list):
...     def len(self):
...         return len(self)
...
>>> class Dict(dict):
...     def len(self):
...         return len(self)
...
>>> class Tuple(tuple):
...     def len(self):
...         return len(self)
...
>>> class Set(set):
...     def len(self):
...         return len(self)
...
>>> my_list = List([1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F'])
>>> my_dict = Dict({'key': 'value', 'site': 'stackoverflow'})
>>> my_set = Set({1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F'})
>>> my_tuple = Tuple((1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F'))
>>> my_containers = Tuple((my_list, my_dict, my_set, my_tuple))
>>>
>>> for container in my_containers:
...     print container.len()
...
15
2
15
15

How to extend / inherit components?

Components can be extended as same as a typescript class inheritance, just that you have to override the selector with a new name. All Input() and Output() Properties from the Parent Component works as normal

Update

@Component is a decorator,

Decorators are applied during the declaration of class not on objects.

Basically, decorators add some metadata to the class object and that cannot be accessed via inheritance.

If you want to achieve the Decorator Inheritance I would Suggest writing a custom decorator. Something like below example.

export function CustomComponent(annotation: any) {
    return function (target: Function) {
    var parentTarget = Object.getPrototypeOf(target.prototype).constructor;

    var parentAnnotations = Reflect.getMetadata('annotations', parentTarget);
    var parentParamTypes = Reflect.getMetadata('design:paramtypes', parentTarget);
    var parentPropMetadata = Reflect.getMetadata('propMetadata', parentTarget);
    var parentParameters = Reflect.getMetadata('parameters', parentTarget);

    var parentAnnotation = parentAnnotations[0];

    Object.keys(parentAnnotation).forEach(key => {
    if (isPresent(parentAnnotation[key])) {
        if (!isPresent(annotation[key])) {
        annotation[key] = parentAnnotation[key];
        }
    }
    });
    // Same for the other metadata
    var metadata = new ComponentMetadata(annotation);

    Reflect.defineMetadata('annotations', [ metadata ], target);
    };
};

Refer: https://medium.com/@ttemplier/angular2-decorators-and-class-inheritance-905921dbd1b7

How to print current date on python3?

I use this which is standard for every time

import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))

How to reload a page using Angularjs?

Be sure to include the $route service into your scope and do this:

$route.reload();

See this:

How to reload or re-render the entire page using AngularJS

If input value is blank, assign a value of "empty" with Javascript

You can set a callback function for the onSubmit event of the form and check the contents of each field. If it contains nothing you can then fill it with the string "empty":

<form name="my_form" action="validate.php" onsubmit="check()">
    <input type="text" name="text1" />
    <input type="submit" value="submit" />
</form>

and in your js:

function check() {
    if(document.forms["my_form"]["text1"].value == "")
        document.forms["my_form"]["text1"].value = "empty";
}

What is HEAD in Git?

After reading all of the previous answers, I still wanted more clarity. This blog at the official git website http://git-scm.com/blog gave me what I was looking for:

The HEAD: Pointer to last commit snapshot, next parent

The HEAD in Git is the pointer to the current branch reference, which is in turn a pointer to the last commit you made or the last commit that was checked out into your working directory. That also means it will be the parent of the next commit you do. It's generally simplest to think of it as HEAD is the snapshot of your last commit.

Empty ArrayList equals null

No, this will not work. The best you will be able to do is to iterate through all values and check them yourself:

boolean empty = true;
for (Object item : arrayList) {
    if (item != null) {
        empty = false;
        break;
    }
}

Maximum length of the textual representation of an IPv6 address?

Answered my own question:

IPv6 addresses are normally written as eight groups of four hexadecimal digits, where each group is separated by a colon (:).

So that's 39 characters max.

Update one MySQL table with values from another

It depends what is a use of those tables, but you might consider putting trigger on original table on insert and update. When insert or update is done, update the second table based on only one item from the original table. It will be quicker.

ASP.NET Identity's default Password Hasher - How does it work and is it secure?

Here is how the default implementation (ASP.NET Framework or ASP.NET Core) works. It uses a Key Derivation Function with random salt to produce the hash. The salt is included as part of the output of the KDF. Thus, each time you "hash" the same password you will get different hashes. To verify the hash the output is split back to the salt and the rest, and the KDF is run again on the password with the specified salt. If the result matches to the rest of the initial output the hash is verified.

Hashing:

public static string HashPassword(string password)
{
    byte[] salt;
    byte[] buffer2;
    if (password == null)
    {
        throw new ArgumentNullException("password");
    }
    using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, 0x10, 0x3e8))
    {
        salt = bytes.Salt;
        buffer2 = bytes.GetBytes(0x20);
    }
    byte[] dst = new byte[0x31];
    Buffer.BlockCopy(salt, 0, dst, 1, 0x10);
    Buffer.BlockCopy(buffer2, 0, dst, 0x11, 0x20);
    return Convert.ToBase64String(dst);
}

Verifying:

public static bool VerifyHashedPassword(string hashedPassword, string password)
{
    byte[] buffer4;
    if (hashedPassword == null)
    {
        return false;
    }
    if (password == null)
    {
        throw new ArgumentNullException("password");
    }
    byte[] src = Convert.FromBase64String(hashedPassword);
    if ((src.Length != 0x31) || (src[0] != 0))
    {
        return false;
    }
    byte[] dst = new byte[0x10];
    Buffer.BlockCopy(src, 1, dst, 0, 0x10);
    byte[] buffer3 = new byte[0x20];
    Buffer.BlockCopy(src, 0x11, buffer3, 0, 0x20);
    using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, dst, 0x3e8))
    {
        buffer4 = bytes.GetBytes(0x20);
    }
    return ByteArraysEqual(buffer3, buffer4);
}

Turning a Comma Separated string into individual rows

select t.OtherID,x.Kod
    from testData t
    cross apply (select Code from dbo.Split(t.Data,',') ) x

VBA Object doesn't support this property or method

Object doesn't support this property or method.

Think of it like if anything after the dot is called on an object. It's like a chain.

An object is a class instance. A class instance supports some properties defined in that class type definition. It exposes whatever intelli-sense in VBE tells you (there are some hidden members but it's not related to this). So after each dot . you get intelli-sense (that white dropdown) trying to help you pick the correct action.

(you can start either way - front to back or back to front, once you understand how this works you'll be able to identify where the problem occurs)

Type this much anywhere in your code area

Dim a As Worksheets
a.

you get help from VBE, it's a little dropdown called Intelli-sense

enter image description here

It lists all available actions that particular object exposes to any user. You can't see the .Selection member of the Worksheets() class. That's what the error tells you exactly.

Object doesn't support this property or method.

If you look at the example on MSDN

Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count

It activates the sheet first then calls the Selection... it's not connected together because Selection is not a member of Worksheets() class. Simply, you can't prefix the Selection

What about

Sub DisplayColumnCount()
    Dim iAreaCount As Integer
    Dim i As Integer

    Worksheets("GRA").Activate
    iAreaCount = Selection.Areas.Count

    If iAreaCount <= 1 Then
        MsgBox "The selection contains " & Selection.Columns.Count & " columns."
    Else
        For i = 1 To iAreaCount
        MsgBox "Area " & i & " of the selection contains " & _
        Selection.Areas(i).Columns.Count & " columns."
        Next i
    End If
End Sub

from HERE

UITextField border color

Try this:

UITextField *theTextFiels=[[UITextField alloc]initWithFrame:CGRectMake(40, 40, 150, 30)];
    theTextFiels.borderStyle=UITextBorderStyleNone;
    theTextFiels.layer.cornerRadius=8.0f;
    theTextFiels.layer.masksToBounds=YES;
        theTextFiels.backgroundColor=[UIColor redColor];
    theTextFiels.layer.borderColor=[[UIColor blackColor]CGColor];
    theTextFiels.layer.borderWidth= 1.0f;

    [self.view addSubview:theTextFiels];
    [theTextFiels release];

and import QuartzCore:

#import <QuartzCore/QuartzCore.h>

How to check if another instance of my shell script is running

I you want the "pidof" method, here is the trick:

    if pidof -o %PPID -x "abc.sh">/dev/null; then
        echo "Process already running"
    fi

Where the -o %PPID parameter tells to omit the pid of the calling shell or shell script. More info in the pidof man page.

How can I get a specific field of a csv file?

import csv
inf = csv.reader(open('yourfile.csv','r'))
for row in inf:
  print row[1]

Javascript require() function giving ReferenceError: require is not defined

By default require() is not a valid function in client side javascript. I recommend you look into require.js as this does extend the client side to provide you with that function.

Can I make a phone call from HTML on Android?

Yes you can; it works on Android too:

tel: phone_number
Calls the entered phone number. Valid telephone numbers as defined in the IETF RFC 3966 are accepted. Valid examples include the following:

* tel:2125551212
* tel: (212) 555 1212

The Android browser uses the Phone app to handle the “tel” scheme, as defined by RFC 3966.
Clicking a link like:

<a href="tel:2125551212">2125551212</a>

on Android will bring up the Phone app and pre-enter the digits for 2125551212 without autodialing.

Have a look to RFC3966

JQuery $.ajax() post - data in a java servlet

For the time being I am going a different route than I previous stated. I changed the way I am formatting the data to:

  &A2168=1&A1837=5&A8472=1&A1987=2

On the server side I am using getParameterNames() to place all the keys into an Enumerator and then iterating over the Enumerator and placing the keys and values into a HashMap. It looks something like this:

Enumeration keys = request.getParameterNames(); 
HashMap map = new HashMap(); 
String key = null; 
while(keys.hasMoreElements()){ 
      key = keys.nextElement().toString(); 
      map.put(key, request.getParameter(key)); 
}

What is the return value of os.system() in Python?

"On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent."

http://docs.python.org/library/os.html#os.system

There is no error, so the exit code is zero

Postgresql GROUP_CONCAT equivalent?

This is probably a good starting point (version 8.4+ only):

SELECT id_field, array_agg(value_field1), array_agg(value_field2)
FROM data_table
GROUP BY id_field

array_agg returns an array, but you can CAST that to text and edit as needed (see clarifications, below).

Prior to version 8.4, you have to define it yourself prior to use:

CREATE AGGREGATE array_agg (anyelement)
(
    sfunc = array_append,
    stype = anyarray,
    initcond = '{}'
);

(paraphrased from the PostgreSQL documentation)

Clarifications:

  • The result of casting an array to text is that the resulting string starts and ends with curly braces. Those braces need to be removed by some method, if they are not desired.
  • Casting ANYARRAY to TEXT best simulates CSV output as elements that contain embedded commas are double-quoted in the output in standard CSV style. Neither array_to_string() or string_agg() (the "group_concat" function added in 9.1) quote strings with embedded commas, resulting in an incorrect number of elements in the resulting list.
  • The new 9.1 string_agg() function does NOT cast the inner results to TEXT first. So "string_agg(value_field)" would generate an error if value_field is an integer. "string_agg(value_field::text)" would be required. The array_agg() method requires only one cast after the aggregation (rather than a cast per value).

What is the difference between an annotated and unannotated tag?

The big difference is perfectly explained here.

Basically, lightweight tags are just pointers to specific commits. No further information is saved; on the other hand, annotated tags are regular objects, which have an author and a date and can be referred because they have their own SHA key.

If knowing who tagged what and when is relevant for you, then use annotated tags. If you just want to tag a specific point in your development, no matter who and when did that, then lightweight tags are good enough.

Normally you'd go for annotated tags, but it is really up to the Git master of the project.

Query a parameter (postgresql.conf setting) like "max_connections"

You can use SHOW:

SHOW max_connections;

This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf in your current session:

RESET max_connections;

However, not applicable to this particular setting. The manual:

This parameter can only be set at server start.

To see all settings:

SHOW ALL;

There is also pg_settings:

The view pg_settings provides access to run-time parameters of the server. It is essentially an alternative interface to the SHOW and SET commands. It also provides access to some facts about each parameter that are not directly available from SHOW, such as minimum and maximum values.

For your original request:

SELECT *
FROM   pg_settings
WHERE  name = 'max_connections';

Finally, there is current_setting(), which can be nested in DML statements:

SELECT current_setting('max_connections');

Related:

Default session timeout for Apache Tomcat applications

Open $CATALINA_BASE/conf/web.xml and find this

<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly   -->
<!-- created sessions by modifying the value below.                       -->

<session-config>
  <session-timeout>30</session-timeout>
</session-config>

all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.

This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different

LINUX: Link all files from one to another directory

GNU cp has an option to create symlinks instead of copying.

cp -rs /mnt/usr/lib /usr/

Note this is a GNU extension not found in POSIX cp.

Total size of the contents of all the files in a directory

If you want the 'apparent size' (that is the number of bytes in each file), not size taken up by files on the disk, use the -b or --bytes option (if you got a Linux system with GNU coreutils):

% du -sbh <directory>

How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session

I encountered the same issue. I think another way to fix this is that you can change the query to join fetch your Element from Model as follows:

Query query = session.createQuery("from Model m join fetch m.element where modelGroup.id = :modelGroupId")

Generating PDF files with JavaScript

I maintain PDFKit, which also powers pdfmake (already mentioned here). It works in both Node and the browser, and supports a bunch of stuff that other libraries do not:

  • Embedding subsetted fonts, with support for unicode.
  • Lots of advanced text layout stuff (columns, page breaking, full unicode line breaking, basic rich text, etc.).
  • Working on even more font stuff for advanced typography (OpenType/AAT ligatures, contextual substitution, etc.). Coming soon: see the fontkit branch if you're interested.
  • More graphics stuff: gradients, etc.
  • Built with modern tools like browserify and streams. Usable both in the browser and node.

Check out http://pdfkit.org/ for a full tutorial to see for yourself what PDFKit can do. And for an example of what kinds of documents can be produced, check out the docs as a PDF generated from some Markdown files using PDFKit itself: http://pdfkit.org/docs/guide.pdf.

You can also try it out interactively in the browser here: http://pdfkit.org/demo/browser.html.

How to run different python versions in cmd

I also met the case to use both python2 and python3 on my Windows machine. Here's how i resolved it:

  1. download python2x and python3x, installed them.
  2. add C:\Python35;C:\Python35\Scripts;C:\Python27;C:\Python27\Scripts to environment variable PATH.
  3. Go to C:\Python35 to rename python.exe to python3.exe, also to C:\Python27, rename python.exe to python2.exe.
  4. restart your command window.
  5. type python2 scriptname.py, or python3 scriptname.py in command line to switch the version you like.

How to determine the current iPhone/device model?

this is (i think) the most updated answer:

let modelName = UIDevice.current.name

print(modelName)

that's it.

No provider for TemplateRef! (NgIf ->TemplateRef)

You missed the * in front of NgIf (like we all have, dozens of times):

<div *ngIf="answer.accepted">&#10004;</div>

Without the *, Angular sees that the ngIf directive is being applied to the div element, but since there is no * or <template> tag, it is unable to locate a template, hence the error.


If you get this error with Angular v5:

Error: StaticInjectorError[TemplateRef]:
  StaticInjectorError[TemplateRef]:
    NullInjectorError: No provider for TemplateRef!

You may have <template>...</template> in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>.

Find difference between timestamps in seconds in PostgreSQL

select age(timestamp_A, timestamp_B)

Answering to Igor's comment:

select age('2013-02-28 11:01:28'::timestamp, '2011-12-31 11:00'::timestamp);
              age              
-------------------------------
 1 year 1 mon 28 days 00:01:28

Eliminate extra separators below UITableView

For iOS 7+ using Storyboards

Simply drag a UIView into your UITableView as the footer. Set the footer view's height to 0.

Django TemplateDoesNotExist?

Check permissions on templates and appname directories, either with ls -l or try doing an absolute path open() from django.

Running ASP.Net on a Linux based server

For ASP.NET on Linux, check out Mono.

That said, thousands of sites run on Windows Server without any issues. A poorly-configured server with any OS will be vulnerable; Linux won't save you from a poor admin.

So I guess my "best practice" for deplying an ASP.NET app would be to use Windows Server 2008 (likely Web edition). And hire a good administrator.

How to make a loop in x86 assembly language?

You need to use conditional jmp commands. This isn't the same syntax as you're using; looks like MASM, but using GAS here's an example from some code I wrote to calculate gcd:

gcd_alg:
    subl    %ecx, %eax      /* a = a - c */
    cmpl    $0, %eax        /* if a == 0 */
    je      gcd_done        /* jump to end */
    cmpl    %ecx, %eax      /* if a < c */
    jl      gcd_preswap     /* swap and start over */
    jmp     gcd_alg         /* keep subtracting */

Basically, I compare two registers with the cmpl instruction (compare long). If it is less the JL (jump less) instruction jumps to the preswap location, otherwise it jumps back to the same label.

As for clearing the screen, that depends on the system you're using.

Use Mockito to mock some methods but not others

According to docs :

Foo mock = mock(Foo.class, CALLS_REAL_METHODS);

// this calls the real implementation of Foo.getSomething()
value = mock.getSomething();

when(mock.getSomething()).thenReturn(fakeValue);

// now fakeValue is returned
value = mock.getSomething();

How do you test a public/private DSA keypair?

Assuming you have the public keys inside X.509 certificates, and assuming they are RSA keys, then for each public key, do

    openssl x509 -in certfile -modulus -noout

For each private key, do

    openssl rsa -in keyfile -modulus -noout

Then match the keys by modulus.

append option to select menu?

Something like this:

var option = document.createElement("option");
option.text = "Text";
option.value = "myvalue";
var select = document.getElementById("id-to-my-select-box");
select.appendChild(option);

Get current url in Angular

You can make use of location service available in @angular/common and via this below code you can get the location or current URL

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';

@Component({
  selector: 'app-top-nav',
  templateUrl: './top-nav.component.html',
  styleUrls: ['./top-nav.component.scss']
})
export class TopNavComponent implements OnInit {

  route: string;

  constructor(location: Location, router: Router) {
    router.events.subscribe((val) => {
      if(location.path() != ''){
        this.route = location.path();
      } else {
        this.route = 'Home'
      }
    });
  }

  ngOnInit() {
  }

}

here is the reference link from where I have copied thing to get location for my project. https://github.com/elliotforbes/angular-2-admin/blob/master/src/app/common/top-nav/top-nav.component.ts

How change List<T> data to IQueryable<T> data

var list = new List<string>();
var queryable = list.AsQueryable();

Add a reference to: System.Linq

Definition of "downstream" and "upstream"

When you read in git tag man page:

One important aspect of git is it is distributed, and being distributed largely means there is no inherent "upstream" or "downstream" in the system.

, that simply means there is no absolute upstream repo or downstream repo.
Those notions are always relative between two repos and depends on the way data flows:

If "yourRepo" has declared "otherRepo" as a remote one, then:

  • you are pulling from upstream "otherRepo" ("otherRepo" is "upstream from you", and you are "downstream for otherRepo").
  • you are pushing to upstream ("otherRepo" is still "upstream", where the information now goes back to).

Note the "from" and "for": you are not just "downstream", you are "downstream from/for", hence the relative aspect.


The DVCS (Distributed Version Control System) twist is: you have no idea what downstream actually is, beside your own repo relative to the remote repos you have declared.

  • you know what upstream is (the repos you are pulling from or pushing to)
  • you don't know what downstream is made of (the other repos pulling from or pushing to your repo).

Basically:

In term of "flow of data", your repo is at the bottom ("downstream") of a flow coming from upstream repos ("pull from") and going back to (the same or other) upstream repos ("push to").


You can see an illustration in the git-rebase man page with the paragraph "RECOVERING FROM UPSTREAM REBASE":

It means you are pulling from an "upstream" repo where a rebase took place, and you (the "downstream" repo) is stuck with the consequence (lots of duplicate commits, because the branch rebased upstream recreated the commits of the same branch you have locally).

That is bad because for one "upstream" repo, there can be many downstream repos (i.e. repos pulling from the upstream one, with the rebased branch), all of them having potentially to deal with the duplicate commits.

Again, with the "flow of data" analogy, in a DVCS, one bad command "upstream" can have a "ripple effect" downstream.


Note: this is not limited to data.
It also applies to parameters, as git commands (like the "porcelain" ones) often call internally other git commands (the "plumbing" ones). See rev-parse man page:

Many git porcelainish commands take mixture of flags (i.e. parameters that begin with a dash '-') and parameters meant for the underlying git rev-list command they use internally and flags and parameters for the other commands they use downstream of git rev-list. This command is used to distinguish between them.

How to get a random number in Ruby

Use rand(range)

From Ruby Random Numbers:

If you needed a random integer to simulate a roll of a six-sided die, you'd use: 1 + rand(6). A roll in craps could be simulated with 2 + rand(6) + rand(6).

Finally, if you just need a random float, just call rand with no arguments.


As Marc-André Lafortune mentions in his answer below (go upvote it), Ruby 1.9.2 has its own Random class (that Marc-André himself helped to debug, hence the 1.9.2 target for that feature).

For instance, in this game where you need to guess 10 numbers, you can initialize them with:

10.times.map{ 20 + Random.rand(11) } 
#=> [26, 26, 22, 20, 30, 26, 23, 23, 25, 22]

Note:

This is why the equivalent of Random.new.rand(20..30) would be 20 + Random.rand(11), since Random.rand(int) returns “a random integer greater than or equal to zero and less than the argument.” 20..30 includes 30, I need to come up with a random number between 0 and 11, excluding 11.

OpenCV error: the function is not implemented

Don't waste your time trying to resolve this issue, this was made clear by the makers themselves. Instead of cv2.imshow() use this:

img = cv2.imread('path_to_image')
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([])  # to hide tick values on X and Y axis
plt.show()

How do I set combobox read-only or user cannot write in a combo box only can select the given items?

The solution is to change the DropDownStyle property to DropDownList. It will help.

Path of currently executing powershell script

From Get-ScriptDirectory to the Rescue blog entry ...

function Get-ScriptDirectory
{
  $Invocation = (Get-Variable MyInvocation -Scope 1).Value
  Split-Path $Invocation.MyCommand.Path
}

What's the use of ob_start() in php?

I use this so I can break out of PHP with a lot of HTML but not render it. It saves me from storing it as a string which disables IDE color-coding.

<?php
ob_start();
?>
<div>
    <span>text</span>
    <a href="#">link</a>
</div>
<?php
$content = ob_get_clean();
?>

Instead of:

<?php
$content = '<div>
    <span>text</span>
    <a href="#">link</a>
</div>';
?>

JSON.parse vs. eval()

All JSON.parse implementations most likely use eval()

JSON.parse is based on Douglas Crockford's solution, which uses eval() right there on line 497.

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

j = eval('(' + text + ')');

The advantage of JSON.parse is that it verifies the argument is correct JSON syntax.

How can I view the Git history in Visual Studio Code?

It is evident to me that GitLens is the most popular extension for Git history.

enter image description here

What I like the most it can provide you side annotations when some line has been changed the last time and by whom.

Enter image description here

How are zlib, gzip and zip related? What do they have in common and how are they different?

The most important difference is that gzip is only capable to compress a single file while zip compresses multiple files one by one and archives them into one single file afterwards. Thus, gzip comes along with tar most of the time (there are other possibilities, though). This comes along with some (dis)advantages.

If you have a big archive and you only need one single file out of it, you have to decompress the whole gzip file to get to that file. This is not required if you have a zip file.

On the other hand, if you compress 10 similiar or even identical files, the zip archive will be much bigger because each file is compressed individually, whereas in gzip in combination with tar a single file is compressed which is much more effective if the files are similiar (equal).

How to count duplicate value in an array in javascript

Duplicates in an array containing alphabets:

_x000D_
_x000D_
var arr = ["a", "b", "a", "z", "e", "a", "b", "f", "d", "f"],_x000D_
  sortedArr = [],_x000D_
  count = 1;_x000D_
_x000D_
sortedArr = arr.sort();_x000D_
_x000D_
for (var i = 0; i < sortedArr.length; i = i + count) {_x000D_
  count = 1;_x000D_
  for (var j = i + 1; j < sortedArr.length; j++) {_x000D_
    if (sortedArr[i] === sortedArr[j])_x000D_
      count++;_x000D_
  }_x000D_
  document.write(sortedArr[i] + " = " + count + "<br>");_x000D_
}
_x000D_
_x000D_
_x000D_

Duplicates in an array containing numbers:

_x000D_
_x000D_
var arr = [2, 1, 3, 2, 8, 9, 1, 3, 1, 1, 1, 2, 24, 25, 67, 10, 54, 2, 1, 9, 8, 1],_x000D_
  sortedArr = [],_x000D_
  count = 1;_x000D_
sortedArr = arr.sort(function(a, b) {_x000D_
  return a - b_x000D_
});_x000D_
for (var i = 0; i < sortedArr.length; i = i + count) {_x000D_
  count = 1;_x000D_
  for (var j = i + 1; j < sortedArr.length; j++) {_x000D_
    if (sortedArr[i] === sortedArr[j])_x000D_
      count++;_x000D_
  }_x000D_
  document.write(sortedArr[i] + " = " + count + "<br>");_x000D_
}
_x000D_
_x000D_
_x000D_

Why call git branch --unset-upstream to fixup?

TL;DR version: remote-tracking branch origin/master used to exist, but does not now, so local branch source is tracking something that does not exist, which is suspicious at best—it means a different Git feature is unable to do anything for you—and Git is warning you about it. You have been getting along just fine without having the "upstream tracking" feature work as intended, so it's up to you whether to change anything.

For another take on upstream settings, see Why do I have to "git push --set-upstream origin <branch>"?


This warning is a new thing in Git, appearing first in Git 1.8.5. The release notes contain just one short bullet-item about it:

  • "git branch -v -v" (and "git status") did not distinguish among a branch that is not based on any other branch, a branch that is in sync with its upstream branch, and a branch that is configured with an upstream branch that no longer exists.

To describe what it means, you first need to know about "remotes", "remote-tracking branches", and how Git handles "tracking an upstream". (Remote-tracking branches is a terribly flawed term—I've started using remote-tracking names instead, which I think is a slight improvement. Below, though, I'll use "remote-tracking branch" for consistency with Git documentation.)

Each "remote" is simply a name, like origin or octopress in this case. Their purpose is to record things like the full URL of the places from which you git fetch or git pull updates. When you use git fetch remote,1 Git goes to that remote (using the saved URL) and brings over the appropriate set of updates. It also records the updates, using "remote-tracking branches".

A "remote-tracking branch" (or remote-tracking name) is simply a recording of a branch name as-last-seen on some "remote". Each remote is itself a Git repository, so it has branches. The branches on remote "origin" are recorded in your local repository under remotes/origin/. The text you showed says that there's a branch named source on origin, and branches named 2.1, linklog, and so on on octopress.

(A "normal" or "local" branch, of course, is just a branch-name that you have created in your own repository.)

Last, you can set up a (local) branch to "track" a "remote-tracking branch". Once local branch L is set to track remote-tracking branch R, Git will call R its "upstream" and tell you whether you're "ahead" and/or "behind" the upstream (in terms of commits). It's normal (even recommend-able) for the local branch and remote-tracking branches to use the same name (except for the remote prefix part), like source and origin/source, but that's not actually necessary.

And in this case, that's not happening. You have a local branch source tracking a remote-tracking branch origin/master.

You're not supposed to need to know the exact mechanics of how Git sets up a local branch to track a remote one, but they are relevant below, so I'll show how this works. We start with your local branch name, source. There are two configuration entries using this name, spelled branch.source.remote and branch.source.merge. From the output you showed, it's clear that these are both set, so that you'd see the following if you ran the given commands:

$ git config --get branch.source.remote
origin
$ git config --get branch.source.merge
refs/heads/master

Putting these together,2 this tells Git that your branch source tracks your "remote-tracking branch", origin/master.

But now look at the output of git branch -a, which shows all the local and remote-tracking branch names in your repository. The remote-tracking names are listed under remotes/ ... and there is no remotes/origin/master. Presumably there was, at one time, but it's gone now.

Git is telling you that you can remove the tracking information with --unset-upstream. This will clear out both branch.source.origin and branch.source.merge, and stop the warning.

It seems fairly likely that what you want, though, is to switch from tracking origin/master, to tracking something else: probably origin/source, but maybe one of the octopress/ names.

You can do this with git branch --set-upstream-to,3 e.g.:

$ git branch --set-upstream-to=origin/source

(assuming you're still on branch "source", and that origin/source is the upstream you want—there is no way for me to tell which one, if any, you actually want, though).

(See also How do you make an existing Git branch track a remote branch?)

I think the way you got here is that when you first did a git clone, the thing you cloned-from had a branch master. You also had a branch master, which was set to track origin/master (this is a normal, standard setup for git). This meant you had branch.master.remote and branch.master.merge set, to origin and refs/heads/master. But then your origin remote changed its name from master to source. To match, I believe you also changed your local name from master to source. This changed the names of your settings, from branch.master.remote to branch.source.remote and from branch.master.merge to branch.source.merge ... but it left the old values, so branch.source.merge was now wrong.

It was at this point that the "upstream" linkage broke, but in Git versions older than 1.8.5, Git never noticed the broken setting. Now that you have 1.8.5, it's pointing this out.


That covers most of the questions, but not the "do I need to fix it" one. It's likely that you have been working around the broken-ness for years now, by doing git pull remote branch (e.g., git pull origin source). If you keep doing that, it will keep working around the problem—so, no, you don't need to fix it. If you like, you can use --unset-upstream to remove the upstream and stop the complaints, and not have local branch source marked as having any upstream at all.

The point of having an upstream is to make various operations more convenient. For instance, git fetch followed by git merge will generally "do the right thing" if the upstream is set correctly, and git status after git fetch will tell you whether your repo matches the upstream one, for that branch.

If you want the convenience, re-set the upstream.


1git pull uses git fetch, and as of Git 1.8.4, this (finally!) also updates the "remote-tracking branch" information. In older versions of Git, the updates did not get recorded in remote-tracking branches with git pull, only with git fetch. Since your Git must be at least version 1.8.5 this is not an issue for you.

2Well, this plus a configuration line I'm deliberately ignoring that is found under remote.origin.fetch. Git has to map the "merge" name to figure out that the full local name for the remote-branch is refs/remotes/origin/master. The mapping almost always works just like this, though, so it's predictable that master goes to origin/master.

3Or, with git config. If you just want to set the upstream to origin/source the only part that has to change is branch.source.merge, and git config branch.source.merge refs/heads/source would do it. But --set-upstream-to says what you want done, rather than making you go do it yourself manually, so that's a "better way".

How to make Visual Studio copy a DLL file to the output directory?

$(OutDir) turned out to be a relative path in VS2013, so I had to combine it with $(ProjectDir) to achieve the desired effect:

xcopy /y /d  "$(ProjectDir)External\*.dll" "$(ProjectDir)$(OutDir)"

BTW, you can easily debug the scripts by adding 'echo ' at the beginning and observe the expanded text in the build output window.

What is "Signal 15 received"

This indicates the linux has delivered a SIGTERM to your process. This is usually at the request of some other process (via kill()) but could also be sent by your process to itself (using raise()). This signal requests an orderly shutdown of your process.

If you need a quick cheatsheet of signal numbers, open a bash shell and:

$ kill -l
 1) SIGHUP   2) SIGINT   3) SIGQUIT  4) SIGILL
 5) SIGTRAP  6) SIGABRT  7) SIGBUS   8) SIGFPE
 9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG  24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM   27) SIGPROF 28) SIGWINCH
29) SIGIO   30) SIGPWR  31) SIGSYS  34) SIGRTMIN
35) SIGRTMIN+1  36) SIGRTMIN+2  37) SIGRTMIN+3  38) SIGRTMIN+4
39) SIGRTMIN+5  40) SIGRTMIN+6  41) SIGRTMIN+7  42) SIGRTMIN+8
43) SIGRTMIN+9  44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9  56) SIGRTMAX-8  57) SIGRTMAX-7  58) SIGRTMAX-6
59) SIGRTMAX-5  60) SIGRTMAX-4  61) SIGRTMAX-3  62) SIGRTMAX-2
63) SIGRTMAX-1  64) SIGRTMAX    

You can determine the sender by using an appropriate signal handler like:

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>

void sigterm_handler(int signal, siginfo_t *info, void *_unused)
{
  fprintf(stderr, "Received SIGTERM from process with pid = %u\n",
      info->si_pid);
  exit(0);
}

int main (void)
{
  struct sigaction action = {
    .sa_handler = NULL,
    .sa_sigaction = sigterm_handler,
    .sa_mask = 0,
    .sa_flags = SA_SIGINFO,
    .sa_restorer = NULL
  };

  sigaction(SIGTERM, &action, NULL);
  sleep(60);

  return 0;
}

Notice that the signal handler also includes a call to exit(). It's also possible for your program to continue to execute by ignoring the signal, but this isn't recommended in general (if it's a user doing it there's a good chance it will be followed by a SIGKILL if your process doesn't exit, and you lost your opportunity to do any cleanup then).

Expression must have class type

Allow an analysis.

#include <iostream>   // not #include "iostream"
using namespace std;  // in this case okay, but never do that in header files

class A
{
 public:
  void f() { cout<<"f()\n"; }
};

int main()
{
 /*
 // A a; //this works
 A *a = new A(); //this doesn't
 a.f(); // "f has not been declared"
 */ // below


 // system("pause");  <-- Don't do this. It is non-portable code. I guess your 
 //                       teacher told you this?
 //                       Better: In your IDE there is prolly an option somewhere
 //                               to not close the terminal/console-window.
 //                       If you compile on a CLI, it is not needed at all.
}

As a general advice:

0) Prefer automatic variables
  int a;
  MyClass myInstance;
  std::vector<int> myIntVector;

1) If you need data sharing on big objects down 
   the call hierarchy, prefer references:

  void foo (std::vector<int> const &input) {...}
  void bar () { 
       std::vector<int> something;
       ...
       foo (something);
  }


2) If you need data sharing up the call hierarchy, prefer smart-pointers
   that automatically manage deletion and reference counting.

3) If you need an array, use std::vector<> instead in most cases.
   std::vector<> is ought to be the one default container.

4) I've yet to find a good reason for blank pointers.

   -> Hard to get right exception safe

       class Foo {
           Foo () : a(new int[512]), b(new int[512]) {}
           ~Foo() {
               delete [] b;
               delete [] a;
           }
       };

       -> if the second new[] fails, Foo leaks memory, because the
          destructor is never called. Avoid this easily by using 
          one of the standard containers, like std::vector, or
          smart-pointers.

As a rule of thumb: If you need to manage memory on your own, there is generally a superiour manager or alternative available already, one that follows the RAII principle.

Keytool is not recognized as an internal or external command

Execute following command:

set PATH="C:\Program Files (x86)\Java\jre7"

(whichever JRE exists in case of 64bit).

Because your Java Path is not set so you can just do this at command line and then execute the keytool import command.

How can I show a hidden div when a select option is selected?

you can use the following common function.

<div>
     <select class="form-control" 
             name="Extension for area validity sought for" 
             onchange="CommonShowHide('txtc1opt2', this, 'States')"
     >
         <option value="All India">All India</option>
         <option value="States">States</option>
     </select>

     <input type="text" 
            id="txtc1opt2" 
            style="display:none;" 
            name="Extension for area validity sought for details" 
            class="form-control" 
            value="" 
            placeholder="">

</div>
<script>
    function CommonShowHide(ElementId, element, value) {
         document
             .getElementById(ElementId)
             .style
             .display = element.value == value ? 'block' : 'none';
    }
</script>

Git : fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists

This usually happens when you use two ssh keys to access two different GitHub account.

Follow these steps to fix this it look too long but trust me it won't take more than 5 minutes:

Step-1: Create two ssh key pairs:

ssh-keygen -t rsa -C "[email protected]"

Step-2: It will create two ssh keys here:

~/.ssh/id_rsa_account1
~/.ssh/id_rsa_account2

Step-3: Now we need to add these keys:

ssh-add ~/.ssh/id_rsa_account2
ssh-add ~/.ssh/id_rsa_account1
  • You can see the added keys list by using this command: ssh-add -l
  • You can remove old cached keys by this command: ssh-add -D

Step-4: Modify the ssh config

cd ~/.ssh/
touch config

subl -a config or code config or nano config

Step-5: Add this to config file:

#Github account1
Host github.com-account1
    HostName github.com
    User account1
    IdentityFile ~/.ssh/id_rsa_account1

#Github account2
Host github.com-account2
    HostName github.com
    User account2
    IdentityFile ~/.ssh/id_rsa_account2

Step-6: Update your .git/config file:

Step-6.1: Navigate to account1's project and update host:

[remote "origin"]
        url = [email protected]:account1/gfs.git

If you are invited by some other user in their git Repository. Then you need to update the host like this:

[remote "origin"]
            url = [email protected]:invitedByUserName/gfs.git

Step-6.2: Navigate to account2's project and update host:

[remote "origin"]
        url = [email protected]:account2/gfs.git

Step-7: Update user name and email for each repository separately if required this is not an amendatory step:

Navigate to account1 project and run these:

git config user.name "account1"
git config user.email "[email protected]" 

Navigate to account2 project and run these:

git config user.name "account2"
git config user.email "[email protected]" 

How to implement DrawerArrowToggle from Android appcompat v7 21 library

First, you should know now the android.support.v4.app.ActionBarDrawerToggle is deprecated.

You must replace that with android.support.v7.app.ActionBarDrawerToggle.

Here is my example and I use the new Toolbar to replace the ActionBar.

MainActivity.java

public class MainActivity extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(mToolbar);
    DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(
        this,  mDrawerLayout, mToolbar,
        R.string.navigation_drawer_open, R.string.navigation_drawer_close
    );
    mDrawerLayout.setDrawerListener(mDrawerToggle);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);
    mDrawerToggle.syncState();
}

styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light">
    <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
</style>

<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
    <item name="spinBars">true</item>
    <item name="color">@android:color/white</item>
</style>

You can read the documents on AndroidDocument#DrawerArrowToggle_spinBars

This attribute is the key to implement the menu-to-arrow animation.

public static int DrawerArrowToggle_spinBars

Whether bars should rotate or not during transition
Must be a boolean value, either "true" or "false".

So, you set this: <item name="spinBars">true</item>.

Then the animation can be presented.

Hope this can help you.

Java: object to byte[] and byte[] to object converter (for Tokyo Cabinet)

You can look at how Hector does this for Cassandra, where the goal is the same - convert everything to and from byte[] in order to store/retrieve from a NoSQL database - see here. For the primitive types (+String), there are special Serializers, otherwise there is the generic ObjectSerializer (expecting Serializable, and using ObjectOutputStream). You can, of course, use only it for everything, but there might be redundant meta-data in the serialized form.

I guess you can copy the entire package and make use of it.

How do I read any request header in PHP

This small PHP snippet can be helpful to you:

<?php
foreach($_SERVER as $key => $value){
echo '$_SERVER["'.$key.'"] = '.$value."<br />";
}
?>

What does appending "?v=1" to CSS and JavaScript URLs in link and script tags do?

As mentioned by others, this is used for front end cache busting. To implement this, I have personally find grunt-cache-bust npm package useful.

Total Number of Row Resultset getRow Method

The getRow() method will always yield 0 after a query:

ResultSet.getRow()

Retrieves the current row number.

Second, you output totalrec but never assign anything to it.

Saving an image in OpenCV

I suggest you run OpenCV sanity check

Its a serie of small executables located in the bin directory of opencv.

It will check if your camera is ok

How to reference a .css file on a razor view?

For CSS that are reused among the entire site I define them in the <head> section of the _Layout:

<head>
    <link href="@Url.Content("~/Styles/main.css")" rel="stylesheet" type="text/css" />
    @RenderSection("Styles", false)
</head>

and if I need some view specific styles I define the Styles section in each view:

@section Styles {
    <link href="@Url.Content("~/Styles/view_specific_style.css")" rel="stylesheet" type="text/css" />
}

Edit: It's useful to know that the second parameter in @RenderSection, false, means that the section is not required on a view that uses this master page, and the view engine will blissfully ignore the fact that there is no "Styles" section defined in your view. If true, the view won't render and an error will be thrown unless the "Styles" section has been defined.

How to Display blob (.pdf) in an AngularJS app

A suggestion of code that I just used in my project using AngularJS v1.7.2

$http.get('LabelsPDF?ids=' + ids, { responseType: 'arraybuffer' })
            .then(function (response) {
                var file = new Blob([response.data], { type: 'application/pdf' });
                var fileURL = URL.createObjectURL(file);
                $scope.ContentPDF = $sce.trustAsResourceUrl(fileURL);
            });

<embed ng-src="{{ContentPDF}}" type="application/pdf" class="col-xs-12" style="height:100px; text-align:center;" />

How to determine the current language of a wordpress page when using polylang?

We can use the get_locale function:

if (get_locale() == 'en_GB') {
    // drink tea
}

No connection could be made because the target machine actively refused it 127.0.0.1

I had the same issue with a site which previously was running fine. I resolved the issue by deleting the temporary files from C:\WINDOWS\Microsoft.NET\Framework\v#.#.#####\Temporary ASP.NET Files\@projectName\###CC##C\###C#CC

Header div stays at top, vertical scrolling div below with scrollbar only attached to that div

You need to use js get better height for body div

<html><body>
<div id="head" style="height:50px; width=100%; font-size:50px;">This is head</div>
<div id="body" style="height:700px; font-size:100px; white-space:pre-wrap;    overflow:scroll;">
This is body
T
h
i
s

i
s

b 
o
d
y
</div>
</body></html>

Angular directive how to add an attribute to the element?

A directive which adds another directive to the same element:

Similar answers:

Here is a plunker: http://plnkr.co/edit/ziU8d826WF6SwQllHHQq?p=preview

app.directive("myDir", function($compile) {
  return {
    priority:1001, // compiles first
    terminal:true, // prevent lower priority directives to compile after it
    compile: function(el) {
      el.removeAttr('my-dir'); // necessary to avoid infinite compile loop
      el.attr('ng-click', 'fxn()');
      var fn = $compile(el);
      return function(scope){
        fn(scope);
      };
    }
  };
});

Much cleaner solution - not to use ngClick at all:

A plunker: http://plnkr.co/edit/jY10enUVm31BwvLkDIAO?p=preview

app.directive("myDir", function($parse) {
  return {
    compile: function(tElm,tAttrs){
      var exp = $parse('fxn()');
      return function (scope,elm){
        elm.bind('click',function(){
          exp(scope);
        });  
      };
    }
  };
});

How do I read CSV data into a record array in NumPy?

This work as a charm...

import csv
with open("data.csv", 'r') as f:
    data = list(csv.reader(f, delimiter=";"))

import numpy as np
data = np.array(data, dtype=np.float)

New Array from Index Range Swift

One more variant using extension and argument name range

This extension uses Range and ClosedRange

extension Array {

    subscript (range r: Range<Int>) -> Array {
        return Array(self[r])
    }


    subscript (range r: ClosedRange<Int>) -> Array {
        return Array(self[r])
    }
}

Tests:

func testArraySubscriptRange() {
    //given
    let arr = ["1", "2", "3"]

    //when
    let result = arr[range: 1..<arr.count] as Array

    //then
    XCTAssertEqual(["2", "3"], result)
}

func testArraySubscriptClosedRange() {
    //given
    let arr = ["1", "2", "3"]

    //when
    let result = arr[range: 1...arr.count - 1] as Array

    //then
    XCTAssertEqual(["2", "3"], result)
}

How do I loop through rows with a data reader in C#?

There is no way to get "the whole row" at once - you need to loop through the rows, and for each row, you need to read each column separately:

using(SqlDataReader rdr = cmd.ExecuteReader())
{
    while (rdr.Read())
    {
        string value1 = rdr.GetString(0);
        string value2 = rdr.GetString(1);
        string value3 = rdr.GetString(2);
    }
}

What you do with those strings that you read for each row is entirely up to you - you could store them into a class that you've defined, or whatever....

Detecting real time window size changes in Angular 4

@HostListener("window:resize", [])
public onResize() {
  this.detectScreenSize();
}

public ngAfterViewInit() {
    this.detectScreenSize();
}

private detectScreenSize() {
    const height = window.innerHeight;
    const width = window.innerWidth;
}

Angular - Can't make ng-repeat orderBy work

As mentioned, only arrays are allowed. But to make it simple for you, you could dynamically convert the object into an array via a piping function as seen here https://gist.github.com/brev/3949705

Just declare the filter, and add it to ng-repeat :)

<div ng-app="myApp">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<div ng-controller="Main">
  <div ng-repeat="release in releases | object2Array | orderBy:'environment_id'">{{release.environment_id}}</div>
</div>

<script>

var app = angular.module('myApp', []).filter('object2Array', function() {
    return function(input) {
      var out = []; 
      for(i in input){
        out.push(input[i]);
      }
      return out;
    }
  })
.controller('Main',function ($scope) {
        $scope.releases = {"tvl-c-wbap001 + tvl-webapp":{"timestamp":" 05:05:53 PM ","environment_id":"CERT5","release_header":"Projects/Dev","date":"19 Oct","release":"12.11.91-1"},"tvl-c-wbap401 + tvl-webapp":{"timestamp":" 10:07:25 AM ","environment_id":"CERT4","release_header":"Future Release","date":"15 Oct","release":"485-1"},"tvl-c-wbap301 + tvl-webapp":{"timestamp":" 07:59:48 AM ","environment_id":"CERT3","release_header":"Next Release","date":"15 Oct","release":"485-1"},"tvl-c-wbap201 + tvl-webapp":{"timestamp":" 03:34:07 AM ","environment_id":"CERT2","release_header":"Next Changes","date":"15 Oct","release":"13.12.3-1"},"tvl-c-wbap101 + tvl-webapp":{"timestamp":" 12:44:23 AM ","environment_id":"CERT1","release_header":"Production Mirror","date":"15 Oct","release":"13.11.309-1"},"tvl-s-wbap002 + tvl-webapp":{"timestamp":" 12:43:23 AM ","environment_id":"Stage2","date":"15 Oct","release":"13.11.310-1"},"tvl-s-wbap001 + tvl-webapp":{"timestamp":" 11:07:38 AM ","environment_id":"Stage1","release_header":"Production Mirror","date":"11 Oct","release":"13.11.310-1"},"tvl-p-wbap001 + tvl-webapp":{"timestamp":" 11:39:25 PM ","environment_id":"Production","release_header":"Pilots","date":"14 Oct","release":"13.11.310-1"},"tvl-p-wbap100 + tvl-webapp":{"timestamp":" 03:27:53 AM ","environment_id":"Production","release_header":"Non Pilots","date":"11 Oct","release":"13.11.309-1"}}
    });
</script>

Oracle: how to add minutes to a timestamp?

SELECT to_char(sysdate + (1/24/60) * 30, 'dd/mm/yy HH24:MI am') from dual;

simply you can use this with various date format....

How to create a link for all mobile devices that opens google maps with a route starting at the current location, destinating a given place?

if (navigator.geolocation) { //Checks if browser supports geolocation
navigator.geolocation.getCurrentPosition(function (position) {                                                                                            
 var latitude = position.coords.latitude;                    //users current
 var longitude = position.coords.longitude;                 //location
 var coords = new google.maps.LatLng(latitude, longitude); //Creates variable for map coordinates
 var directionsService = new google.maps.DirectionsService();
 var directionsDisplay = new google.maps.DirectionsRenderer();
 var mapOptions = //Sets map options
 {
   zoom: 15,  //Sets zoom level (0-21)
   center: coords, //zoom in on users location
   mapTypeControl: true, //allows you to select map type eg. map or satellite
   navigationControlOptions:
   {
     style: google.maps.NavigationControlStyle.SMALL //sets map controls size eg. zoom
   },
   mapTypeId: google.maps.MapTypeId.ROADMAP //sets type of map Options:ROADMAP, SATELLITE, HYBRID, TERRIAN
 };
 map = new google.maps.Map( /*creates Map variable*/ document.getElementById("map"),    mapOptions /*Creates a new map using the passed optional parameters in the mapOptions parameter.*/);
 directionsDisplay.setMap(map);
 directionsDisplay.setPanel(document.getElementById('panel'));
 var request = {
   origin: coords,
   destination: 'BT42 1FL',
   travelMode: google.maps.DirectionsTravelMode.DRIVING
 };

 directionsService.route(request, function (response, status) {
   if (status == google.maps.DirectionsStatus.OK) {
     directionsDisplay.setDirections(response);
   }
 });
 });
 }

adding text to an existing text element in javascript via DOM

What about this.

_x000D_
_x000D_
var p = document.getElementById("p")_x000D_
p.innerText = p.innerText+" And this is addon."
_x000D_
<p id ="p">This is some text</p>
_x000D_
_x000D_
_x000D_

Postgres password authentication fails

I came across this question, and the answers here didn't work for me; i couldn't figure out why i can't login and got the above error.

It turns out that postgresql saves usernames lowercase, but during authentication it uses both upper- and lowercase.

CREATE USER myNewUser WITH PASSWORD 'passWord';

will create a user with the username 'mynewuser' and password 'passWord'.

This means you have to authenticate with 'mynewuser', and not with 'myNewUser'. For a newbie in pgsql like me, this was confusing. I hope it helps others who run into this problem.

Bootstrap 3: Offset isn't working?

There is no col-??-offset-0. All "rows" assume there is no offset unless it has been specified. I think you are wanting 3 rows on a small screen and 1 row on a medium screen.

To get the result I believe you are looking for try this:

<div class="container">
    <div class="row">
      <div class="col-sm-4 col-md-12">
        <p>On small screen there are 3 rows, and on a medium screen 1 row</p>
      </div>
      <div class="col-sm-4 col-md-12">
        <p>On small screen there are 3 rows, and on a medium screen 1 row</p>
      </div>
      <div class="col-sm-4 col-md-12">
        <p>On small screen there are 3 rows, and on a medium screen 1 row</p>
      </div>
    </div>
  </div>

Keep in mind you will only see a difference on a small tablet with what you described. Medium, large, and extra small screens the columns are spanning 12.

Hope this helps.

Efficient method to generate UUID String in JAVA (UUID.randomUUID().toString() without the dashes)

I have just copied UUID toString() method and just updated it to remove "-" from it. It will be much more faster and straight forward than any other solution

public String generateUUIDString(UUID uuid) {
    return (digits(uuid.getMostSignificantBits() >> 32, 8) +
            digits(uuid.getMostSignificantBits() >> 16, 4) +
            digits(uuid.getMostSignificantBits(), 4) +
            digits(uuid.getLeastSignificantBits() >> 48, 4) +
            digits(uuid.getLeastSignificantBits(), 12));
}

/** Returns val represented by the specified number of hex digits. */
private String digits(long val, int digits) {
    long hi = 1L << (digits * 4);
    return Long.toHexString(hi | (val & (hi - 1))).substring(1);
}

Usage:

generateUUIDString(UUID.randomUUID())

Another implementation using reflection

public String generateString(UUID uuid) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

    if (uuid == null) {
        return "";
    }

    Method digits = UUID.class.getDeclaredMethod("digits", long.class, int.class);
    digits.setAccessible(true);

    return ( (String) digits.invoke(uuid, uuid.getMostSignificantBits() >> 32, 8) +
            digits.invoke(uuid, uuid.getMostSignificantBits() >> 16, 4) +
            digits.invoke(uuid, uuid.getMostSignificantBits(), 4) +
            digits.invoke(uuid, uuid.getLeastSignificantBits() >> 48, 4) +
            digits.invoke(uuid, uuid.getLeastSignificantBits(), 12));

}

Difference between return 1, return 0, return -1 and exit?

return in function return execution back to caller and exit from function terminates the program.

in main function return 0 or exit(0) are same but if you write exit(0) in different function then you program will exit from that position.

returning different values like return 1 or return -1 means that program is returning error .

When exit(0) is used to exit from program, destructors for locally scoped non-static objects are not called. But destructors are called if return 0 is used.

Difference between os.getenv and os.environ.get

In addition to the answers above:

$ python3 -m timeit -s 'import os' 'os.environ.get("TERM_PROGRAM")'
200000 loops, best of 5: 1.65 usec per loop

$ python3 -m timeit -s 'import os' 'os.getenv("TERM_PROGRAM")'
200000 loops, best of 5: 1.83 usec per loop

CSS3 selector to find the 2nd div of the same class

Selectors can be combined:

.bar:nth-child(2)

means "thing that has class bar" that is also the 2nd child.

How do I bind onchange event of a TextBox using JQuery?

Combination of keyup and change is not necessarily enough (browser's autocomplete and paste using mouse also changes the contents of a text box, but doesn't fire either of these events):

jquery change not working incase of dynamic value change

HashMap get/put complexity

HashMap operation is dependent factor of hashCode implementation. For the ideal scenario lets say the good hash implementation which provide unique hash code for every object (No hash collision) then the best, worst and average case scenario would be O(1). Let's consider a scenario where a bad implementation of hashCode always returns 1 or such hash which has hash collision. In this case the time complexity would be O(n).

Now coming to the second part of the question about memory, then yes memory constraint would be taken care by JVM.

how to make a cell of table hyperlink

Why not combine the onclick method with the <a> element inside the <td> for backup for non-JS? Seems to work great.

<td onclick="location.href='yourpage.html'"><a href="yourpage.html">Link</a></td>

React Native absolute positioning horizontal centre

It's very simple really. Use percentage for width and left properties. For example:

logo : {
  position: 'absolute',
  top : 50,
  left: '30%',
  zIndex: 1,
  width: '40%',
  height: 150,
}

Whatever width is, left equals (100% - width)/2

C++ static virtual members?

It is possible!

But what exactly is possible, let's narrow down. People often want some kind of "static virtual function" because of duplication of code needed for being able to call the same function through static call "SomeDerivedClass::myfunction()" and polymorphic call "base_class_pointer->myfunction()". "Legal" method for allowing such functionality is duplication of function definitions:

class Object
{
public:
    static string getTypeInformationStatic() { return "base class";}
    virtual string getTypeInformation() { return getTypeInformationStatic(); }
}; 
class Foo: public Object
{
public:
    static string getTypeInformationStatic() { return "derived class";}
    virtual string getTypeInformation() { return getTypeInformationStatic(); }
};

What if base class has a great number of static functions and derived class has to override every of them and one forgot to provide a duplicating definition for virtual function. Right, we'll get some strange error during runtime which is hard to track down. Cause duplication of code is a bad thing. The following tries to resolve this problem (and I want to tell beforehand that it is completely type-safe and doesn't contain any black magic like typeid's or dynamic_cast's :)

So, we want to provide only one definition of getTypeInformation() per derived class and it is obvious that it has to be a definition of static function because it is not possible to call "SomeDerivedClass::getTypeInformation()" if getTypeInformation() is virtual. How can we call static function of derived class through pointer to base class? It is not possible with vtable because vtable stores pointers only to virtual functions and since we decided not to use virtual functions, we cannot modify vtable for our benefit. Then, to be able to access static function for derived class through pointer to base class we have to store somehow the type of an object within its base class. One approach is to make base class templatized using "curiously recurring template pattern" but it is not appropriate here and we'll use a technique called "type erasure":

class TypeKeeper
{
public:
    virtual string getTypeInformation() = 0;
};
template<class T>
class TypeKeeperImpl: public TypeKeeper
{
public:
    virtual string getTypeInformation() { return T::getTypeInformationStatic(); }
};

Now we can store the type of an object within base class "Object" with a variable "keeper":

class Object
{
public:
    Object(){}
    boost::scoped_ptr<TypeKeeper> keeper;

    //not virtual
    string getTypeInformation() const 
    { return keeper? keeper->getTypeInformation(): string("base class"); }

};

In a derived class keeper must be initialized during construction:

class Foo: public Object
{
public:
    Foo() { keeper.reset(new TypeKeeperImpl<Foo>()); }
    //note the name of the function
    static string getTypeInformationStatic() 
    { return "class for proving static virtual functions concept"; }
};

Let's add syntactic sugar:

template<class T>
void override_static_functions(T* t)
{ t->keeper.reset(new TypeKeeperImpl<T>()); }
#define OVERRIDE_STATIC_FUNCTIONS override_static_functions(this)

Now declarations of descendants look like:

class Foo: public Object
{
public:
    Foo() { OVERRIDE_STATIC_FUNCTIONS; }
    static string getTypeInformationStatic() 
    { return "class for proving static virtual functions concept"; }
};

class Bar: public Foo
{
public:
    Bar() { OVERRIDE_STATIC_FUNCTIONS; }
    static string getTypeInformationStatic() 
    { return "another class for the same reason"; }
};

usage:

Object* obj = new Foo();
cout << obj->getTypeInformation() << endl;  //calls Foo::getTypeInformationStatic()
obj = new Bar();
cout << obj->getTypeInformation() << endl;  //calls Bar::getTypeInformationStatic()
Foo* foo = new Bar();
cout << foo->getTypeInformation() << endl; //calls Bar::getTypeInformationStatic()
Foo::getTypeInformation(); //compile-time error
Foo::getTypeInformationStatic(); //calls Foo::getTypeInformationStatic()
Bar::getTypeInformationStatic(); //calls Bar::getTypeInformationStatic()

Advantages:

  1. less duplication of code (but we have to call OVERRIDE_STATIC_FUNCTIONS in every constructor)

Disadvantages:

  1. OVERRIDE_STATIC_FUNCTIONS in every constructor
  2. memory and performance overhead
  3. increased complexity

Open issues:

1) there are different names for static and virtual functions how to solve ambiguity here?

class Foo
{
public:
    static void f(bool f=true) { cout << "static";}
    virtual void f() { cout << "virtual";}
};
//somewhere
Foo::f(); //calls static f(), no ambiguity
ptr_to_foo->f(); //ambiguity

2) how to implicitly call OVERRIDE_STATIC_FUNCTIONS inside every constructor?

What is the difference between lower bound and tight bound?

The basic difference between

Blockquote

asymptotically upper bound and asymptotically tight Asym.upperbound means a given algorythm that can executes with maximum amount of time depending upon the number of inputs ,for eg in sorting algo if all the array (n)elements are in descending order then for ascending them it will take a running time of O(n) which shows upper bound complexity ,but if they are already sorted then it will take ohm(1).so we generally used "O"notation for upper bound complexity.

Asym. tightbound bound shows the for eg(c1g(n)<=f(n)<=c2g(n)) shows the tight bound limit such that the function have the value in between two bound (upper bound and lower bound),giving the average case.

How to build a Debian/Ubuntu package from source?

First, the title question: Assuming the debian directory is already there, be in the source directory (the directory containing the debian directory) and invoke dpkg-buildpackage. I like to run it with these options:

dpkg-buildpackage -us -uc -nc

which mean don't sign the result and don't clean.

How can I check if I have listed all the dependencies correctly?

Getting the dependencies is a black art. The "official" way is to check build depends is if the package builds with only the base system, the "build-essential" packages, and the build dependencies you have specified. Don't know a general answer for regular Dependencies, just wade in :)

How I can I prevent the update system installing the older version in the repo on an update? How I can prevent the system installing a newer version (when its out), overwriting my custom package?

My knowledge might be out of date on this one, but to address both: Use dpkg --set-selections. Assuming nullidentd was the package you wanted to stay put, run as root

echo 'nullidentd hold' | dpkg --set-selections

Alternately, since you are building from source, you can use an epoch to set the version number artificially high and never be bothered again. To use an epoch, add a new entry to the debian/changelog file, and put a 99: in front of the version number. Given my nullidentd example, the first line of your updated changelog would read:

nullidentd (99:1.0-4) unstable; urgency=low

Bernard's link is good, especially if you have to create the debian directory yourself - also helpful are the developers reference and the general resource page. Adam's link also looks good but I'm not familiar with it.

Is there a NumPy function to return the first index of something in an array?

To index on any criteria, you can so something like the following:

In [1]: from numpy import *
In [2]: x = arange(125).reshape((5,5,5))
In [3]: y = indices(x.shape)
In [4]: locs = y[:,x >= 120] # put whatever you want in place of x >= 120
In [5]: pts = hsplit(locs, len(locs[0]))
In [6]: for pt in pts:
   .....:         print(', '.join(str(p[0]) for p in pt))
4, 4, 0
4, 4, 1
4, 4, 2
4, 4, 3
4, 4, 4

And here's a quick function to do what list.index() does, except doesn't raise an exception if it's not found. Beware -- this is probably very slow on large arrays. You can probably monkey patch this on to arrays if you'd rather use it as a method.

def ndindex(ndarray, item):
    if len(ndarray.shape) == 1:
        try:
            return [ndarray.tolist().index(item)]
        except:
            pass
    else:
        for i, subarray in enumerate(ndarray):
            try:
                return [i] + ndindex(subarray, item)
            except:
                pass

In [1]: ndindex(x, 103)
Out[1]: [4, 0, 3]

Path to Powershell.exe (v 2.0)

I think $PsHome has the information you're after?

PS .> $PsHome
C:\Windows\System32\WindowsPowerShell\v1.0

PS .> Get-Help about_automatic_variables

TOPIC
    about_Automatic_Variables ...

"Rate This App"-link in Google Play store app on the phone

Here is a working and up to date code :)

/*
* Start with rating the app
* Determine if the Play Store is installed on the device
*
* */
public void rateApp()
{
    try
    {
        Intent rateIntent = rateIntentForUrl("market://details");
        startActivity(rateIntent);
    }
    catch (ActivityNotFoundException e)
    {
        Intent rateIntent = rateIntentForUrl("https://play.google.com/store/apps/details");
        startActivity(rateIntent);
    }
}

private Intent rateIntentForUrl(String url)
{
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format("%s?id=%s", url, getPackageName())));
    int flags = Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
    if (Build.VERSION.SDK_INT >= 21)
    {
        flags |= Intent.FLAG_ACTIVITY_NEW_DOCUMENT;
    }
    else
    {
        //noinspection deprecation
        flags |= Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET;
    }
    intent.addFlags(flags);
    return intent;
}

Put the code in the Activity you would like to call it from.
When the user clicks a button to rate the app, just call the rateApp() function.

Why can't Visual Studio find my DLL?

try "configuration properties -> debugging -> environment" and set the PATH variable in run-time

Change header background color of modal of twitter bootstrap

You can solve this by simply adding class to modal-header

<div class="modal-header bg-primary text-white">

Creating a PHP header/footer

the simpler, the better.

index.php

<? 
if (empty($_SERVER['QUERY_STRING'])) { 
  $name="index"; 
} else { 
  $name=basename($_SERVER['QUERY_STRING']); 
} 
$file="txt/".$name.".htm"; 
if (is_readable($file)) { 
  include 'header.php';
  readfile($file);
} else { 
  header("HTTP/1.0 404 Not Found");
  exit;
} 
?>

header.php

<a href="index.php">Main page</a><br>
<a href=?about>About</a><br>
<a href=?links>Links</a><br>
<br><br> 

the actual static html pages stored in the txt folder in the page.htm format

How can I run NUnit tests in Visual Studio 2017?

This one helped me:

Getting started with .NET unit testing using NUnit

Basically:

  • Add the NUnit 3 library in NuGet.
  • Create the class you want to test.
  • Create a separate testing class. This should have [TestFixture] above it.
  • Create a function in the testing class. This should have [Test] above it.
  • Then go into TEST/WINDOW/TEST EXPLORER (across the top).
  • Click run to the left-hand side. It will tell you what has passed and what has failed.

My example code is here:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;

namespace NUnitTesting
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }

    public class Maths
    {
        public int Add(int a, int b)
        {
            int x = a + b;
            return x;
        }
    }

    [TestFixture]
    public class TestLogging
    {
        [Test]
        public void Add()
        {
            Maths add = new Maths();
            int expectedResult = add.Add(1, 2);
            Assert.That(expectedResult, Is.EqualTo(3));
        }
    }
}

This will return true, and if you change the parameter in Is.EqualTo it will fail, etc.

Create aar file in Android Studio

After following the first and second steps mentioned in the hcpl's answer in the same thread, we added , '*.aar'], dir: 'libs' in the our-android-app-project-based-on-gradle/app/build.gradle file as shown below:

...

dependencies {
       implementation fileTree(include: ['*.jar', '*.aar'], dir: 'libs')

...

Our gradle version is com.android.tools.build:gradle:3.2.1

Swap DIV position with CSS only

Someone linked me this: What is the best way to move an element that's on the top to the bottom in Responsive design.

The solution in that worked perfectly. Though it doesn’t support old IE, that doesn’t matter for me, since I’m using responsive design for mobile. And it works for most mobile browsers.

Basically, I had this:

@media (max-width: 30em) {
  .container {
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    -webkit-box-orient: vertical;
    -moz-box-orient: vertical;
    -webkit-flex-direction: column;
    -ms-flex-direction: column;
    flex-direction: column;
    /* optional */
    -webkit-box-align: start;
    -moz-box-align: start;
    -ms-flex-align: start;
    -webkit-align-items: flex-start;
    align-items: flex-start;
  }

  .container .first_div {
    -webkit-box-ordinal-group: 2;
    -moz-box-ordinal-group: 2;
    -ms-flex-order: 2;
    -webkit-order: 2;
    order: 2;
  }

  .container .second_div {
    -webkit-box-ordinal-group: 1;
    -moz-box-ordinal-group: 1;
    -ms-flex-order: 1;
    -webkit-order: 1;
    order: 1;
  }
}

This worked better than floats for me, because I needed them stacked on top of each other and I had about five different divs that I had to swap around the position of.

How to put a link on a button with bootstrap?

You can call a function on click event of button.

<input type="button" class="btn btn-info" value="Input Button" onclick=" relocate_home()">

<script>
function relocate_home()
{
     location.href = "www.yoursite.com";
} 
</script>

OR Use this Code

<a href="#link" class="btn btn-info" role="button">Link Button</a>

Multiple conditions with CASE statements

It's not a cut and paste. The CASE expression must return a value, and you are returning a string containing SQL (which is technically a value but of a wrong type). This is what you wanted to write, I think:

SELECT * FROM [Purchasing].[Vendor] WHERE  
CASE
  WHEN @url IS null OR @url = '' OR @url = 'ALL'
    THEN PurchasingWebServiceURL LIKE '%'
  WHEN @url = 'blank'
    THEN PurchasingWebServiceURL = ''
  WHEN @url = 'fail'
    THEN PurchasingWebServiceURL NOT LIKE '%treyresearch%'
  ELSE PurchasingWebServiceURL = '%' + @url + '%' 
END

I also suspect that this might not work in some dialects, but can't test now (Oracle, I'm looking at you), due to not having booleans.

However, since @url is not dependent on the table values, why not make three different queries, and choose which to evaluate based on your parameter?

convert base64 to image in javascript/jquery

You can just create an Image object and put the base64 as its src, including the data:image... part like this:

var image = new Image();
image.src = 'data:image/png;base64,iVBORw0K...';
document.body.appendChild(image);

It's what they call "Data URIs" and here's the compatibility table for inner peace.

how to use sqltransaction in c#

The following example creates a SqlConnection and a SqlTransaction. It also demonstrates how to use the BeginTransaction, Commit, and Rollback methods. The transaction is rolled back on any error, or if it is disposed without first being committed. Try/Catch error handling is used to handle any errors when attempting to commit or roll back the transaction.

private static void ExecuteSqlTransaction(string connectionString)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();

        SqlCommand command = connection.CreateCommand();
        SqlTransaction transaction;

        // Start a local transaction.
        transaction = connection.BeginTransaction("SampleTransaction");

        // Must assign both transaction object and connection 
        // to Command object for a pending local transaction
        command.Connection = connection;
        command.Transaction = transaction;

        try
        {
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
            command.ExecuteNonQuery();
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
            command.ExecuteNonQuery();

            // Attempt to commit the transaction.
            transaction.Commit();
            Console.WriteLine("Both records are written to database.");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
            Console.WriteLine("  Message: {0}", ex.Message);

            // Attempt to roll back the transaction. 
            try
            {
                transaction.Rollback();
            }
            catch (Exception ex2)
            {
                // This catch block will handle any errors that may have occurred 
                // on the server that would cause the rollback to fail, such as 
                // a closed connection.
                Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
                Console.WriteLine("  Message: {0}", ex2.Message);
            }
        }
    }
}

See SqlTransaction Class

Resizing an iframe based on content

may be a bit late, as all the other answers are older :-) but... here´s my solution. Tested in actual FF, Chrome and Safari 5.0.

css:

iframe {border:0; overflow:hidden;}

javascript:

$(document).ready(function(){
    $("iframe").load( function () {
        var c = (this.contentWindow || this.contentDocument);
        if (c.document) d = c.document;
        var ih = $(d).outerHeight();
        var iw = $(d).outerWidth();
        $(this).css({
            height: ih,
            width: iw
        });
    });
});

Hope this will help anybody.

How do I create a view controller file after creating a new view controller?

Correct, when you drag a view controller object onto your storyboard in order to create a new scene, it doesn't automatically make the new class for you, too.

Having added a new view controller scene to your storyboard, you then have to:

  1. Create a UIViewController subclass. For example, go to your target's folder in the project navigator panel on the left and then control-click and choose "New File...". Choose a "Cocoa Touch Class":

    Cocoa Touch Class

    And then select a unique name for the new view controller subclass:

    UIViewController subclass

  2. Specify this new subclass as the base class for the scene you just added to the storyboard.

    enter image description here

  3. Now hook up any IBOutlet and IBAction references for this new scene with the new view controller subclass.

Python: Importing urllib.quote

This is how I handle this, without using exceptions.

import sys
if sys.version_info.major > 2:  # Python 3 or later
    from urllib.parse import quote
else:  # Python 2
    from urllib import quote

convert nan value to zero

nan is never equal to nan

if z!=z:z=0

so for a 2D array

for entry in nparr:
    if entry!=entry:entry=0

How long is the SHA256 hash?

Why would you make it VARCHAR? It doesn't vary. It's always 64 characters, which can be determined by running anything into one of the online SHA-256 calculators.

What is the size of column of int(11) in mysql in bytes?

In MySQL integer int(11) has size is 4 bytes which equals 32 bit.

Signed value is : -2^(32-1) to 0 to 2^(32-1)-1 = -2147483648 to 0 to 2147483647

Unsigned values is : 0 to 2^32-1 = 0 to 4294967295

Better way to convert file sizes in Python

Instead of a size divisor of 1024 * 1024 you could use the << bitwise shifting operator, i.e. 1<<20 to get megabytes, 1<<30 to get gigabytes, etc.

In the simplest scenario you can have e.g. a constant MBFACTOR = float(1<<20) which can then be used with bytes, i.e.: megas = size_in_bytes/MBFACTOR.

Megabytes are usually all that you need, or otherwise something like this can be used:

# bytes pretty-printing
UNITS_MAPPING = [
    (1<<50, ' PB'),
    (1<<40, ' TB'),
    (1<<30, ' GB'),
    (1<<20, ' MB'),
    (1<<10, ' KB'),
    (1, (' byte', ' bytes')),
]


def pretty_size(bytes, units=UNITS_MAPPING):
    """Get human-readable file sizes.
    simplified version of https://pypi.python.org/pypi/hurry.filesize/
    """
    for factor, suffix in units:
        if bytes >= factor:
            break
    amount = int(bytes / factor)

    if isinstance(suffix, tuple):
        singular, multiple = suffix
        if amount == 1:
            suffix = singular
        else:
            suffix = multiple
    return str(amount) + suffix

print(pretty_size(1))
print(pretty_size(42))
print(pretty_size(4096))
print(pretty_size(238048577))
print(pretty_size(334073741824))
print(pretty_size(96995116277763))
print(pretty_size(3125899904842624))

## [Out] ###########################
1 byte
42 bytes
4 KB
227 MB
311 GB
88 TB
2 PB

Add items in array angular 4

Yes there is a way to do it.

First declare a class.

//anyfile.ts
export class Custom
{
  name: string, 
  empoloyeeID: number
}

Then in your component import the class

import {Custom} from '../path/to/anyfile.ts'
.....
export class FormComponent implements OnInit {
 name: string;
 empoloyeeID : number;
 empList: Array<Custom> = [];
 constructor() {

 }

 ngOnInit() {
 }
 onEmpCreate(){
   //console.log(this.name,this.empoloyeeID);
   let customObj = new Custom();
   customObj.name = "something";
   customObj.employeeId = 12; 
   this.empList.push(customObj);
   this.name ="";
   this.empoloyeeID = 0; 
 }
}

Another way would be to interfaces read the documentation once - https://www.typescriptlang.org/docs/handbook/interfaces.html

Also checkout this question, it is very interesting - When to use Interface and Model in TypeScript / Angular2

Valid content-type for XML, HTML and XHTML documents

HTML: text/html, full-stop.

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

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

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

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

Best approach to converting Boolean object to string in java

If this is for the purpose of getting a constant "true" value, rather than "True" or "TRUE", you can use this:

Boolean.TRUE.toString();
Boolean.FALSE.toString();

What is the most efficient way to loop through dataframes with pandas?

Another suggestion would be to combine groupby with vectorized calculations if subsets of the rows shared characteristics which allowed you to do so.

Where can I find the assembly System.Web.Extensions dll?

The assembly was introduced with .NET 3.5 and is in the GAC.

Simply add a .NET reference to your project.

Project -> Right Click References -> Select .NET tab -> System.Web.Extensions

If it is not there, you need to install .NET 3.5 or 4.0.

how to split the ng-repeat data with three columns using bootstrap

Following is a more simple way:

<table>
    <tr ng-repeat="item in lists" ng-hide="$index%2!==0">
        <td>
            <label>{{ lists[$index].name}}</label>
        </td>
        <td ng-hide="!lists[$index+1]">
            <label>{{ lists[$index+1].name}}</label>
        </td>
    </tr>
</table>

Cumulo Nimbus's answer is useful for me but I want this grid wrapped by a div which can show the scrollbar when the list is too long.

To achieve this I added style="height:200px; overflow:auto" to a div around the table which causes it to show as a single column.

Now works for array length of one.

How do I remove all non alphanumeric characters from a string except dash?

Here's an extension method using @ata answer as inspiration.

"hello-world123, 456".MakeAlphaNumeric(new char[]{'-'});// yields "hello-world123456"

or if you require additional characters other than hyphen...

"hello-world123, 456!?".MakeAlphaNumeric(new char[]{'-','!'});// yields "hello-world123456!"


public static class StringExtensions
{   
    public static string MakeAlphaNumeric(this string input, params char[] exceptions)
    {
        var charArray = input.ToCharArray();
        var alphaNumeric = Array.FindAll<char>(charArray, (c => char.IsLetterOrDigit(c)|| exceptions?.Contains(c) == true));
        return new string(alphaNumeric);
    }
}

How to print to console in pytest?

Using -s option will print output of all functions, which may be too much.

If you need particular output, the doc page you mentioned offers few suggestions:

  1. Insert assert False, "dumb assert to make PyTest print my stuff" at the end of your function, and you will see your output due to failed test.

  2. You have special object passed to you by PyTest, and you can write the output into a file to inspect it later, like

    def test_good1(capsys):
        for i in range(5):
            print i
        out, err = capsys.readouterr()
        open("err.txt", "w").write(err)
        open("out.txt", "w").write(out)
    

    You can open the out and err files in a separate tab and let editor automatically refresh it for you, or do a simple py.test; cat out.txt shell command to run your test.

That is rather hackish way to do stuff, but may be it is the stuff you need: after all, TDD means you mess with stuff and leave it clean and silent when it's ready :-).

How does it work - requestLocationUpdates() + LocationRequest/Listener

You are implementing LocationListener in your activity MainActivity. The call for concurrent location updates will therefor be like this:

mLocationClient.requestLocationUpdates(mLocationRequest, this);

Be sure that the LocationListener you're implementing is from the google api, that is import this:

import com.google.android.gms.location.LocationListener;

and not this:

import android.location.LocationListener;

and it should work just fine.

It's also important that the LocationClient really is connected before you do this. I suggest you don't call it in the onCreate or onStart methods, but in onResume. It is all explained quite well in the tutorial for Google Location Api: https://developer.android.com/training/location/index.html

How do I turn off the output from tar commands on Unix?

Just drop the option v.

-v is for verbose. If you don't use it then it won't display:

tar -zxf tmp.tar.gz -C ~/tmp1

How to prevent downloading images and video files from my website?

You can't stop image/video theft but you can make harder for normal users but you can't make it harder for the programmers like us (I mean thieves that know little web programming).

There are some tricks you can try:

1.) Using flash as YouTube and many others sites like http://www.funnenjoy.com does.

2.) Div overlaping or background pic setting (but users with little sense can easily save all resources by opening inspect element or other developer option).

3.) You can disable right click and specific keys like CTRL + S and others possibles with JavaScript but main drawback is that if user disable JavaScript our all tricks fail down.

4.) Save image in none online directories (if you have full access to web server) and read that files with server side languages like PHP every time when image / video is required and change image id time to time or create script that can automatically change ID after every access.

5.) Use .htaccess in apache to prevent linking of your images by others sites. you can use this site to automatically generate .htacess http://www.htaccesstools.com/hotlink-protection/

FFMPEG mp4 from http live streaming m3u8 file?

Aergistal's answer works, but I found that converting to mp4 can make some m3u8 videos broken. If you are stuck with this problem, try to convert them to mkv, and convert them to mp4 later.

Reading serial data in realtime in Python

You can use inWaiting() to get the amount of bytes available at the input queue.

Then you can use read() to read the bytes, something like that:

While True:
    bytesToRead = ser.inWaiting()
    ser.read(bytesToRead)

Why not to use readline() at this case from Docs:

Read a line which is terminated with end-of-line (eol) character (\n by default) or until timeout.

You are waiting for the timeout at each reading since it waits for eol. the serial input Q remains the same it just a lot of time to get to the "end" of the buffer, To understand it better: you are writing to the input Q like a race car, and reading like an old car :)