Programs & Examples On #Sha2

sha-2 refers to the family of secure hash functions consisting of SHA-224, SHA-256, SHA-384, and SHA-512. These are defined by the [US NIST](http://csrc.nist.gov/) in FIPS 180-4.

Is calculating an MD5 hash less CPU intensive than SHA family functions?

sha1sum is quite a bit faster on Power9 than md5sum

$ uname -mov
#1 SMP Mon May 13 12:16:08 EDT 2019 ppc64le GNU/Linux

$ cat /proc/cpuinfo
processor       : 0
cpu             : POWER9, altivec supported
clock           : 2166.000000MHz
revision        : 2.2 (pvr 004e 1202)

$ ls -l linux-master.tar
-rw-rw-r-- 1 x x 829685760 Jan 29 14:30 linux-master.tar

$ time sha1sum linux-master.tar
10fbf911e254c4fe8e5eb2e605c6c02d29a88563  linux-master.tar

real    0m1.685s
user    0m1.528s
sys     0m0.156s

$ time md5sum linux-master.tar
d476375abacda064ae437a683c537ec4  linux-master.tar

real    0m2.942s
user    0m2.806s
sys     0m0.136s

$ time sum linux-master.tar
36928 810240

real    0m2.186s
user    0m1.917s
sys     0m0.268s

Check if my SSL Certificate is SHA1 or SHA2

Use the Linux Command Line

Use the command line, as described in this related question: How do I check if my SSL Certificate is SHA1 or SHA2 on the commandline.

Command

Here's the command. Replace www.yoursite.com:443 to fit your needs. Default SSL port is 443:

openssl s_client -connect www.yoursite.com:443 < /dev/null 2>/dev/null \
    | openssl x509 -text -in /dev/stdin | grep "Signature Algorithm"

Results

This should return something like this for the sha1:

Signature Algorithm: sha1WithRSAEncryption

or this for the newer version:

Signature Algorithm: sha256WithRSAEncryption

References

The article Why Google is Hurrying the Web to Kill SHA-1 describes exactly what you would expect and has a pretty graphic, too.

Are there any SHA-256 javascript implementations that are generally considered trustworthy?

Besides the Stanford lib that tylerl mentioned. I found jsrsasign very useful (Github repo here:https://github.com/kjur/jsrsasign). I don't know how exactly trustworthy it is, but i've used its API of SHA256, Base64, RSA, x509 etc. and it works pretty well. In fact, it includes the Stanford lib as well.

If all you want to do is SHA256, jsrsasign might be a overkill. But if you have other needs in the related area, I feel it's a good fit.

Python AttributeError: 'module' object has no attribute 'Serial'

I accidentally installed 'serial' (sudo python -m pip install serial) instead of 'pySerial' (sudo python -m pip install pyserial), which lead to the same error.

If the previously mentioned solutions did not work for you, double check if you installed the correct library.

How to define an enumerated type (enum) in C?

Declaring an enum variable is done like this:

enum strategy {RANDOM, IMMEDIATE, SEARCH};
enum strategy my_strategy = IMMEDIATE;

However, you can use a typedef to shorten the variable declarations, like so:

typedef enum {RANDOM, IMMEDIATE, SEARCH} strategy;
strategy my_strategy = IMMEDIATE;

Having a naming convention to distinguish between types and variables is a good idea:

typedef enum {RANDOM, IMMEDIATE, SEARCH} strategy_type;
strategy_type my_strategy = IMMEDIATE;

redistributable offline .NET Framework 3.5 installer for Windows 8

Microsoft .NET framework 3.5 can be installed on windows 10 without having installation media. The file you need is called microsoft-windows-netfx3-ondemand-package.cab. Just google it and you will get the download links. After downloading it, copy that file to C:\dotnet35 and run the following command.

Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:c:\dotnet35 /LimitAccess

Tested and worked in Windows 10 without any issue.

Rank function in MySQL

Here is a generic solution that assigns dense rank over partition to rows. It uses user variables:

CREATE TABLE person (
    id INT NOT NULL PRIMARY KEY,
    firstname VARCHAR(10),
    gender VARCHAR(1),
    age INT
);

INSERT INTO person (id, firstname, gender, age) VALUES
(1,  'Adams',  'M', 33),
(2,  'Matt',   'M', 31),
(3,  'Grace',  'F', 25),
(4,  'Harry',  'M', 20),
(5,  'Scott',  'M', 30),
(6,  'Sarah',  'F', 30),
(7,  'Tony',   'M', 30),
(8,  'Lucy',   'F', 27),
(9,  'Zoe',    'F', 30),
(10, 'Megan',  'F', 26),
(11, 'Emily',  'F', 20),
(12, 'Peter',  'M', 20),
(13, 'John',   'M', 21),
(14, 'Kate',   'F', 35),
(15, 'James',  'M', 32),
(16, 'Cole',   'M', 25),
(17, 'Dennis', 'M', 27),
(18, 'Smith',  'M', 35),
(19, 'Zack',   'M', 35),
(20, 'Jill',   'F', 25);

SELECT person.*, @rank := CASE
    WHEN @partval = gender AND @rankval = age THEN @rank
    WHEN @partval = gender AND (@rankval := age) IS NOT NULL THEN @rank + 1
    WHEN (@partval := gender) IS NOT NULL AND (@rankval := age) IS NOT NULL THEN 1
END AS rnk
FROM person, (SELECT @rank := NULL, @partval := NULL, @rankval := NULL) AS x
ORDER BY gender, age;

Notice that the variable assignments are placed inside the CASE expression. This (in theory) takes care of order of evaluation issue. The IS NOT NULL is added to handle datatype conversion and short circuiting issues.

PS: It can easily be converted to row number over partition by by removing all conditions that check for tie.

| id | firstname | gender | age | rank |
|----|-----------|--------|-----|------|
| 11 | Emily     | F      | 20  | 1    |
| 20 | Jill      | F      | 25  | 2    |
| 3  | Grace     | F      | 25  | 2    |
| 10 | Megan     | F      | 26  | 3    |
| 8  | Lucy      | F      | 27  | 4    |
| 6  | Sarah     | F      | 30  | 5    |
| 9  | Zoe       | F      | 30  | 5    |
| 14 | Kate      | F      | 35  | 6    |
| 4  | Harry     | M      | 20  | 1    |
| 12 | Peter     | M      | 20  | 1    |
| 13 | John      | M      | 21  | 2    |
| 16 | Cole      | M      | 25  | 3    |
| 17 | Dennis    | M      | 27  | 4    |
| 7  | Tony      | M      | 30  | 5    |
| 5  | Scott     | M      | 30  | 5    |
| 2  | Matt      | M      | 31  | 6    |
| 15 | James     | M      | 32  | 7    |
| 1  | Adams     | M      | 33  | 8    |
| 18 | Smith     | M      | 35  | 9    |
| 19 | Zack      | M      | 35  | 9    |

Demo on db<>fiddle

How to get a list of all files that changed between two Git commits?

  • To list all unstaged tracked changed files:

    git diff --name-only
    
  • To list all staged tracked changed files:

    git diff --name-only --staged
    
  • To list all staged and unstaged tracked changed files:

    { git diff --name-only ; git diff --name-only --staged ; } | sort | uniq
    
  • To list all untracked files (the ones listed by git status, so not including any ignored files):

    git ls-files --other --exclude-standard
    

If you're using this in a shell script, and you want to programmatically check if these commands returned anything, you'll be interested in git diff's --exit-code option.

Easiest way to split a string on newlines in .NET?

I did not know about Environment.Newline, but I guess this is a very good solution.

My try would have been:

        string str = "Test Me\r\nTest Me\nTest Me";
        var splitted = str.Split('\n').Select(s => s.Trim()).ToArray();

The additional .Trim removes any \r or \n that might be still present (e. g. when on windows but splitting a string with os x newline characters). Probably not the fastest method though.

EDIT:

As the comments correctly pointed out, this also removes any whitespace at the start of the line or before the new line feed. If you need to preserve that whitespace, use one of the other options.

How to check if an element does NOT have a specific class?

You can try this:

<div id="div1" class="myClass">there is a class</div>
<div id="div2"> there is no class2 </div>

$(document).ready(function(){
    $("#div2").not('.myClass');  // do not have `myClass` class.
});

How to execute a remote command over ssh with arguments?

I'm using the following to execute commands on the remote from my local computer:

ssh -i ~/.ssh/$GIT_PRIVKEY user@$IP "bash -s" < localpath/script.sh $arg1 $arg2

sql set variable using COUNT

You want:

DECLARE @times int

SELECT @times =  COUNT(DidWin)
FROM thetable
WHERE DidWin = 1 AND Playername='Me'

You also don't need the 'as' clause.

Comparing object properties in c#

This works even if the objects are different. you could customize the methods in the utilities class maybe you want to compare private properties as well...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class ObjectA
{
    public string PropertyA { get; set; }
    public string PropertyB { get; set; }
    public string PropertyC { get; set; }
    public DateTime PropertyD { get; set; }

    public string FieldA;
    public DateTime FieldB;
}

class ObjectB
{
    public string PropertyA { get; set; }
    public string PropertyB { get; set; }
    public string PropertyC { get; set; }
    public DateTime PropertyD { get; set; }


    public string FieldA;
    public DateTime FieldB;


}

class Program
{
    static void Main(string[] args)
    {
        // create two objects with same properties
        ObjectA a = new ObjectA() { PropertyA = "test", PropertyB = "test2", PropertyC = "test3" };
        ObjectB b = new ObjectB() { PropertyA = "test", PropertyB = "test2", PropertyC = "test3" };

        // add fields to those objects
        a.FieldA = "hello";
        b.FieldA = "Something differnt";

        if (a.ComparePropertiesTo(b))
        {
            Console.WriteLine("objects have the same properties");
        }
        else
        {
            Console.WriteLine("objects have diferent properties!");
        }


        if (a.CompareFieldsTo(b))
        {
            Console.WriteLine("objects have the same Fields");
        }
        else
        {
            Console.WriteLine("objects have diferent Fields!");
        }

        Console.Read();
    }
}

public static class Utilities
{
    public static bool ComparePropertiesTo(this Object a, Object b)
    {
        System.Reflection.PropertyInfo[] properties = a.GetType().GetProperties(); // get all the properties of object a

        foreach (var property in properties)
        {
            var propertyName = property.Name;

            var aValue = a.GetType().GetProperty(propertyName).GetValue(a, null);
            object bValue;

            try // try to get the same property from object b. maybe that property does
                // not exist! 
            {
                bValue = b.GetType().GetProperty(propertyName).GetValue(b, null);
            }
            catch
            {
                return false;
            }

            if (aValue == null && bValue == null)
                continue;

            if (aValue == null && bValue != null)
                return false;

            if (aValue != null && bValue == null)
               return false;

            // if properties do not match return false
            if (aValue.GetHashCode() != bValue.GetHashCode())
            {
                return false;
            }
        }

        return true;
    }



    public static bool CompareFieldsTo(this Object a, Object b)
    {
        System.Reflection.FieldInfo[] fields = a.GetType().GetFields(); // get all the properties of object a

        foreach (var field in fields)
        {
            var fieldName = field.Name;

            var aValue = a.GetType().GetField(fieldName).GetValue(a);

            object bValue;

            try // try to get the same property from object b. maybe that property does
            // not exist! 
            {
                bValue = b.GetType().GetField(fieldName).GetValue(b);
            }
            catch
            {
                return false;
            }

            if (aValue == null && bValue == null)
               continue;

            if (aValue == null && bValue != null)
               return false;

            if (aValue != null && bValue == null)
               return false;


            // if properties do not match return false
            if (aValue.GetHashCode() != bValue.GetHashCode())
            {
                return false;
            }
        }

        return true;
    }


}

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

What about:

def dict_merge_and_sum( d1, d2 ):
    ret = d1
    ret.update({ k:v + d2[k] for k,v in d1.items() if k in d2 })
    ret.update({ k:v for k,v in d2.items() if k not in d1 })
    return ret

A = {'a': 1, 'b': 2, 'c': 3}
B = {'b': 3, 'c': 4, 'd': 5}

print( dict_merge_and_sum( A, B ) )

Output:

{'d': 5, 'a': 1, 'c': 7, 'b': 5}

How to define Gradle's home in IDEA?

This is where my gradle home is (Arch Linux):

/usr/share/java/gradle/

How can I run a function from a script in command line?

Using case

#!/bin/bash

fun1 () {
    echo "run function1"
    [[ "$@" ]] && echo "options: $@"
}

fun2 () {
    echo "run function2"
    [[ "$@" ]] && echo "options: $@"
}

case $1 in
    fun1) "$@"; exit;;
    fun2) "$@"; exit;;
esac

fun1
fun2

This script will run functions fun1 and fun2 but if you start it with option fun1 or fun2 it'll only run given function with args(if provided) and exit. Usage

$ ./test 
run function1
run function2

$ ./test fun2 a b c
run function2
options: a b c

Objective-C and Swift URL encoding

 NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NUL,(CFStringRef)@"parameter",NULL,(CFStringRef)@"!*'();@&+$,/?%#[]~=_-.:",kCFStringEncodingUTF8 );

NSURL * url = [[NSURL alloc] initWithString:[@"address here" stringByAppendingFormat:@"?cid=%@",encodedString, nil]];

Could not load the Tomcat server configuration

You tried to start Tomcat and got the following error:

Could not load the Tomcat server configuration at /Servers/Tomcat v7.0 Server at localhost-config. The configuration may be corrupt or incomplete

How to solve:

  • Close Eclipse
  • Copy all files from TOMCAT_7_HOME/conf to WORKSPACE_FOLDER/Servers/Tomcat v7.0 Server at localhost-config
  • Start Eclipse
  • Expand the Servers project, click on the Tomcat 7 project and hit F5
  • Start Tomcat from Eclipse

How do I change the default index page in Apache?

You can also set DirectoryIndex in apache's httpd.conf file.

CentOS keeps this file in /etc/httpd/conf/httpd.conf Debian: /etc/apache2/apache2.conf

Open the file in your text editor and find the line starting with DirectoryIndex

To load landing.html as a default (but index.html if that's not found) change this line to read:

DirectoryIndex  landing.html index.html

Executing Javascript code "on the spot" in Chrome?

If you mean you want to execute the function inputted, yes, that is simple:

Use this JS code:

eval(document.getElementById( -- el ID -- ).value);

String comparison - Android

String unlike int or other numeric variables are compared in Java differently than other languages.

To compare Strings in Java (android) it is used the method .compareTo();

so the code should be like this:

if(gender.compareTo("Male")==0){
   salutation ="Mr.";
}
if(gender.compareTo("Female")==0){
   salutation ="Ms.";
}

Create a new object from type parameter in generic class

i use this: let instance = <T>{}; it generally works EDIT 1:

export class EntityCollection<T extends { id: number }>{
  mutable: EditableEntity<T>[] = [];
  immutable: T[] = [];
  edit(index: number) {
    this.mutable[index].entity = Object.assign(<T>{}, this.immutable[index]);
  }
}

How can I find a specific element in a List<T>?

Or if you do not prefer to use LINQ you can do it the old-school way:

List<MyClass> list = new List<MyClass>();
foreach (MyClass element in list)
{
    if (element.GetId() == "heres_where_you_put_what_you_are_looking_for")
    {

        break; // If you only want to find the first instance a break here would be best for your application
    }
}

How to do what head, tail, more, less, sed do in Powershell?

$Push_Pop = $ErrorActionPreference #Suppresses errors
$ErrorActionPreference = “SilentlyContinue” #Suppresses errors
#Script
    #gc .\output\*.csv -ReadCount 5 | %{$_;throw "pipeline end!"} # head
    #gc .\output\*.csv | %{$num=0;}{$num++;"$num $_"}             # cat -n
    gc .\output\*.csv | %{$num=0;}{$num++; if($num -gt 2 -and $num -lt 7){"$num $_"}} # sed
#End Script 
$ErrorActionPreference = $Push_Pop #Suppresses errors

You don't get all the errors with the pushpop code BTW, your code only works with the "sed" option. All the rest ignores anything but gc and path.

How to completely uninstall kubernetes

use kubeadm reset command. this will un-configure the kubernetes cluster.

HTML: how to make 2 tables with different CSS

<table id="table1"></table>
<table id="table2"></table>

or

<table class="table1"></table>
<table class="table2"></table>

Intermediate language used in scalac?

maybe this will help you out:

http://lampwww.epfl.ch/~paltherr/phd/altherr-phd.pdf

or this page:

www.scala-lang.org/node/6372‎

How to exit a 'git status' list in a terminal?

q or SHIFT+q will do the trick. This will get you out of many extensive page scrolling sessions like git status, git show HEAD, git diff etc. This will not exit your window or end your session.

How to Select Min and Max date values in Linq Query

This should work for you

//Retrieve Minimum Date
var MinDate = (from d in dataRows select d.Date).Min();

//Retrieve Maximum Date
var MaxDate = (from d in dataRows select d.Date).Max(); 

(From here)

How do I get a TextBox to only accept numeric input in WPF?

After using some of the solutions here for some time, I developed my own that works well for my MVVM setup. Note that it's not as dynamic as some of the other ones in a sense of still allowing users to enter erroneous characters, but it blocks them from pressing the button and thus doing anything. This goes well with my theme of graying out buttons when actions cannot be performed.

I have a TextBox that a user must enter a number of document pages to be printed:

<TextBox Text="{Binding NumberPagesToPrint, UpdateSourceTrigger=PropertyChanged}"/>

...with this binding property:

private string _numberPagesToPrint;
public string NumberPagesToPrint
{
    get { return _numberPagesToPrint; }
    set
    {
        if (_numberPagesToPrint == value)
        {
            return;
        }

        _numberPagesToPrint = value;
        OnPropertyChanged("NumberPagesToPrint");
    }
}

I also have a button:

<Button Template="{DynamicResource CustomButton_Flat}" Content="Set"
        Command="{Binding SetNumberPagesCommand}"/>

...with this command binding:

private RelayCommand _setNumberPagesCommand;
public ICommand SetNumberPagesCommand
{
    get
    {
        if (_setNumberPagesCommand == null)
        {
            int num;
            _setNumberPagesCommand = new RelayCommand(param => SetNumberOfPages(),
                () => Int32.TryParse(NumberPagesToPrint, out num));
        }

        return _setNumberPagesCommand;
    }
}

And then there's the method of SetNumberOfPages(), but it's unimportant for this topic. It works well in my case because I don't have to add any code into the View's code-behind file and it allows me to control behavior using the Command property.

Combining border-top,border-right,border-left,border-bottom in CSS

I can relate to the problem, there should be a shorthand like...

border: 1px solid red top bottom left;

Of course that doesn't work! Kobi's answer gave me an idea. Let's say you want to do top, bottom and left, but not right. Instead of doing border-top: border-left: border-bottom: (three statements) you could do two like this, the zero cancels out the right side.

border: 1px dashed yellow;
border-width:1px 0 1px 1px;

Two statements instead of three, small improvement :-D

Get values from an object in JavaScript

If you $ is defined then You can iterate

var data={"id" : 1, "second" : "abcd"};
$.each(data, function() {
  var key = Object.keys(this)[0];
  var value = this[key];
  //do something with value;
}); 

You can access it by following way If you know the values of keys

data.id

or

data["id"]

How do I format a number in Java?

From this thread, there are different ways to do this:

double r = 5.1234;
System.out.println(r); // r is 5.1234

int decimalPlaces = 2;
BigDecimal bd = new BigDecimal(r);

// setScale is immutable
bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);
r = bd.doubleValue();

System.out.println(r); // r is 5.12

f = (float) (Math.round(n*100.0f)/100.0f);

DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
double dd = 100.2397;
double dd2dec = new Double(df2.format(dd)).doubleValue();

// The value of dd2dec will be 100.24

The DecimalFormat() seems to be the most dynamic way to do it, and it is also very easy to understand when reading others code.

Shell command to tar directory excluding certain files/folders

The following bash script should do the trick. It uses the answer given here by Marcus Sundman.

#!/bin/bash

echo -n "Please enter the name of the tar file you wish to create with out extension "
read nam

echo -n "Please enter the path to the directories to tar "
read pathin

echo tar -czvf $nam.tar.gz
excludes=`find $pathin -iname "*.CC" -exec echo "--exclude \'{}\'" \;|xargs`
echo $pathin

echo tar -czvf $nam.tar.gz $excludes $pathin

This will print out the command you need and you can just copy and paste it back in. There is probably a more elegant way to provide it directly to the command line.

Just change *.CC for any other common extension, file name or regex you want to exclude and this should still work.

EDIT

Just to add a little explanation; find generates a list of files matching the chosen regex (in this case *.CC). This list is passed via xargs to the echo command. This prints --exclude 'one entry from the list'. The slashes () are escape characters for the ' marks.

Loop through properties in JavaScript object with Lodash

You can definitely do this with vanilla JS like stecb has shown, but I think each is the best answer to the core question concerning how to do it with lodash.

_.each( myObject.options, ( val, key ) => { 
    console.log( key, val ); 
} );

Like JohnnyHK mentioned, there is also the has method which would be helpful for the use case, but from what is originally stated set may be more useful. Let's say you wanted to add something to this object dynamically as you've mentioned:

let dynamicKey = 'someCrazyProperty';
let dynamicValue = 'someCrazyValue';

_.set( myObject.options, dynamicKey, dynamicValue );

That's how I'd do it, based on the original description.

CSS Layout - Dynamic width DIV

This will do what you want. Fixed sides with 50px-width, and the content fills the remaining area.

<div style="width:100%;">
    <div style="width: 50px; float: left;">Left Side</div>
    <div style="width: 50px; float: right;">Right Side</div>
    <div style="margin-left: 50px; margin-right: 50px;">Content Goes Here</div>
</div>

TypeError: only length-1 arrays can be converted to Python scalars while plot showing

dataframe['column'].squeeze() should solve this. It basically changes the dataframe column to a list.

Rename all files in a folder with a prefix in a single command

Try the rename command in the folder with the files:

rename 's/^/Unix_/' *

The argument of rename (sed s command) indicates to replace the regex ^ with Unix_. The caret (^) is a special character that means start of the line.

How to start MySQL with --skip-grant-tables?

After trying lots of things, this is what worked for me:

sudo mysql -u root
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'newpassword'; 

So first we use sudo to log in mysql as root without needing a password. Then we just update root's password.

After that, I restarted mysqld:

sudo service mysql restart

And the newpassword logged root in!

How to run console application from Windows Service?

As pierre said, there is no way to have a user interface for a windows service (or no easy way). What I do in that kind of situation is to have a settings file that is read from the service on whatever interval the service operates on and have a standalone application that makes changes to the settings file.

How do you rotate a two dimensional array?

This a better version of it in Java: I've made it for a matrix with a different width and height

  • h is here the height of the matrix after rotating
  • w is here the width of the matrix after rotating

 

public int[][] rotateMatrixRight(int[][] matrix)
{
    /* W and H are already swapped */
    int w = matrix.length;
    int h = matrix[0].length;
    int[][] ret = new int[h][w];
    for (int i = 0; i < h; ++i) {
        for (int j = 0; j < w; ++j) {
            ret[i][j] = matrix[w - j - 1][i];
        }
    }
    return ret;
}


public int[][] rotateMatrixLeft(int[][] matrix)
{
    /* W and H are already swapped */
    int w = matrix.length;
    int h = matrix[0].length;   
    int[][] ret = new int[h][w];
    for (int i = 0; i < h; ++i) {
        for (int j = 0; j < w; ++j) {
            ret[i][j] = matrix[j][h - i - 1];
        }
    }
    return ret;
}

This code is based on Nick Berardi's post.

How to create border in UIButton?

Update with Swift 3

    button.layer.borderWidth = 0.8
    button.layer.borderColor = UIColor.blue.cgColor

enter image description here

Remove the string on the beginning of an URL

Depends on what you need, you have a couple of choices, you can do:

// this will replace the first occurrence of "www." and return "testwww.com"
"www.testwww.com".replace("www.", "");

// this will slice the first four characters and return "testwww.com"
"www.testwww.com".slice(4);

// this will replace the www. only if it is at the beginning
"www.testwww.com".replace(/^(www\.)/,"");

html tables & inline styles

Forget float, margin and html 3/5. The mail is very obsolete. You need do all with table. One line = one table. You need margin or padding ? Do another column.

Codepen

Example : i need one line with 1 One Picture of 40*40 2 One margin of 10 px 3 One text of 400px

I start my line :

<table style=" background-repeat:no-repeat; width:450px;margin:0;" cellpadding="0" cellspacing="0" border="0">
   <tr style="height:40px; width:450px; margin:0;">
     <td style="height:40px; width:40px; margin:0;">
        <img src="" style="width=40px;height40;margin:0;display:block"
     </td>
     <td style="height:40px; width:10px; margin:0;">        
     </td>
     <td style="height:40px; width:400px; margin:0;">
     <p style=" margin:0;"> my text   </p>
     </td>
   </tr>
</table>

What type of hash does WordPress use?

Start phpMyAdmin and access wp_users from your wordpress instance. Edit record and select user_pass function to match MD5. Write the string that will be your new password in VALUE. Click, GO. Go to your wordpress website and enter your new password. Back to phpMyAdmin you will see that WP changed the HASH to something like $P$B... enjoy!

Rotate axis text in python matplotlib

import pylab as pl
pl.xticks(rotation = 90)

Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website

Solved by doing the following in my windows 10:

mklink "C:\Users\hal\AppData\Local\Continuum\anaconda3\DLLs\libssl-1_1-x64.dll" "C:\Users\hal\AppData\Local\Continuum\anaconda3\Library\bin\libssl-1_1-x64.dll"

mklink "C:\ProgramData\Anaconda3\DLLs\libcrypto-1_1-x64.dll" "C:\ProgramData\Anaconda3\Library\bin\libcrypto-1_1-x64.dll"

CodeIgniter - how to catch DB errors?

Maybe this:

$db_debug = $this->db->db_debug; //save setting

$this->db->db_debug = FALSE; //disable debugging for queries

$result = $this->db->query($sql); //run query

//check for errors, etc

$this->db->db_debug = $db_debug; //restore setting

Getting a better understanding of callback functions in JavaScript

You can just say

callback();

Alternately you can use the call method if you want to adjust the value of this within the callback.

callback.call( newValueForThis);

Inside the function this would be whatever newValueForThis is.

Python: AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

You are using str methods on an open file object.

You can read the file as a list of lines by simply calling list() on the file object:

with open('goodlines.txt') as f:
    mylist = list(f)

This does include the newline characters. You can strip those in a list comprehension:

with open('goodlines.txt') as f:
    mylist = [line.rstrip('\n') for line in f]

Dynamically Add C# Properties at Runtime

Thanks @Clint for the great answer:

Just wanted to highlight how easy it was to solve this using the Expando Object:

    var dynamicObject = new ExpandoObject() as IDictionary<string, Object>;
    foreach (var property in properties) {
        dynamicObject.Add(property.Key,property.Value);
    }

How to get htaccess to work on MAMP

I'm using MAMP (downloaded today) and had this problem also. The issue is with this version of the MAMP stack's default httpd.conf directive around line 370. Look at httpd.conf down at around line 370 and you will find:

<Directory "/Applications/MAMP/bin/mamp">
    Options Indexes MultiViews
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>

You need to change: AllowOverride None To: AllowOverride All

Color text in terminal applications in UNIX

This is a little C program that illustrates how you could use color codes:

#include <stdio.h>

#define KNRM  "\x1B[0m"
#define KRED  "\x1B[31m"
#define KGRN  "\x1B[32m"
#define KYEL  "\x1B[33m"
#define KBLU  "\x1B[34m"
#define KMAG  "\x1B[35m"
#define KCYN  "\x1B[36m"
#define KWHT  "\x1B[37m"

int main()
{
    printf("%sred\n", KRED);
    printf("%sgreen\n", KGRN);
    printf("%syellow\n", KYEL);
    printf("%sblue\n", KBLU);
    printf("%smagenta\n", KMAG);
    printf("%scyan\n", KCYN);
    printf("%swhite\n", KWHT);
    printf("%snormal\n", KNRM);

    return 0;
}

How do I copy SQL Azure database to my local development server?

Regarding the " I couldn't get the SSIS import / export to work as I got the error 'Failure inserting into the read-only column "id"'. This can be gotten around by specifying in the mapping screen that you do want to allow Identity elements to be inserted.

After that, everything worked fine using SQL Import/Export wizard to copy from Azure to local database.

I only had SQL Import/Export Wizard that comes with SQL Server 2008 R2 (worked fine), and Visual Studio 2012 Express to create local database.

twitter bootstrap navbar fixed top overlapping site

Your answer is right in the docs:

Body padding required

The fixed navbar will overlay your other content, unless you add padding to the top of the <body>. Try out your own values or use our snippet below. Tip: By default, the navbar is 50px high.

body { padding-top: 70px; }

Make sure to include this after the core Bootstrap CSS.

and in the Bootstrap 4 docs...

Fixed navbars use position: fixed, meaning they’re pulled from the normal flow of the DOM and may require custom CSS (e.g., padding-top on the ) to prevent overlap with other elements.

java.lang.NoClassDefFoundError: javax/mail/Authenticator, whats wrong?

You need to add two jars into the WEB-INF/lib directory or your webapp (or lib directory of the server):

Calculate the number of business days between two dates?

Here is the function which we can use to calculate business days between two date. I'm not using holiday list as it can vary accross country/region.

If we want to use it anyway we can take third argument as list of holiday and before incrementing count we should check that list does not contains d

public static int GetBussinessDaysBetweenTwoDates(DateTime StartDate,   DateTime EndDate)
    {
        if (StartDate > EndDate)
            return -1;

        int bd = 0;

        for (DateTime d = StartDate; d < EndDate; d = d.AddDays(1))
        {
            if (d.DayOfWeek != DayOfWeek.Saturday && d.DayOfWeek != DayOfWeek.Sunday)
                bd++;
        }

        return bd;
    }

Keyboard shortcut to clear cell output in Jupyter notebook

STEP 1 :Click on the "Help"and click on "Edit Keyboard Shortcut" STEP1-screenshot

STEP 2 :Add the Shortcut you desire to the "Clear Cell" field STEP2-screenshot

How do I encode URI parameter values?

Jersey's UriBuilder encodes URI components using application/x-www-form-urlencoded and RFC 3986 as needed. According to the Javadoc

Builder methods perform contextual encoding of characters not permitted in the corresponding URI component following the rules of the application/x-www-form-urlencoded media type for query parameters and RFC 3986 for all other components. Note that only characters not permitted in a particular component are subject to encoding so, e.g., a path supplied to one of the path methods may contain matrix parameters or multiple path segments since the separators are legal characters and will not be encoded. Percent encoded values are also recognized where allowed and will not be double encoded.

How can I use a local image as the base image with a dockerfile?

You can have - characters in your images. Assume you have a local image (not a local registry) named centos-base-image with tag 7.3.1611.

docker version 
      Client:
       Version:         1.12.6
       API version:     1.24
       Package version: docker-common-1.12.6-16.el7.centos.x86_64
       Go version:      go1.7.4

      Server:
       Version:         1.12.6
       API version:     1.24
       Package version: docker-common-1.12.6-16.el7.centos.x86_64
       Go version:      go1.7.4

docker images
 REPOSITORY            TAG
 centos-base-image     7.3.1611

Dockerfile

FROM centos-base-image:7.3.1611
RUN yum -y install epel-release libaio bc flex

Result

Sending build context to Docker daemon 315.9 MB
Step 1 : FROM centos-base-image:7.3.1611
  ---> c4d84e86782e
Step 2 : RUN yum -y install epel-release libaio bc flex
  ---> Running in 36d8abd0dad9
...

In the example above FROM is fetching your local image, you can provide additional instructions to fetch an image from your custom registry (e.g. FROM localhost:5000/my-image:with.tag). See https://docs.docker.com/engine/reference/commandline/pull/#pull-from-a-different-registry and https://docs.docker.com/registry/#tldr

Finally, if your image is not being resolved when providing a name, try adding a tag to the image when you create it

This GitHub thread describes a similar issue of not finding local images by name.

By omitting a specific tag, docker will look for an image tagged "latest", so either create an image with the :latest tag, or change your FROM

Can I pass an argument to a VBScript (vbs file launched with cscript)?

You can use WScript.Arguments to access the arguments passed to your script.

Calling the script:

cscript.exe test.vbs "C:\temp\"

Inside your script:

Set File = FSO.OpenTextFile(WScript.Arguments(0) &"\test.txt", 2, True)

Don't forget to check if there actually has been an argument passed to your script. You can do so by checking the Count property:

if WScript.Arguments.Count = 0 then
    WScript.Echo "Missing parameters"
end if

If your script is over after you close the file then there is no need to set the variables to Nothing. The resources will be cleaned up automatically when the cscript.exe process terminates. Setting a variable to Nothing usually is only necessary if you explicitly want to free resources during the execution of your script. In that case, you would set variables which contain a reference to a COM object to Nothing, which would release the COM object before your script terminates. This is just a short answer to your bonus question, you will find more information in these related questions:

Is there a need to set Objects to Nothing inside VBA Functions

When must I set a variable to “Nothing” in VB6?

Modify request parameter with servlet filter

As you've noted HttpServletRequest does not have a setParameter method. This is deliberate, since the class represents the request as it came from the client, and modifying the parameter would not represent that.

One solution is to use the HttpServletRequestWrapper class, which allows you to wrap one request with another. You can subclass that, and override the getParameter method to return your sanitized value. You can then pass that wrapped request to chain.doFilter instead of the original request.

It's a bit ugly, but that's what the servlet API says you should do. If you try to pass anything else to doFilter, some servlet containers will complain that you have violated the spec, and will refuse to handle it.

A more elegant solution is more work - modify the original servlet/JSP that processes the parameter, so that it expects a request attribute instead of a parameter. The filter examines the parameter, sanitizes it, and sets the attribute (using request.setAttribute) with the sanitized value. No subclassing, no spoofing, but does require you to modify other parts of your application.

Cannot set some HTTP headers when using System.Net.WebRequest

I ran into same issue below piece of code worked for me

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

request.Headers["UserAgent"] = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; 
Trident/5.0)"

How do I get Maven to use the correct repositories?

the pom.xml for the project I have doesn't have this "http://repo1.maven.org/myurlhere" anywhere in it

All projects have http://repo1.maven.org/ declared as <repository> (and <pluginRepository>) by default. This repository, which is called the central repository, is inherited like others default settings from the "Super POM" (all projects inherit from the Super POM). So a POM is actually a combination of the Super POM, any parent POMs and the current POM. This combination is called the "effective POM" and can be printed using the effective-pom goal of the Maven Help plugin (useful for debugging).

And indeed, if you run:

mvn help:effective-pom

You'll see at least the following:

  <repositories>
    <repository>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
      <id>central</id>
      <name>Maven Repository Switchboard</name>
      <url>http://repo1.maven.org/maven2</url>
    </repository>
  </repositories>
  <pluginRepositories>
    <pluginRepository>
      <releases>
        <updatePolicy>never</updatePolicy>
      </releases>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
      <id>central</id>
      <name>Maven Plugin Repository</name>
      <url>http://repo1.maven.org/maven2</url>
    </pluginRepository>
  </pluginRepositories>

it has the absolute url where the maven repo is for the project but maven is still trying to download from the general maven repo

Maven will try to find dependencies in all repositories declared, including in the central one which is there by default as we saw. But, according to the trace you are showing, you only have one repository defined (the central repository) or maven would print something like this:

Reason: Unable to download the artifact from any repository

  url.project:project:pom:x.x

from the specified remote repositories:
  central (http://repo1.maven.org/),
  another-repository (http://another/repository)

So, basically, maven is unable to find the url.project:project:pom:x.x because it is not available in central.

But without knowing which project you've checked out (it has maybe specific instructions) or which dependency is missing (it can maybe be found in another repository), it's impossible to help you further.

Return multiple values from a function in swift

you should return three different values from this method and get these three in a single variable like this.

func getTime()-> (hour:Int,min:Int,sec:Int){
//your code
return (hour,min,sec)
}

get the value in single variable

let getTime = getTime()

now you can access the hour,min and seconds simply by "." ie.

print("hour:\(getTime.hour) min:\(getTime.min) sec:\(getTime.sec)")

CSS3 Rotate Animation

To achieve the 360 degree rotation, here is the Working Solution.

The HTML:

<img class="image" src="your-image.png">

The CSS:

.image {
    overflow: hidden;
    transition-duration: 0.8s;
    transition-property: transform;
}
.image:hover {
    transform: rotate(360deg);
    -webkit-transform: rotate(360deg);
}

You have to hover on the image and you will get the 360 degree rotation effect.

PS: Add a -webkit- extension for it to work on chrome and other webkit browers. You can check the updated fiddle for webkit HERE

Android intent for playing video?

following code works just fine for me.

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(movieurl));
startActivity(intent);

Test for array of string type in TypeScript

there is a little problem here because the

if (typeof item !== 'string') {
    return false
}

will not stop the foreach. So the function will return true even if the array does contain none string values.

This seems to wok for me:

function isStringArray(value: any): value is number[] {
  if (Object.prototype.toString.call(value) === '[object Array]') {
     if (value.length < 1) {
       return false;
     } else {
       return value.every((d: any) => typeof d === 'string');
     }
  }
  return false;
}

Greetings, Hans

Does java.util.List.isEmpty() check if the list itself is null?

Yes, it will throw an Exception. maybe you are used to PHP code, where empty($element) does also check for isset($element)? In Java this is not the case.

You can memorize that easily because the method is directly called on the list (the method belongs to the list). So if there is no list, then there is no method. And Java will complain that there is no list to call this method on.

How to get name of dataframe column in pyspark?

You can get the names from the schema by doing

spark_df.schema.names

Printing the schema can be useful to visualize it as well

spark_df.printSchema()

Max tcp/ip connections on Windows Server 2008

How many thousands of users?

I've run some TCP/IP client/server connection tests in the past on Windows 2003 Server and managed more than 70,000 connections on a reasonably low spec VM. (see here for details: http://www.lenholgate.com/blog/2005/10/the-64000-connection-question.html). I would be extremely surprised if Windows 2008 Server is limited to less than 2003 Server and, IMHO, the posting that Cloud links to is too vague to be much use. This kind of question comes up a lot, I blogged about why I don't really think that it's something that you should actually worry about here: http://www.serverframework.com/asynchronousevents/2010/12/one-million-tcp-connections.html.

Personally I'd test it and see. Even if there is no inherent limit in the Windows 2008 Server version that you intend to use there will still be practical limits based on memory, processor speed and server design.

If you want to run some 'generic' tests you can use my multi-client connection test and the associated echo server. Detailed here: http://www.lenholgate.com/blog/2005/11/windows-tcpip-server-performance.html and here: http://www.lenholgate.com/blog/2005/11/simple-echo-servers.html. These are what I used to run my own tests for my server framework and these are what allowed me to create 70,000 active connections on a Windows 2003 Server VM with 760MB of memory.

Edited to add details from the comment below...

If you're already thinking of multiple servers I'd take the following approach.

  1. Use the free tools that I link to and prove to yourself that you can create a reasonable number of connections onto your target OS (beware of the Windows limits on dynamic ports which may cause your client connections to fail, search for MAX_USER_PORT).

  2. during development regularly test your actual server with test clients that can create connections and actually 'do something' on the server. This will help to prevent you building the server in ways that restrict its scalability. See here: http://www.serverframework.com/asynchronousevents/2010/10/how-to-support-10000-or-more-concurrent-tcp-connections-part-2-perf-tests-from-day-0.html

How to tell which row number is clicked in a table?

A better approach would be to delegate the event, which means catching it as it bubbles to the parent node.

delegation - overview

This solution is both more robust and efficient.

It allows the event to be handled even if more rows are dynamically added to the table later, and also results in attaching a single event handler to the parent node (table element), instead of one for each child node (tr element).

Assuming that the OP's example is a simplified one, the table's structure can be more complex, for example:

<table id="indexedTable">
    ...
    <tr>
        <td><p>1</p></td>
        <td>2</td>
        <td><p>3</p></td>
    </tr>
</table>

Therefore, a simplistic approach such as getting e.target.parentElement will not work, as clicking the internal <p> and clicking the center <td> will produce different results.

Using delegation normalizes the event handling, only assuming that there are no nested tables.

implementation

Both of the following snippets are equivalent:

$("#indexedTable").delegate("tr", "click", function(e) {
    console.log($(e.currentTarget).index() + 1);
});

$("#indexedTable").on("click", "tr", function(e) {
    console.log($(e.currentTarget).index() + 1);
});

They attach a listener to table element and handle any event that bubbles from the table rows. The current API is the on method and the delegate method is legacy API (and actually calls on behind the scenes).

Note that the order of parameters to both functions is different.

example

A comparison between direct handler attachment and delegation is available below or on jsFiddle:

_x000D_
_x000D_
$("#table-delegate").on("click", "tr", function(e) {_x000D_
  var idx = $(e.currentTarget).index() + 1;_x000D_
  $("#delegation-idx").text(idx);  _x000D_
  console.log('delegated', idx);_x000D_
});_x000D_
_x000D_
$("#table-direct tr").on("click", function(e) {_x000D_
  var idx = $(e.currentTarget).index() + 1;_x000D_
  $("#direct-idx").text(idx);_x000D_
  console.log('direct', idx);_x000D_
});_x000D_
_x000D_
$('[data-action=add-row]').click(function(e) {_x000D_
  var id = e.target.dataset.table;_x000D_
  $('#' + id + ' tbody')_x000D_
    .append($('<tr><td>extra</td><td>extra</td><td>extra</td></tr>')[0])_x000D_
});
_x000D_
tr:hover{_x000D_
    background:#ddd;_x000D_
}_x000D_
_x000D_
button.add-row {_x000D_
    margin-bottom: 5px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
<h1>Event handling test</h1>_x000D_
<p>Add rows to both tables and see the difference in handling.</p>_x000D_
<p>Event delegation attaches a single event listener and events related to newly added children are caught.</p>_x000D_
<p>Direct event handling attaches an event handler to each child, where children added after the inital handler attachment don't have a handler attached to them, and therefore their indices won't be logged to console.</p>_x000D_
<h2>Delegation</h2>_x000D_
<p><span>row index: </span><span id="delegation-idx">unknown</span></p>_x000D_
<button class="add-row" data-action="add-row" data-table="table-delegate">Add row to delegation</button>_x000D_
<table id="table-delegate" class="table">_x000D_
    <tbody>_x000D_
    <tr>_x000D_
        <td>normal</td>_x000D_
        <td>normal</td>_x000D_
        <td>normal</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td><p>nested</p></td>_x000D_
        <td><p>nested</p></td>_x000D_
        <td><p>nested</p></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>normal</td>_x000D_
        <td>normal</td>_x000D_
        <td><p>nested</p></td>_x000D_
    </tr>_x000D_
_x000D_
</table>_x000D_
_x000D_
<h2>Direct attachment</h2>_x000D_
<p><span>row index: </span><span id="direct-idx">unknown</span></p>_x000D_
<button class="add-row" data-action="add-row" data-table="table-direct">Add row to direct</button>_x000D_
<table id="table-direct" class="table">_x000D_
<tbody>_x000D_
    <tr>_x000D_
        <td>normal</td>_x000D_
        <td>normal</td>_x000D_
        <td>normal</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td><p>nested</p></td>_x000D_
        <td><p>nested</p></td>_x000D_
        <td><p>nested</p></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>normal</td>_x000D_
        <td>normal</td>_x000D_
        <td><p>nested</p></td>_x000D_
    </tr>_x000D_
    _x000D_
</tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Here's the demo on jsFiddle.

P.S:

If you do have nested tables (or, in the general case, wish to delegate to elements with specific depth), you can use this suggestion from the jQuery bug report.

How can I concatenate a string and a number in Python?

You would have to convert the int into a string.

# This program calculates a workers gross pay

hours = float(raw_input("Enter hours worked: \n"))

rate = float(raw_input("Enter your hourly rate of pay: \n"))

gross = hours * rate

print "Your gross pay for working " +str(hours)+ " at a rate of " + str(rate) + " hourly is $"  + str(gross)

Java's L number (long) specification

By default any integral primitive data type (byte, short, int, long) will be treated as int type by java compiler. For byte and short, as long as value assigned to them is in their range, there is no problem and no suffix required. If value assigned to byte and short exceeds their range, explicit type casting is required.

Ex:

byte b = 130; // CE: range is exceeding.

to overcome this perform type casting.

byte b = (byte)130; //valid, but chances of losing data is there.

In case of long data type, it can accept the integer value without any hassle. Suppose we assign like

Long l = 2147483647; //which is max value of int

in this case no suffix like L/l is required. By default value 2147483647 is considered by java compiler is int type. Internal type casting is done by compiler and int is auto promoted to Long type.

Long l = 2147483648; //CE: value is treated as int but out of range 

Here we need to put suffix as L to treat the literal 2147483648 as long type by java compiler.

so finally

Long l = 2147483648L;// works fine.

Unicode, UTF, ASCII, ANSI format differences

Going down your list:

  • "Unicode" isn't an encoding, although unfortunately, a lot of documentation imprecisely uses it to refer to whichever Unicode encoding that particular system uses by default. On Windows and Java, this often means UTF-16; in many other places, it means UTF-8. Properly, Unicode refers to the abstract character set itself, not to any particular encoding.
  • UTF-16: 2 bytes per "code unit". This is the native format of strings in .NET, and generally in Windows and Java. Values outside the Basic Multilingual Plane (BMP) are encoded as surrogate pairs. These used to be relatively rarely used, but now many consumer applications will need to be aware of non-BMP characters in order to support emojis.
  • UTF-8: Variable length encoding, 1-4 bytes per code point. ASCII values are encoded as ASCII using 1 byte.
  • UTF-7: Usually used for mail encoding. Chances are if you think you need it and you're not doing mail, you're wrong. (That's just my experience of people posting in newsgroups etc - outside mail, it's really not widely used at all.)
  • UTF-32: Fixed width encoding using 4 bytes per code point. This isn't very efficient, but makes life easier outside the BMP. I have a .NET Utf32String class as part of my MiscUtil library, should you ever want it. (It's not been very thoroughly tested, mind you.)
  • ASCII: Single byte encoding only using the bottom 7 bits. (Unicode code points 0-127.) No accents etc.
  • ANSI: There's no one fixed ANSI encoding - there are lots of them. Usually when people say "ANSI" they mean "the default locale/codepage for my system" which is obtained via Encoding.Default, and is often Windows-1252 but can be other locales.

There's more on my Unicode page and tips for debugging Unicode problems.

The other big resource of code is unicode.org which contains more information than you'll ever be able to work your way through - possibly the most useful bit is the code charts.

change values in array when doing foreach

You can try this if you want to override

var newArray= [444,555,666];
var oldArray =[11,22,33];
oldArray.forEach((name, index) => oldArray [index] = newArray[index]);
console.log(newArray);

Regex date validation for yyyy-mm-dd

A simple one would be

\d{4}-\d{2}-\d{2}

Regular expression visualization

Debuggex Demo

but this does not restrict month to 1-12 and days from 1 to 31.

There are more complex checks like in the other answers, by the way pretty clever ones. Nevertheless you have to check for a valid date, because there are no checks for if a month has 28, 30, or 31 days.

How do I access (read, write) Google Sheets spreadsheets with Python?

This thread seems to be quite old. If anyone's still looking, the steps mentioned here : https://github.com/burnash/gspread work very well.

import gspread
from oauth2client.service_account import ServiceAccountCredentials
import os

os.chdir(r'your_path')

scope = ['https://spreadsheets.google.com/feeds',
     'https://www.googleapis.com/auth/drive']

creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
gc = gspread.authorize(creds)
wks = gc.open("Trial_Sheet").sheet1
wks.update_acell('H3', "I'm here!")

Make sure to drop your credentials json file in your current directory. Rename it as client_secret.json.

You might run into errors if you don't enable Google Sheet API with your current credentials.

Get value from text area

Vanilla JS

document.getElementById("textareaID").value

jQuery

$("#textareaID").val()

Cannot do the other way round (it's always good to know what you're doing)

document.getElementById("textareaID").value() // --> TypeError: Property 'value' of object #<HTMLTextAreaElement> is not a function

jQuery:

$("#textareaID").value // --> undefined

Add data dynamically to an Array

Let's say you have defined an empty array:

$myArr = array();

If you want to simply add an element, e.g. 'New Element to Array', write

$myArr[] = 'New Element to Array';

if you are calling the data from the database, below code will work fine

$sql = "SELECT $element FROM $table";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0)//if it finds any row
{
   while($result = mysql_fetch_object($query))
   {
      //adding data to the array
      $myArr[] = $result->$element;
   }
}

max(length(field)) in mysql

I suppose you could use a solution such as this one :

select name, length(name)
from users
where id = (
    select id
    from users
    order by length(name) desc
    limit 1
);

Might not be the optimal solution, though... But seems to work.

How can I create directory tree in C++/Linux?

So many approaches has been described here but most of them need hard coding of your path into your code. There is an easy solution for that problem, using QDir and QFileInfo, two classes of Qt framework. Since your already in Linux environment it should be easy to use Qt.

QString qStringFileName("path/to/the/file/that/dont/exist.txt");
QDir dir = QFileInfo(qStringFileName).dir();
if(!dir.exists()) {
        dir.mkpath(dir.path());
}

Make sure you have write access to that Path.

addEventListener for keydown on Canvas

Edit - This answer is a solution, but a much simpler and proper approach would be setting the tabindex attribute on the canvas element (as suggested by hobberwickey).

You can't focus a canvas element. A simple work around this, would be to make your "own" focus.

var lastDownTarget, canvas;
window.onload = function() {
    canvas = document.getElementById('canvas');

    document.addEventListener('mousedown', function(event) {
        lastDownTarget = event.target;
        alert('mousedown');
    }, false);

    document.addEventListener('keydown', function(event) {
        if(lastDownTarget == canvas) {
            alert('keydown');
        }
    }, false);
}

JSFIDDLE

How to force page refreshes or reloads in jQuery?

You can refresh the events after adding new ones by applying the following code: -Release the Events -set Event Source -Re-render Events

  $('#calendar').fullCalendar('removeEvents');
                  $('#calendar').fullCalendar('addEventSource', YoureventSource);         
                  $('#calendar').fullCalendar('rerenderEvents' );

That will solve the problem

Create an array of integers property in Objective-C

I'm just speculating:

I think that the variable defined in the ivars allocates the space right in the object. This prevents you from creating accessors because you can't give an array by value to a function but only through a pointer. Therefore you have to use a pointer in the ivars:

int *doubleDigits;

And then allocate the space for it in the init-method:

@synthesize doubleDigits;

- (id)init {
    if (self = [super init]) {
        doubleDigits = malloc(sizeof(int) * 10);
        /*
         * This works, but is dangerous (forbidden) because bufferDoubleDigits
         * gets deleted at the end of -(id)init because it's on the stack:
         * int bufferDoubleDigits[] = {1,2,3,4,5,6,7,8,9,10};
         * [self setDoubleDigits:bufferDoubleDigits];
         *
         * If you want to be on the safe side use memcpy() (needs #include <string.h>)
         * doubleDigits = malloc(sizeof(int) * 10);
         * int bufferDoubleDigits[] = {1,2,3,4,5,6,7,8,9,10};
         * memcpy(doubleDigits, bufferDoubleDigits, sizeof(int) * 10);
         */
    }
    return self;
}

- (void)dealloc {
    free(doubleDigits);
    [super dealloc];
}

In this case the interface looks like this:

@interface MyClass : NSObject {
    int *doubleDigits;
}
@property int *doubleDigits;

Edit:

I'm really unsure wether it's allowed to do this, are those values really on the stack or are they stored somewhere else? They are probably stored on the stack and therefore not safe to use in this context. (See the question on initializer lists)

int bufferDoubleDigits[] = {1,2,3,4,5,6,7,8,9,10};
[self setDoubleDigits:bufferDoubleDigits];

How to save the contents of a div as a image?

There are several of this same question (1, 2). One way of doing it is using canvas. Here's a working solution. Here you can see some working examples of using this library.

What is the connection string for localdb for version 11

1) Requires .NET framework 4 updated to at least 4.0.2. If you have 4.0.2, then you should have

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319\SKUs\.NETFramework,Version=v4.0.2

If you have installed latest VS 2012 chances are that you already have 4.0.2. Just verify first.

2) Next you need to have an instance of LocalDb. By default you have an instance whose name is a single v character followed by the LocalDB release version number in the format xx.x. For example, v11.0 represents SQL Server 2012. Automatic instances are public by default. You can also have named instances which are private. Named instances provide isolation from other instances and can improve performance by reducing resource contention with other database users. You can check the status of instances using the SqlLocalDb.exe utility (run it from command line).

3) Next your connection string should look like:

"Server=(localdb)\\v11.0;Integrated Security=true;"

or

"Data Source=(localdb)\\test;Integrated Security=true;"

from your code. They both are the same. Notice the two \\ required because \v and \t means special characters. Also note that what appears after (localdb)\\ is the name of your LocalDb instance. v11.0 is the default public instance, test is something I have created manually which is private.

  1. If you have a database (.mdf file) already:

    "Server=(localdb)\\Test;Integrated Security=true;AttachDbFileName= myDbFile;"
    
  2. If you don't have a Sql Server database:

    "Server=(localdb)\\v11.0;Integrated Security=true;"
    

And you can create your own database programmatically:

a) to save it in the default location with default setting:

var query = "CREATE DATABASE myDbName;";

b) To save it in a specific location with your own custom settings:

// your db name
string dbName = "myDbName";

// path to your db files:
// ensure that the directory exists and you have read write permission.
string[] files = { Path.Combine(Application.StartupPath, dbName + ".mdf"), 
                   Path.Combine(Application.StartupPath, dbName + ".ldf") };

// db creation query:
// note that the data file and log file have different logical names
var query = "CREATE DATABASE " + dbName +
    " ON PRIMARY" +
    " (NAME = " + dbName + "_data," +
    " FILENAME = '" + files[0] + "'," +
    " SIZE = 3MB," +
    " MAXSIZE = 10MB," +
    " FILEGROWTH = 10%)" +

    " LOG ON" +
    " (NAME = " + dbName + "_log," +
    " FILENAME = '" + files[1] + "'," +
    " SIZE = 1MB," +
    " MAXSIZE = 5MB," +
    " FILEGROWTH = 10%)" +
    ";";

And execute!

A sample table can be loaded into the database with something like:

 @"CREATE TABLE supportContacts 
    (
        id int identity primary key, 
        type varchar(20), 
        details varchar(30)
    );
   INSERT INTO supportContacts
   (type, details)
   VALUES
   ('Email', '[email protected]'),
   ('Twitter', '@sqlfiddle');";

Note that SqlLocalDb.exe utility doesnt give you access to databases, you separately need sqlcmd utility which is sad..

EDIT: moved position of semicolon otherwise error would occur if code was copy/pasted

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

Personally, I use

if not (x is None):

which is understood immediately without ambiguity by every programmer, even those not expert in the Python syntax.

Using both Python 2.x and Python 3.x in IPython Notebook

Following are the steps to add the python2 kernel to jupyter notebook::

open a terminal and create a new python 2 environment: conda create -n py27 python=2.7

activate the environment: Linux source activate py27 or windows activate py27

install the kernel in the env: conda install notebook ipykernel

install the kernel for outside the env: ipython kernel install --user

close the env: source deactivate

Although a late answer hope someone finds it useful :p

How do I increase the contrast of an image in Python OpenCV

img = cv2.imread("/x2.jpeg")

image = cv2.resize(img, (1800, 1800))

alpha=1.5
beta=20

new_image=cv2.addWeighted(image,alpha,np.zeros(image.shape, image.dtype),0,beta)

cv2.imshow("new",new_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Find location of a removable SD card

Here is the way I use to find the external card. Use mount cmd return then parse the vfat part.

String s = "";
try {
Process process = new ProcessBuilder().command("mount")
        .redirectErrorStream(true).start();

process.waitFor();

InputStream is = process.getInputStream();
byte[] buffer = new byte[1024];
while (is.read(buffer) != -1) {
    s = s + new String(buffer);
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}

//????mount??
String[] lines = s.split("\n");
for(int i=0; i<lines.length; i++) {
//???????????vfat??,???????????sd????
if(-1 != lines[i].indexOf(path[0]) && -1 != lines[i].indexOf("vfat")) {
    //??????
    String[] blocks = lines[i].split("\\s");
    for(int j=0; j<blocks.length; j++) {
        //????????vfat??
        if(-1 != blocks[j].indexOf(path[0])) {
            //Test if it is the external sd card.
        }
    }
}
}

I want to remove double quotes from a String

If you only want to remove the boundary quotes:

function stripquotes(a) {
    if (a.charAt(0) === '"' && a.charAt(a.length-1) === '"') {
        return a.substr(1, a.length-2);
    }
    return a;
}

This approach won't touch the string if it doesn't look like "text in quotes".

How do I compare two hashes?

Rails is deprecating the diff method.

For a quick one-liner:

hash1.to_s == hash2.to_s

How to install Laravel's Artisan?

Use the project's root folder

Artisan comes with Laravel by default, if your php command works fine, then the only thing you need to do is to navigate to the project's root folder. The root folder is the parent folder of the app folder. For example:

cd c:\Program Files\xampp\htdocs\your-project-name

Now the php artisan list command should work fine, because PHP runs the file called artisan in the project's folder.

Install the framework

Keep in mind that Artisan runs scripts stored in the vendor folder, so if you installed Laravel without Composer, like downloading and extracting the Laravel GitHub repo, then you don't have the framework itself and you may get the following error when you try to use Artisan:

Could not open input file: artisan

To solve this you have to install the framework itself by running composer install in your project's root folder.

SQL Error with Order By in Subquery

Try moving the order by clause outside sub select and add the order by field in sub select



SELECT * FROM 

(SELECT COUNT(1) ,refKlinik_id FROM Seanslar WHERE MONTH(tarihi) = 4 GROUP BY refKlinik_id)
as dorduncuay 

ORDER BY refKlinik_id 

org.hibernate.MappingException: Could not determine type for: java.util.Set

I had similar problem I found the issue I was mixing the annotations some of them above the attributes and some of them above public methods. I just put all of them above attributes and it works.

What is the opposite of evt.preventDefault();

You can always use this attached to some click event in your script:

location.href = this.href;

example of usage is:

jQuery('a').click(function(e) {
    location.href = this.href;
});

Make an image follow mouse pointer

Ok, here's a simple box that follows the cursor

Doing the rest is a simple case of remembering the last cursor position and applying a formula to get the box to move other than exactly where the cursor is. A timeout would also be handy if the box has a limited acceleration and must catch up to the cursor after it stops moving. Replacing the box with an image is simple CSS (which can replace most of the setup code for the box). I think the actual thinking code in the example is about 8 lines.

Select the right image (use a sprite) to orientate the rocket.

Yeah, annoying as hell. :-)

_x000D_
_x000D_
function getMouseCoords(e) {
  var e = e || window.event;
  document.getElementById('container').innerHTML = e.clientX + ', ' +
    e.clientY + '<br>' + e.screenX + ', ' + e.screenY;
}


var followCursor = (function() {
  var s = document.createElement('div');
  s.style.position = 'absolute';
  s.style.margin = '0';
  s.style.padding = '5px';
  s.style.border = '1px solid red';
  s.textContent = ""

  return {
    init: function() {
      document.body.appendChild(s);
    },

    run: function(e) {
      var e = e || window.event;
      s.style.left = (e.clientX - 5) + 'px';
      s.style.top = (e.clientY - 5) + 'px';
      getMouseCoords(e);
    }
  };
}());

window.onload = function() {
  followCursor.init();
  document.body.onmousemove = followCursor.run;
}
_x000D_
#container {
  width: 1000px;
  height: 1000px;
  border: 1px solid blue;
}
_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

WCF gives an unsecured or incorrectly secured fault error

Try changing your security mode to "transport".

You have a mismatch between the security tag and the transport tag.

Highlighting Text Color using Html.fromHtml() in Android?

 String name = modelOrderList.get(position).getName();   //get name from List
    String text = "<font color='#000000'>" + name + "</font>"; //set Black color of name
    /* check API version, according to version call method of Html class  */
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.N) {
        Log.d(TAG, "onBindViewHolder: if");
        holder.textViewName.setText(context.getString(R.string._5687982) + " ");
        holder.textViewName.append(Html.fromHtml(text));
    } else {
        Log.d(TAG, "onBindViewHolder: else");
        holder.textViewName.setText("123456" + " ");   //set text 
        holder.textViewName.append(Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY));   //append text into textView
    }

How to resize an image to fit in the browser window?

Use this code in your style tag

<style>
html {
  background: url(imagename) no-repeat center center fixed;
  background-size: cover;
  height: 100%;
  overflow: hidden;
}
</style>

Java - how do I write a file to a specified directory

The best practice is using File.separator in the paths.

Query comparing dates in SQL

Try to use "#" before and after of the date and be sure of your system date format. maybe "YYYYMMDD O YYYY-MM-DD O MM-DD-YYYY O USING '/ O \' "

Ex:

 select id,numbers_from,created_date,amount_numbers,SMS_text 
 from Test_Table
 where 
 created_date <= #2013-04-12#

How to get the selected value from RadioButtonList?

Using your radio button's ID, try rb.SelectedValue.

how to make a full screen div, and prevent size to be changed by content?

Notice how most of these can only be used WITHOUT a DOCTYPE. I'm looking for the same answer, but I have a DOCTYPE. There is one way to do it with a DOCTYPE however, although it doesn't apply to the style of my site, but it will work on the type of page you want to create:

div#full-size{
    position: absolute;
    top:0;
    bottom:0;
    right:0;
    left:0;
    overflow:hidden;

Now, this was mentioned earlier but I just wanted to clarify that this is normally used with a DOCTYPE, height:100%; only works without a DOCTYPE

How to check if BigDecimal variable == 0 in java?

A simple and better way for your exemple is:

BigDecimal price;

if(BigDecimal.ZERO.compareTo(price) == 0){
    
   //Returns TRUE

}

jQuery, simple polling example

Here's a helpful article on long polling (long-held HTTP request) using jQuery. A code snippet derived from this article:

(function poll() {
    setTimeout(function() {
        $.ajax({
            url: "/server/api/function",
            type: "GET",
            success: function(data) {
                console.log("polling");
            },
            dataType: "json",
            complete: poll,
            timeout: 2000
        })
    }, 5000);
})();

This will make the next request only after the ajax request has completed.

A variation on the above that will execute immediately the first time it is called before honouring the wait/timeout interval.

(function poll() {
    $.ajax({
        url: "/server/api/function",
        type: "GET",
        success: function(data) {
            console.log("polling");
        },
        dataType: "json",
        complete: setTimeout(function() {poll()}, 5000),
        timeout: 2000
    })
})();

Shell script to check if file exists

for entry in "/home/loc/etc/"/*
do

   if [ -s /home/loc/etc/$entry ]
   then
       echo "$entry File is available"
   else
       echo "$entry File is not available"
fi
done

Hope it helps

center aligning a fixed position div

If you know the width is 400px this would be the easiest way to do it I guess.

 left: calc(50% - 200px);

Could not reserve enough space for object heap to start JVM

It looks like the machine you're trying to run this on has only 256 MB memory.

Maybe the JVM tries to allocate a large, contiguous block of 64 MB memory. The 192 MB that you have free might be fragmented into smaller pieces, so that there is no contiguous block of 64 MB free to allocate.

Try starting your Java program with a smaller heap size, for example:

java -Xms16m ...

Properly escape a double quote in CSV

Not only double quotes, you will be in need for single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).

Use fputcsv() to write, and fgetcsv() to read, which will take care of all.

How to set cursor position in EditText?

If you want to set cursor position in EditText? try these below code

EditText rename;
 String title = "title_goes_here";
 int counts = (int) title.length();
 rename.setSelection(counts);
 rename.setText(title);

Using for loop inside of a JSP

Do this

    <% for(int i = 0; i < allFestivals.size(); i+=1) { %>
        <tr>      
            <td><%=allFestivals.get(i).getFestivalName()%></td>
        </tr>
    <% } %>

Better way is to use c:foreach see link jstl for each

In git, what is the difference between merge --squash and rebase?

Let's start by the following example:

enter image description here

Now we have 3 options to merge changes of feature branch into master branch:

  1. Merge commits
    Will keep all commits history of the feature branch and move them into the master branch
    Will add extra dummy commit.

  2. Rebase and merge
    Will append all commits history of the feature branch in the front of the master branch
    Will NOT add extra dummy commit.

  3. Squash and merge
    Will group all feature branch commits into one commit then append it in the front of the master branch
    Will add extra dummy commit.

You can find below how the master branch will look after each one of them.

enter image description here

In all cases:
We can safely DELETE the feature branch.

Java 8 stream's .min() and .max(): why does this compile?

Apart from the information given by David M. Lloyd one could add that the mechanism that allows this is called target typing.

The idea is that the type the compiler assigns to a lambda expressions or a method references does not depend only on the expression itself, but also on where it is used.

The target of an expression is the variable to which its result is assigned or the parameter to which its result is passed.

Lambda expressions and method references are assigned a type which matches the type of their target, if such a type can be found.

See the Type Inference section in the Java Tutorial for more information.

Monitor network activity in Android Phones

You would need to root the phone and cross compile tcpdump or use someone else's already compiled version.

You might find it easier to do these experiments with the emulator, in which case you could do the monitoring from the hosting pc. If you must use a real device, another option would be to put it on a wifi network hanging off of a secondary interface on a linux box running tcpdump.

I don't know off the top of my head how you would go about filtering by a specific process. One suggestion I found in some quick googling is to use strace on the subject process instead of tcpdump on the system.

How to echo JSON in PHP

Native JSON support has been included in PHP since 5.2 in the form of methods json_encode() and json_decode(). You would use the first to output a PHP variable in JSON.

How to open .SQLite files

My favorite:

https://inloop.github.io/sqlite-viewer/

No installation needed. Just drop the file.

incompatible character encodings: ASCII-8BIT and UTF-8

I solved it by following these steps:

  • Make sure config.encoding = "utf-8" is in the application.rb file.
  • Make sure you are using the 'mysql2' gem.
  • Put # encoding: utf-8 at the top of file containing UTF-8 characters.
  • Above the <App Name>::Application.initialize! line in the environment.rb file, add following two lines:

    Encoding.default_external = Encoding::UTF_8
    Encoding.default_internal = Encoding::UTF_8
    

http://rorguide.blogspot.com/2011/06/incompatible-character-encodings-ascii.html

jQuery ui datepicker with Angularjs

I finally was able to run datepicker directive in angular js , here are pointers

include following JS in order

  1. jquery.js
  2. jquery-ui.js
  3. angular-min.js

I added the following

<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"> </script>      

in html code

<body ng-app="myApp" ng-controller="myController">
// some other html code 
<input type="text" ng-model="date" mydatepicker />
<br/>
 {{ date }}
 //some other html code
 </body>

in the js , make sure you code for the directive first and after that add the code for controller , else it will cause issues.

date picker directive :

var app = angular.module('myApp',[]);
app.directive('mydatepicker', function () {
return {
    restrict: 'A',
    require: 'ngModel',
     link: function (scope, element, attrs, ngModelCtrl) {
        element.datepicker({
            dateFormat: 'DD, d  MM, yy',
            onSelect: function (date) {
                scope.date = date;
                scope.$apply();
            }
        });
    }
  };
});

directive code referred from above answers.

After this directive , write the controller

app.controller('myController',function($scope){
//controller code
};

TRY THIS INSTEAD in angular js

  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>  

along with jquery.js and jquery-ui.js

we can implement angular js datepicker as

<input type="date" ng-model="date" name="DOB">

This gives the built in datepicker and date is set in ng-model and can be used for further processing and validation.

Found this after lot of successful headbanging with previous approach. :)

Return JSON response from Flask view

As of version 1.1.0 Flask, if a view returns a dict it will be turned into a JSON response.

@app.route("/users", methods=['GET'])
def get_user():
    return {
        "user": "John Doe",
    }

Mocking Logger and LoggerFactory with PowerMock and Mockito

Somewhat late to the party - I was doing something similar and needed some pointers and ended up here. Taking no credit - I took all of the code from Brice but got the "zero interactions" than Cengiz got.

Using guidance from what jheriks amd Joseph Lust had put I think I know why - I had my object under test as a field and newed it up in a @Before unlike Brice. Then the actual logger was not the mock but a real class init'd as jhriks suggested...

I would normally do this for my object under test so as to get a fresh object for each test. When I moved the field to a local and newed it in the test it ran ok. However, if I tried a second test it was not the mock in my test but the mock from the first test and I got the zero interactions again.

When I put the creation of the mock in the @BeforeClass the logger in the object under test is always the mock but see the note below for the problems with this...

Class under test

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyClassWithSomeLogging  {

    private static final Logger LOG = LoggerFactory.getLogger(MyClassWithSomeLogging.class);

    public void doStuff(boolean b) {
        if(b) {
            LOG.info("true");
        } else {
            LOG.info("false");
        }

    }
}

Test

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.mockito.Mockito.*;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.*;
import static org.powermock.api.mockito.PowerMockito.when;


@RunWith(PowerMockRunner.class)
@PrepareForTest({LoggerFactory.class})
public class MyClassWithSomeLoggingTest {

    private static Logger mockLOG;

    @BeforeClass
    public static void setup() {
        mockStatic(LoggerFactory.class);
        mockLOG = mock(Logger.class);
        when(LoggerFactory.getLogger(any(Class.class))).thenReturn(mockLOG);
    }

    @Test
    public void testIt() {
        MyClassWithSomeLogging myClassWithSomeLogging = new MyClassWithSomeLogging();
        myClassWithSomeLogging.doStuff(true);

        verify(mockLOG, times(1)).info("true");
    }

    @Test
    public void testIt2() {
        MyClassWithSomeLogging myClassWithSomeLogging = new MyClassWithSomeLogging();
        myClassWithSomeLogging.doStuff(false);

        verify(mockLOG, times(1)).info("false");
    }

    @AfterClass
    public static void verifyStatic() {
        verify(mockLOG, times(1)).info("true");
        verify(mockLOG, times(1)).info("false");
        verify(mockLOG, times(2)).info(anyString());
    }
}

Note

If you have two tests with the same expectation I had to do the verify in the @AfterClass as the invocations on the static are stacked up - verify(mockLOG, times(2)).info("true"); - rather than times(1) in each test as the second test would fail saying there where 2 invocation of this. This is pretty pants but I couldn't find a way to clear the invocations. I'd like to know if anyone can think of a way round this....

CSS root directory

click here for good explaination!

All you need to know about relative file paths:

Starting with "/" returns to the root directory and starts there

Starting with "../" moves one directory backward and starts there

Starting with "../../" moves two directories backward and starts there (and so on...)

To move forward, just start with the first subdirectory and keep moving forward

How to run python script in webpage

Well, OP didn't say server or client side, so i will just leave this here in case someone like me is looking for client side:

http://skulpt.org/using.html

Skulpt is a implementation of Python to run at client side. Very interesting, no plugin required, just a simple JS.

What are metaclasses in Python?

Classes as objects

Before understanding metaclasses, you need to master classes in Python. And Python has a very peculiar idea of what classes are, borrowed from the Smalltalk language.

In most languages, classes are just pieces of code that describe how to produce an object. That's kinda true in Python too:

>>> class ObjectCreator(object):
...       pass
...

>>> my_object = ObjectCreator()
>>> print(my_object)
<__main__.ObjectCreator object at 0x8974f2c>

But classes are more than that in Python. Classes are objects too.

Yes, objects.

As soon as you use the keyword class, Python executes it and creates an OBJECT. The instruction

>>> class ObjectCreator(object):
...       pass
...

creates in memory an object with the name "ObjectCreator".

This object (the class) is itself capable of creating objects (the instances), and this is why it's a class.

But still, it's an object, and therefore:

  • you can assign it to a variable
  • you can copy it
  • you can add attributes to it
  • you can pass it as a function parameter

e.g.:

>>> print(ObjectCreator) # you can print a class because it's an object
<class '__main__.ObjectCreator'>
>>> def echo(o):
...       print(o)
...
>>> echo(ObjectCreator) # you can pass a class as a parameter
<class '__main__.ObjectCreator'>
>>> print(hasattr(ObjectCreator, 'new_attribute'))
False
>>> ObjectCreator.new_attribute = 'foo' # you can add attributes to a class
>>> print(hasattr(ObjectCreator, 'new_attribute'))
True
>>> print(ObjectCreator.new_attribute)
foo
>>> ObjectCreatorMirror = ObjectCreator # you can assign a class to a variable
>>> print(ObjectCreatorMirror.new_attribute)
foo
>>> print(ObjectCreatorMirror())
<__main__.ObjectCreator object at 0x8997b4c>

Creating classes dynamically

Since classes are objects, you can create them on the fly, like any object.

First, you can create a class in a function using class:

>>> def choose_class(name):
...     if name == 'foo':
...         class Foo(object):
...             pass
...         return Foo # return the class, not an instance
...     else:
...         class Bar(object):
...             pass
...         return Bar
...
>>> MyClass = choose_class('foo')
>>> print(MyClass) # the function returns a class, not an instance
<class '__main__.Foo'>
>>> print(MyClass()) # you can create an object from this class
<__main__.Foo object at 0x89c6d4c>

But it's not so dynamic, since you still have to write the whole class yourself.

Since classes are objects, they must be generated by something.

When you use the class keyword, Python creates this object automatically. But as with most things in Python, it gives you a way to do it manually.

Remember the function type? The good old function that lets you know what type an object is:

>>> print(type(1))
<type 'int'>
>>> print(type("1"))
<type 'str'>
>>> print(type(ObjectCreator))
<type 'type'>
>>> print(type(ObjectCreator()))
<class '__main__.ObjectCreator'>

Well, type has a completely different ability, it can also create classes on the fly. type can take the description of a class as parameters, and return a class.

(I know, it's silly that the same function can have two completely different uses according to the parameters you pass to it. It's an issue due to backward compatibility in Python)

type works this way:

type(name, bases, attrs)

Where:

  • name: name of the class
  • bases: tuple of the parent class (for inheritance, can be empty)
  • attrs: dictionary containing attributes names and values

e.g.:

>>> class MyShinyClass(object):
...       pass

can be created manually this way:

>>> MyShinyClass = type('MyShinyClass', (), {}) # returns a class object
>>> print(MyShinyClass)
<class '__main__.MyShinyClass'>
>>> print(MyShinyClass()) # create an instance with the class
<__main__.MyShinyClass object at 0x8997cec>

You'll notice that we use "MyShinyClass" as the name of the class and as the variable to hold the class reference. They can be different, but there is no reason to complicate things.

type accepts a dictionary to define the attributes of the class. So:

>>> class Foo(object):
...       bar = True

Can be translated to:

>>> Foo = type('Foo', (), {'bar':True})

And used as a normal class:

>>> print(Foo)
<class '__main__.Foo'>
>>> print(Foo.bar)
True
>>> f = Foo()
>>> print(f)
<__main__.Foo object at 0x8a9b84c>
>>> print(f.bar)
True

And of course, you can inherit from it, so:

>>>   class FooChild(Foo):
...         pass

would be:

>>> FooChild = type('FooChild', (Foo,), {})
>>> print(FooChild)
<class '__main__.FooChild'>
>>> print(FooChild.bar) # bar is inherited from Foo
True

Eventually, you'll want to add methods to your class. Just define a function with the proper signature and assign it as an attribute.

>>> def echo_bar(self):
...       print(self.bar)
...
>>> FooChild = type('FooChild', (Foo,), {'echo_bar': echo_bar})
>>> hasattr(Foo, 'echo_bar')
False
>>> hasattr(FooChild, 'echo_bar')
True
>>> my_foo = FooChild()
>>> my_foo.echo_bar()
True

And you can add even more methods after you dynamically create the class, just like adding methods to a normally created class object.

>>> def echo_bar_more(self):
...       print('yet another method')
...
>>> FooChild.echo_bar_more = echo_bar_more
>>> hasattr(FooChild, 'echo_bar_more')
True

You see where we are going: in Python, classes are objects, and you can create a class on the fly, dynamically.

This is what Python does when you use the keyword class, and it does so by using a metaclass.

What are metaclasses (finally)

Metaclasses are the 'stuff' that creates classes.

You define classes in order to create objects, right?

But we learned that Python classes are objects.

Well, metaclasses are what create these objects. They are the classes' classes, you can picture them this way:

MyClass = MetaClass()
my_object = MyClass()

You've seen that type lets you do something like this:

MyClass = type('MyClass', (), {})

It's because the function type is in fact a metaclass. type is the metaclass Python uses to create all classes behind the scenes.

Now you wonder why the heck is it written in lowercase, and not Type?

Well, I guess it's a matter of consistency with str, the class that creates strings objects, and int the class that creates integer objects. type is just the class that creates class objects.

You see that by checking the __class__ attribute.

Everything, and I mean everything, is an object in Python. That includes ints, strings, functions and classes. All of them are objects. And all of them have been created from a class:

>>> age = 35
>>> age.__class__
<type 'int'>
>>> name = 'bob'
>>> name.__class__
<type 'str'>
>>> def foo(): pass
>>> foo.__class__
<type 'function'>
>>> class Bar(object): pass
>>> b = Bar()
>>> b.__class__
<class '__main__.Bar'>

Now, what is the __class__ of any __class__ ?

>>> age.__class__.__class__
<type 'type'>
>>> name.__class__.__class__
<type 'type'>
>>> foo.__class__.__class__
<type 'type'>
>>> b.__class__.__class__
<type 'type'>

So, a metaclass is just the stuff that creates class objects.

You can call it a 'class factory' if you wish.

type is the built-in metaclass Python uses, but of course, you can create your own metaclass.

The __metaclass__ attribute

In Python 2, you can add a __metaclass__ attribute when you write a class (see next section for the Python 3 syntax):

class Foo(object):
    __metaclass__ = something...
    [...]

If you do so, Python will use the metaclass to create the class Foo.

Careful, it's tricky.

You write class Foo(object) first, but the class object Foo is not created in memory yet.

Python will look for __metaclass__ in the class definition. If it finds it, it will use it to create the object class Foo. If it doesn't, it will use type to create the class.

Read that several times.

When you do:

class Foo(Bar):
    pass

Python does the following:

Is there a __metaclass__ attribute in Foo?

If yes, create in-memory a class object (I said a class object, stay with me here), with the name Foo by using what is in __metaclass__.

If Python can't find __metaclass__, it will look for a __metaclass__ at the MODULE level, and try to do the same (but only for classes that don't inherit anything, basically old-style classes).

Then if it can't find any __metaclass__ at all, it will use the Bar's (the first parent) own metaclass (which might be the default type) to create the class object.

Be careful here that the __metaclass__ attribute will not be inherited, the metaclass of the parent (Bar.__class__) will be. If Bar used a __metaclass__ attribute that created Bar with type() (and not type.__new__()), the subclasses will not inherit that behavior.

Now the big question is, what can you put in __metaclass__?

The answer is something that can create a class.

And what can create a class? type, or anything that subclasses or uses it.

Metaclasses in Python 3

The syntax to set the metaclass has been changed in Python 3:

class Foo(object, metaclass=something):
    ...

i.e. the __metaclass__ attribute is no longer used, in favor of a keyword argument in the list of base classes.

The behavior of metaclasses however stays largely the same.

One thing added to metaclasses in Python 3 is that you can also pass attributes as keyword-arguments into a metaclass, like so:

class Foo(object, metaclass=something, kwarg1=value1, kwarg2=value2):
    ...

Read the section below for how python handles this.

Custom metaclasses

The main purpose of a metaclass is to change the class automatically, when it's created.

You usually do this for APIs, where you want to create classes matching the current context.

Imagine a stupid example, where you decide that all classes in your module should have their attributes written in uppercase. There are several ways to do this, but one way is to set __metaclass__ at the module level.

This way, all classes of this module will be created using this metaclass, and we just have to tell the metaclass to turn all attributes to uppercase.

Luckily, __metaclass__ can actually be any callable, it doesn't need to be a formal class (I know, something with 'class' in its name doesn't need to be a class, go figure... but it's helpful).

So we will start with a simple example, by using a function.

# the metaclass will automatically get passed the same argument
# that you usually pass to `type`
def upper_attr(future_class_name, future_class_parents, future_class_attrs):
    """
      Return a class object, with the list of its attribute turned
      into uppercase.
    """
    # pick up any attribute that doesn't start with '__' and uppercase it
    uppercase_attrs = {
        attr if attr.startswith("__") else attr.upper(): v
        for attr, v in future_class_attrs.items()
    }

    # let `type` do the class creation
    return type(future_class_name, future_class_parents, uppercase_attrs)

__metaclass__ = upper_attr # this will affect all classes in the module

class Foo(): # global __metaclass__ won't work with "object" though
    # but we can define __metaclass__ here instead to affect only this class
    # and this will work with "object" children
    bar = 'bip'

Let's check:

>>> hasattr(Foo, 'bar')
False
>>> hasattr(Foo, 'BAR')
True
>>> Foo.BAR
'bip'

Now, let's do exactly the same, but using a real class for a metaclass:

# remember that `type` is actually a class like `str` and `int`
# so you can inherit from it
class UpperAttrMetaclass(type):
    # __new__ is the method called before __init__
    # it's the method that creates the object and returns it
    # while __init__ just initializes the object passed as parameter
    # you rarely use __new__, except when you want to control how the object
    # is created.
    # here the created object is the class, and we want to customize it
    # so we override __new__
    # you can do some stuff in __init__ too if you wish
    # some advanced use involves overriding __call__ as well, but we won't
    # see this
    def __new__(upperattr_metaclass, future_class_name,
                future_class_parents, future_class_attrs):
        uppercase_attrs = {
            attr if attr.startswith("__") else attr.upper(): v
            for attr, v in future_class_attrs.items()
        }
        return type(future_class_name, future_class_parents, uppercase_attrs)

Let's rewrite the above, but with shorter and more realistic variable names now that we know what they mean:

class UpperAttrMetaclass(type):
    def __new__(cls, clsname, bases, attrs):
        uppercase_attrs = {
            attr if attr.startswith("__") else attr.upper(): v
            for attr, v in attrs.items()
        }
        return type(clsname, bases, uppercase_attrs)

You may have noticed the extra argument cls. There is nothing special about it: __new__ always receives the class it's defined in, as the first parameter. Just like you have self for ordinary methods which receive the instance as the first parameter, or the defining class for class methods.

But this is not proper OOP. We are calling type directly and we aren't overriding or calling the parent's __new__. Let's do that instead:

class UpperAttrMetaclass(type):
    def __new__(cls, clsname, bases, attrs):
        uppercase_attrs = {
            attr if attr.startswith("__") else attr.upper(): v
            for attr, v in attrs.items()
        }
        return type.__new__(cls, clsname, bases, uppercase_attrs)

We can make it even cleaner by using super, which will ease inheritance (because yes, you can have metaclasses, inheriting from metaclasses, inheriting from type):

class UpperAttrMetaclass(type):
    def __new__(cls, clsname, bases, attrs):
        uppercase_attrs = {
            attr if attr.startswith("__") else attr.upper(): v
            for attr, v in attrs.items()
        }
        return super(UpperAttrMetaclass, cls).__new__(
            cls, clsname, bases, uppercase_attrs)

Oh, and in python 3 if you do this call with keyword arguments, like this:

class Foo(object, metaclass=MyMetaclass, kwarg1=value1):
    ...

It translates to this in the metaclass to use it:

class MyMetaclass(type):
    def __new__(cls, clsname, bases, dct, kwargs1=default):
        ...

That's it. There is really nothing more about metaclasses.

The reason behind the complexity of the code using metaclasses is not because of metaclasses, it's because you usually use metaclasses to do twisted stuff relying on introspection, manipulating inheritance, vars such as __dict__, etc.

Indeed, metaclasses are especially useful to do black magic, and therefore complicated stuff. But by themselves, they are simple:

  • intercept a class creation
  • modify the class
  • return the modified class

Why would you use metaclasses classes instead of functions?

Since __metaclass__ can accept any callable, why would you use a class since it's obviously more complicated?

There are several reasons to do so:

  • The intention is clear. When you read UpperAttrMetaclass(type), you know what's going to follow
  • You can use OOP. Metaclass can inherit from metaclass, override parent methods. Metaclasses can even use metaclasses.
  • Subclasses of a class will be instances of its metaclass if you specified a metaclass-class, but not with a metaclass-function.
  • You can structure your code better. You never use metaclasses for something as trivial as the above example. It's usually for something complicated. Having the ability to make several methods and group them in one class is very useful to make the code easier to read.
  • You can hook on __new__, __init__ and __call__. Which will allow you to do different stuff, Even if usually you can do it all in __new__, some people are just more comfortable using __init__.
  • These are called metaclasses, damn it! It must mean something!

Why would you use metaclasses?

Now the big question. Why would you use some obscure error-prone feature?

Well, usually you don't:

Metaclasses are deeper magic that 99% of users should never worry about it. If you wonder whether you need them, you don't (the people who actually need them to know with certainty that they need them and don't need an explanation about why).

Python Guru Tim Peters

The main use case for a metaclass is creating an API. A typical example of this is the Django ORM. It allows you to define something like this:

class Person(models.Model):
    name = models.CharField(max_length=30)
    age = models.IntegerField()

But if you do this:

person = Person(name='bob', age='35')
print(person.age)

It won't return an IntegerField object. It will return an int, and can even take it directly from the database.

This is possible because models.Model defines __metaclass__ and it uses some magic that will turn the Person you just defined with simple statements into a complex hook to a database field.

Django makes something complex look simple by exposing a simple API and using metaclasses, recreating code from this API to do the real job behind the scenes.

The last word

First, you know that classes are objects that can create instances.

Well, in fact, classes are themselves instances. Of metaclasses.

>>> class Foo(object): pass
>>> id(Foo)
142630324

Everything is an object in Python, and they are all either instance of classes or instances of metaclasses.

Except for type.

type is actually its own metaclass. This is not something you could reproduce in pure Python, and is done by cheating a little bit at the implementation level.

Secondly, metaclasses are complicated. You may not want to use them for very simple class alterations. You can change classes by using two different techniques:

99% of the time you need class alteration, you are better off using these.

But 98% of the time, you don't need class alteration at all.

Enum "Inheritance"

I realize I'm a bit late to this party, but here's my two cents.

We're all clear that Enum inheritance is not supported by the framework. Some very interesting workarounds have been suggested in this thread, but none of them felt quite like what I was looking for, so I had a go at it myself.

Introducing: ObjectEnum

You can check the code and documentation here: https://github.com/dimi3tron/ObjectEnum.

And the package here: https://www.nuget.org/packages/ObjectEnum

Or just install it: Install-Package ObjectEnum

In short, ObjectEnum<TEnum> acts as a wrapper for any enum. By overriding the GetDefinedValues() in subclasses, one can specify which enum values are valid for this specific class.

A number of operator overloads have been added to make an ObjectEnum<TEnum> instance behave as if it were an instance of the underlying enum, keeping in mind the defined value restrictions. This means you can easily compare the instance to an int or enum value, and thus use it in a switch case or any other conditional.

I'd like to refer to the github repo mentioned above for examples and further info.

I hope you find this useful. Feel free to comment or open an issue on github for further thoughts or comments.

Here are a few short examples of what you can do with ObjectEnum<TEnum>:

var sunday = new WorkDay(DayOfWeek.Sunday); //throws exception
var monday = new WorkDay(DayOfWeek.Monday); //works fine
var label = $"{monday} is day {(int)monday}." //produces: "Monday is day 1."
var mondayIsAlwaysMonday = monday == DayOfWeek.Monday; //true, sorry...

var friday = new WorkDay(DayOfWeek.Friday);

switch((DayOfWeek)friday){
    case DayOfWeek.Monday:
        //do something monday related
        break;
        /*...*/
    case DayOfWeek.Friday:
        //do something friday related
        break;
}

Requested registry access is not allowed

You can't write to the HKCR (or HKLM) hives in Vista and newer versions of Windows unless you have administrative privileges. Therefore, you'll either need to be logged in as an Administrator before you run your utility, give it a manifest that says it requires Administrator level (which will prompt the user for Admin login info), or quit changing things in places that non-Administrators shouldn't be playing. :-)

PowerShell To Set Folder Permissions

Specifying inheritance in the FileSystemAccessRule() constructor fixes this, as demonstrated by the modified code below (notice the two new constuctor parameters inserted between "FullControl" and "Allow").

$Acl = Get-Acl "\\R9N2WRN\Share"

$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("user", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")

$Acl.SetAccessRule($Ar)
Set-Acl "\\R9N2WRN\Share" $Acl

According to this topic

"when you create a FileSystemAccessRule the way you have, the InheritanceFlags property is set to None. In the GUI, this corresponds to an ACE with the Apply To box set to "This Folder Only", and that type of entry has to be viewed through the Advanced settings."

I have tested the modification and it works, but of course credit is due to the MVP posting the answer in that topic.

Grant Select on a view not base table when base table is in a different database

I had a similar issue where I was getting the same error message for a user. I feel that by sharing my mistake, I can clear up the issue, answer the question, and prevent others from making the same mistake.
I wanted a user to have access to 4 particular views without having access to their underlying tables (or anything else in the DB for that matter).
Initially I gave them the database role membership of "db_denydatareader" thinking that this would prevent them from selecting anything from any table or view (which it did - as I thought), though I then granted "select" on these 4 views assuming that it would work as I intended - it did not.
The correct way to do it is to simply not grant them the db_datareader role and simply grant "select" on the items which you want the user to be able to access. The results of the above was that the user was able to access absolutely nothing outside these 4 views - the tables which these views area based on are also not available to this user.

Check if program is running with bash shell script?

You can achieve almost everything in PROCESS_NUM with this one-liner:

[ `pgrep $1` ] && return 1 || return 0

if you're looking for a partial match, i.e. program is named foobar and you want your $1 to be just foo you can add the -f switch to pgrep:

[[ `pgrep -f $1` ]] && return 1 || return 0

Putting it all together your script could be reworked like this:

#!/bin/bash

check_process() {
  echo "$ts: checking $1"
  [ "$1" = "" ]  && return 0
  [ `pgrep -n $1` ] && return 1 || return 0
}

while [ 1 ]; do 
  # timestamp
  ts=`date +%T`

  echo "$ts: begin checking..."
  check_process "dropbox"
  [ $? -eq 0 ] && echo "$ts: not running, restarting..." && `dropbox start -i > /dev/null`
  sleep 5
done

Running it would look like this:

# SHELL #1
22:07:26: begin checking...
22:07:26: checking dropbox
22:07:31: begin checking...
22:07:31: checking dropbox

# SHELL #2
$ dropbox stop
Dropbox daemon stopped.

# SHELL #1
22:07:36: begin checking...
22:07:36: checking dropbox
22:07:36: not running, restarting...
22:07:42: begin checking...
22:07:42: checking dropbox

Hope this helps!

javascript - Create Simple Dynamic Array

A little late to this game, but there is REALLY cool stuff you can do with ES6 these days.

You can now fill an array of dynamic length with random numbers in one line of code!

[...Array(10).keys()].map(() => Math.floor(Math.random() * 100))

How to change content on hover

This little and simple trick I just learnt may help someone trying to avoid :before or :after pseudo elements altogether (for whatever reason) in changing text on hover. You can add both texts in the HTML, but vary the CSS 'display' property based on hover. Assuming the second text 'Add' has a class named 'add-label'; here is a little modification:

span.add-label{
 display:none;
}
.item:hover span.align{
 display:none;
}
.item:hover span.add-label{
 display:block;
}

Here is a demonstration on codepen: https://codepen.io/ifekt/pen/zBaEVJ

How do I find the value of $CATALINA_HOME?

Tomcat can tell you in several ways. Here's the easiest:

 $ /path/to/catalina.sh version
Using CATALINA_BASE:   /usr/local/apache-tomcat-7.0.29
Using CATALINA_HOME:   /usr/local/apache-tomcat-7.0.29
Using CATALINA_TMPDIR: /usr/local/apache-tomcat-7.0.29/temp
Using JRE_HOME:        /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
Using CLASSPATH:       /usr/local/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/local/apache-tomcat-7.0.29/bin/tomcat-juli.jar
Server version: Apache Tomcat/7.0.29
Server built:   Jul 3 2012 11:31:52
Server number:  7.0.29.0
OS Name:        Mac OS X
OS Version:     10.7.4
Architecture:   x86_64
JVM Version:    1.6.0_33-b03-424-11M3720
JVM Vendor:     Apple Inc.

If you don't know where catalina.sh is (or it never gets called), you can usually find it via ps:

$ ps aux | grep catalina
chris            930   0.0  3.1  2987336 258328 s000  S    Wed01PM   2:29.43 /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java -Dnop -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.library.path=/usr/local/apache-tomcat-7.0.29/lib -Djava.endorsed.dirs=/usr/local/apache-tomcat-7.0.29/endorsed -classpath /usr/local/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/local/apache-tomcat-7.0.29/bin/tomcat-juli.jar -Dcatalina.base=/Users/chris/blah/blah -Dcatalina.home=/usr/local/apache-tomcat-7.0.29 -Djava.io.tmpdir=/Users/chris/blah/blah/temp org.apache.catalina.startup.Bootstrap start

From the ps output, you can see both catalina.home and catalina.base. catalina.home is where the Tomcat base files are installed, and catalina.base is where the running configuration of Tomcat exists. These are often set to the same value unless you have configured your Tomcat for multiple (configuration) instances to be launched from a single Tomcat base install.

You can also interrogate the JVM directly if you can't find it in a ps listing:

$ jinfo -sysprops 930 | grep catalina
Attaching to process ID 930, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 20.8-b03-424
catalina.base = /Users/chris/blah/blah
[...]
catalina.home = /usr/local/apache-tomcat-7.0.29

If you can't manage that, you can always try to write a JSP that dumps the values of the two system properties catalina.home and catalina.base.

How do I use boolean variables in Perl?

Beautiful explanation given by bobf for Boolean values : True or False? A Quick Reference Guide

Truth tests for different values

                       Result of the expression when $var is:

Expression          | 1      | '0.0'  | a string | 0     | empty str | undef
--------------------+--------+--------+----------+-------+-----------+-------
if( $var )          | true   | true   | true     | false | false     | false
if( defined $var )  | true   | true   | true     | true  | true      | false
if( $var eq '' )    | false  | false  | false    | false | true      | true
if( $var == 0 )     | false  | true   | true     | true  | true      | true

How to grey out a button?

You should create a XML file for the disabled button (drawable/btn_disable.xml)

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/grey" />
    <corners android:radius="6dp" />
</shape>

And create a selector for the button (drawable/btn_selector.xml)

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/btn_disable" android:state_enabled="false"/>
    <item android:drawable="@drawable/btn_default" android:state_enabled="true"/>
    <item android:drawable="@drawable/btn_default" android:state_pressed="false" />

</selector>

Add the selector to your button

<style name="srp_button" parent="@android:style/Widget.Button">
    <item name="android:background">@drawable/btn_selector</item>
</style>

Get top first record from duplicate records having no unique identity

Doesn't SELECT DISTINCT help? I suppose it would return the result you want.

javascript password generator

This will produce a realistic password if having characters [\]^_ is fine. Requires lodash and es7

String.fromCodePoint(...range(8).map(() => Math.floor(Math.random() * 57) + 0x41))

and here's without lodash

String.fromCodePoint(...Array.from({length: 8}, () => Math.floor(Math.random() * 57) + 65))

How does Python manage int and long?

On my machine:

>>> print type(1<<30)
<type 'int'>
>>> print type(1<<31)
<type 'long'>
>>> print type(0x7FFFFFFF)
<type 'int'>
>>> print type(0x7FFFFFFF+1)
<type 'long'>

Python uses ints (32 bit signed integers, I don't know if they are C ints under the hood or not) for values that fit into 32 bit, but automatically switches to longs (arbitrarily large number of bits - i.e. bignums) for anything larger. I'm guessing this speeds things up for smaller values while avoiding any overflows with a seamless transition to bignums.

CSS3 transition doesn't work with display property

I faced the problem with display:none

I have several horizontal bars with transition effects but I wanted to show only part of that container and fold the rest while maintaining the effects. I reproduced a small demo here

The obvious was to wrap those hidden animated bars in a div then toggle that element's height and opacity

.hide{
  opacity: 0;
  height: 0;
}
.bars-wrapper.expanded > .hide{
 opacity: 1;
 height: auto;
}

The animation works well but the issue was that these hidden bars were still consuming space on my page and overlapping other elements

enter image description here

so adding display:none to the hidden wrapper .hide solves the margin issue but not the transition, neither applying display:none or height:0;opacity:0 works on the children elements.

So my final workaround was to give those hidden bars a negative and absolute position and it worked well with CSS transitions.

Jsfiddle

How to download a file from a URL in C#?

Also you can use DownloadFileAsync method in WebClient class. It downloads to a local file the resource with the specified URI. Also this method does not block the calling thread.

Sample:

    webClient.DownloadFileAsync(new Uri("http://www.example.com/file/test.jpg"), "test.jpg");

For more information:

http://csharpexamples.com/download-files-synchronous-asynchronous-url-c/

Changing the size of a column referenced by a schema-bound view in SQL Server

If anyone wants to "Increase the column width of the replicated table" in SQL Server 2008, then no need to change the property of "replicate_ddl=1". Simply follow below steps --

  1. Open SSMS
  2. Connect to Publisher database
  3. run command -- ALTER TABLE [Table_Name] ALTER COLUMN [Column_Name] varchar(22)
  4. It will increase the column width from varchar(x) to varchar(22) and same change you can see on subscriber (transaction got replicated). So no need to re-initialize the replication

Hope this will help all who are looking for it.

Is SQL syntax case sensitive?

Have the best of both worlds

These days you can just write all your sql statements in lowercase and if you ever need to have it formatted then just install a plugin that will do it for you. This is only applicable if your code editor has those plugins available. VSCode has many extensions that can do this.

Unsupported method: BaseConfig.getApplicationIdSuffix()

For Android Studio 3 I need to update two files to fix the error:--

1. app/build.gradle

buildscript {
    repositories {
        jcenter()
        mavenCentral()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
    }
}

2. app/gradle/wrapper/gradle-wrapper.properties

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

Right pad a string with variable number of spaces

Based on KMier's answer, addresses the comment that this method poses a problem when the field to be padded is not a field, but the outcome of a (possibly complicated) function; the entire function has to be repeated.

Also, this allows for padding a field to the maximum length of its contents.

WITH
cte AS (
  SELECT 'foo' AS value_to_be_padded
  UNION SELECT 'foobar'
),
cte_max AS (
  SELECT MAX(LEN(value_to_be_padded)) AS max_len
)
SELECT
  CONCAT(SPACE(max_len - LEN(value_to_be_padded)), value_to_be_padded AS left_padded,
  CONCAT(value_to_be_padded, SPACE(max_len - LEN(value_to_be_padded)) AS right_padded;

Xcode 10, Command CodeSign failed with a nonzero exit code

Not sure if this will help anyone - but make sure you have Find Implicit Dependencies checked off. Sometimes this can lead to your project "losing track" of where to look for certain things.


enter image description here


Once you do this, I suggest then also cleaning your project and rebuilding.

enter image description here

Android Layout Weight

android:Layout_weight can be used when you don't attach a fix value to your width already like fill_parent etc.

Do something like this :

<Button>

Android:layout_width="0dp"
Android:layout_weight=1

-----other parameters
</Button>

Equivalent to AssemblyInfo in dotnet core/csproj

Adding to NightOwl888's answer, you can go one step further and add an AssemblyInfo class rather than just a plain class:

enter image description here

python pandas extract year from datetime: df['year'] = df['date'].year is not working

Probably already too late to answer but since you have already parse the dates while loading the data, you can just do this to get the day

df['date'] = pd.DatetimeIndex(df['date']).year

How to determine whether a given Linux is 32 bit or 64 bit?

If you were running a 64 bit platform you would see x86_64 or something very similar in the output from uname -a

To get your specific machine hardware name run

uname -m

You can also call

getconf LONG_BIT

which returns either 32 or 64

Get the Selected value from the Drop down box in PHP

Couldn't you just pass the a name attribute and wrap it in a form?

<form id="form" action="do_stuff.php" method="post">
    <select id="select_catalog" name="select_catalog_query">
    <?php <<<INSERT THE SELECT OPTION LOOP>>> ?>
    </select>
</form>

And then look for $_POST['select_catalog_query'] ?

How to use a dot "." to access members of dictionary?

The answer of @derek73 is very neat, but it cannot be pickled nor (deep)copied, and it returns None for missing keys. The code below fixes this.

Edit: I did not see the answer above that addresses the exact same point (upvoted). I'm leaving the answer here for reference.

class dotdict(dict):
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__

    def __getattr__(self, name):
        try:
            return self[name]
        except KeyError:
            raise AttributeError(name)

Why aren't Xcode breakpoints functioning?

It has happened the same thing to me in XCode 6.3.1. I managed to fix it by:

  • Going to View->Navigators->Show Debug Navigators
  • Right click in the project root -> Move Breakpoints (If selected the User option)
  • (I also Selected the option share breakpoints, even though I'm not sure if that necessary).

After doing that change I set the Move breakpoints options back to the project, and unselecting the Share breakpoints option, and still works.

I don't exactly know why but this get my breakpoints back.

Remove quotes from a character vector in R

Here is one combining noquote and paste:

noquote(paste("Argument is of length zero",sQuote("!"),"and",dQuote("double")))


#[1] Argument is of length zero ‘!’ and “double”

How to launch an EXE from Web page (asp.net)

As part of the solution that Larry K suggested, registering your own protocol might be a possible solution. The web page could contain a simple link to download and install the application - which would then register its own protocol in the Windows registry.

The web page would then contain links with parameters that would result in the registerd program being opened and any parameters specified in the link being passed to it. There's a good description of how to do this on MSDN

How to convert 1 to true or 0 to false upon model fetch

Use a double not:

!!1 = true;

!!0 = false;

obj.isChecked = !!parseInt(obj.isChecked);

How to set initial size of std::vector?

std::vector<CustomClass *> whatever(20000);

or:

std::vector<CustomClass *> whatever;
whatever.reserve(20000);

The former sets the actual size of the array -- i.e., makes it a vector of 20000 pointers. The latter leaves the vector empty, but reserves space for 20000 pointers, so you can insert (up to) that many without it having to reallocate.

At least in my experience, it's fairly unusual for either of these to make a huge difference in performance--but either can affect correctness under some circumstances. In particular, as long as no reallocation takes place, iterators into the vector are guaranteed to remain valid, and once you've set the size/reserved space, you're guaranteed there won't be any reallocations as long as you don't increase the size beyond that.

GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag

You are calling GridView.RenderControl(htmlTextWriter), hence the page raises an exception that a Server-Control was rendered outside of a Form.

You could avoid this execption by overriding VerifyRenderingInServerForm

public override void VerifyRenderingInServerForm(Control control)
{
  /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
     server control at run time. */
}

See here and here.

jQuery date formatting

you can use the below code without the plugin.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>_x000D_
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">_x000D_
<script>_x000D_
$( function() {_x000D_
    //call the function on page load_x000D_
 $( "#datepicker" ).datepicker();_x000D_
    //set the date format here_x000D_
    $( "#datepicker" ).datepicker("option" , "dateFormat", "dd-mm-yy");_x000D_
 _x000D_
    // you also can use _x000D_
    // yy-mm-dd_x000D_
    // d M, y_x000D_
    // d MM, y_x000D_
    // DD, d MM, yy_x000D_
    // &apos;day&apos; d &apos;of&apos; MM &apos;in the year&apos; yy (With text - 'day' d 'of' MM 'in the year' yy)_x000D_
 } );_x000D_
 </script>_x000D_
_x000D_
Pick the Date: <input type="text" id="datepicker">
_x000D_
_x000D_
_x000D_

How to get file path from OpenFileDialog and FolderBrowserDialog?

Use the Path class from System.IO. It contains useful calls for manipulating file paths, including GetDirectoryName which does what you want, returning the directory portion of the file path.

Usage is simple.

string directoryPath = System.IO.Path.GetDirectoryName(choofdlog.FileName);

Which Architecture patterns are used on Android?

In Android the "work queue processor" pattern is commonly used to offload tasks from an application's main thread.

Example: The design of the IntentService class.

The IntentService receives the Intents, launch a worker thread, and stops the service as appropriate.All requests are handled on a single worker thread.

Plot smooth line with PyPlot

For this example spline works well, but if the function is not smooth inherently and you want to have smoothed version you can also try:

from scipy.ndimage.filters import gaussian_filter1d

ysmoothed = gaussian_filter1d(y, sigma=2)
plt.plot(x, ysmoothed)
plt.show()

if you increase sigma you can get a more smoothed function.

Proceed with caution with this one. It modifies the original values and may not be what you want.

Extracting first n columns of a numpy matrix

If a is your array:

In [11]: a[:,:2]
Out[11]: 
array([[-0.57098887, -0.4274751 ],
       [-0.22279713, -0.51723555],
       [ 0.67492385, -0.69294472],
       [ 0.41086611,  0.26374238]])

Cast received object to a List<object> or IEnumerable<object>

Nowadays it's like:

var collection = new List<object>(objectVar);

PHP Warning: Division by zero

If it shows an error on the first run only, it's probably because you haven't sent any POST data. You should check for POST variables before working with them. Undefined, null, empty array, empty string, etc. are all considered false; and when PHP auto-casts that false boolean value to an integer or a float, it becomes zero. That's what happens with your variables, they are not set on the first run, and thus are treated as zeroes.

10 / $unsetVariable

becomes

10 / 0

Bottom line: check if your inputs exist and if they are valid before doing anything with them, also enable error reporting when you're doing local work as it will save you a lot of time. You can enable all errors to be reported like this: error_reporting(E_ALL);

To fix your specific problem: don't do any calculations if there's no input from your form; just show the form instead.

How can I echo a newline in a batch file?

There is a standard feature echo: in cmd/bat-files to write blank line, which emulates a new line in your cmd-output:

@echo off
@echo line1
@echo:
@echo line2

Output of cited above cmd-file:

line1

line2

Importing CommonCrypto in a Swift framework

It's very simple. Add

#import <CommonCrypto/CommonCrypto.h>

to a .h file (the bridging header file of your project). As a convention you can call it YourProjectName-Bridging-Header.h.

Then go to your project Build Settings and look for Swift Compiler - Code Generation. Under it, add the name of your bridging header to the entry "Objetive-C Bridging Header".

You're done. No imports required in your Swift code. Any public Objective-C headers listed in this bridging header file will be visible to Swift.

Convert integer to hex and hex to integer

Convert int to hex:

SELECT FORMAT(512+255,'X')

Foreach in a Foreach in MVC View

Assuming your controller's action method is something like this:

public ActionResult AllCategories(int id = 0)
{
    return View(db.Categories.Include(p => p.Products).ToList());
}

Modify your models to be something like this:

public class Product
{
    [Key]
    public int ID { get; set; }
    public int CategoryID { get; set; }
    //new code
    public virtual Category Category { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Path { get; set; }

    //remove code below
    //public virtual ICollection<Category> Categories { get; set; }
}

public class Category
{
    [Key]
    public int CategoryID { get; set; }
    public string Name { get; set; }
    //new code
    public virtual ICollection<Product> Products{ get; set; }
}

Then your since now the controller takes in a Category as Model (instead of a Product):

foreach (var category in Model)
{
    <h3><u>@category.Name</u></h3>
    <div>
        <ul>    
            @foreach (var product in Model.Products)
            {
                // cut for brevity, need to add back more code from original
                <li>@product.Title</li>
            }
        </ul>
    </div>
}

UPDATED: Add ToList() to the controller return statement.

How to check if a string array contains one string in JavaScript?

You can use the indexOfmethod and "extend" the Array class with the method contains like this:

Array.prototype.contains = function(element){
    return this.indexOf(element) > -1;
};

with the following results:

["A", "B", "C"].contains("A") equals true

["A", "B", "C"].contains("D") equals false

Error: "Could Not Find Installable ISAM"

I have just encountered a very similar problem.

Like you, my connection string appeared correct--and indeed, exactly the same connection string was working in other scenarios.

The problem turned out to be a lack of resources. 19 times out of 20, I would see the "Could not find installable ISAM," but once or twice (without any code changes at all), it would yield "Out of memory" instead.

Rebooting the machine "solved" the problem (for now...?). This happened using Jet version 4.0.9505.0 on Windows XP.

jQuery AJAX single file upload

A. Grab file data from the file field

The first thing to do is bind a function to the change event on your file field and a function for grabbing the file data:

// Variable to store your files
var files;

// Add events
$('input[type=file]').on('change', prepareUpload);

// Grab the files and set them to our variable
function prepareUpload(event)
{
  files = event.target.files;
}

This saves the file data to a file variable for later use.

B. Handle the file upload on submit

When the form is submitted you need to handle the file upload in its own AJAX request. Add the following binding and function:

$('form').on('submit', uploadFiles);

// Catch the form submit and upload the files
function uploadFiles(event)
{
  event.stopPropagation(); // Stop stuff happening
    event.preventDefault(); // Totally stop stuff happening

// START A LOADING SPINNER HERE

// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
    data.append(key, value);
});

$.ajax({
    url: 'submit.php?files',
    type: 'POST',
    data: data,
    cache: false,
    dataType: 'json',
    processData: false, // Don't process the files
    contentType: false, // Set content type to false as jQuery will tell the server its a query string request
    success: function(data, textStatus, jqXHR)
    {
        if(typeof data.error === 'undefined')
        {
            // Success so call function to process the form
            submitForm(event, data);
        }
        else
        {
            // Handle errors here
            console.log('ERRORS: ' + data.error);
        }
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
        // Handle errors here
        console.log('ERRORS: ' + textStatus);
        // STOP LOADING SPINNER
    }
});
}

What this function does is create a new formData object and appends each file to it. It then passes that data as a request to the server. 2 attributes need to be set to false:

  • processData - Because jQuery will convert the files arrays into strings and the server can't pick it up.
  • contentType - Set this to false because jQuery defaults to application/x-www-form-urlencoded and doesn't send the files. Also setting it to multipart/form-data doesn't seem to work either.

C. Upload the files

Quick and dirty php script to upload the files and pass back some info:

<?php // You need to add server side validation and better error handling here

$data = array();

if(isset($_GET['files']))
{  
$error = false;
$files = array();

$uploaddir = './uploads/';
foreach($_FILES as $file)
{
    if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
    {
        $files[] = $uploaddir .$file['name'];
    }
    else
    {
        $error = true;
    }
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
    $data = array('success' => 'Form was submitted', 'formData' => $_POST);
}

echo json_encode($data);

?>

IMP: Don't use this, write your own.

D. Handle the form submit

The success method of the upload function passes the data sent back from the server to the submit function. You can then pass that to the server as part of your post:

function submitForm(event, data)
{
  // Create a jQuery object from the form
$form = $(event.target);

// Serialize the form data
var formData = $form.serialize();

// You should sterilise the file names
$.each(data.files, function(key, value)
{
    formData = formData + '&filenames[]=' + value;
});

$.ajax({
    url: 'submit.php',
    type: 'POST',
    data: formData,
    cache: false,
    dataType: 'json',
    success: function(data, textStatus, jqXHR)
    {
        if(typeof data.error === 'undefined')
        {
            // Success so call function to process the form
            console.log('SUCCESS: ' + data.success);
        }
        else
        {
            // Handle errors here
            console.log('ERRORS: ' + data.error);
        }
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
        // Handle errors here
        console.log('ERRORS: ' + textStatus);
    },
    complete: function()
    {
        // STOP LOADING SPINNER
    }
});
}

Final note

This script is an example only, you'll need to handle both server and client side validation and some way to notify users that the file upload is happening. I made a project for it on Github if you want to see it working.

Referenced From

Get last field using awk substr

You can also use:

    sed -n 's/.*\/\([^\/]\{1,\}\)$/\1/p'

or

    sed -n 's/.*\/\([^\/]*\)$/\1/p'

How to find text in a column and saving the row number where it is first found - Excel VBA

I'm not really familiar with all those parameters of the Find method; but upon shortening it, the following is working for me:

With WB.Sheets("ECM Overview")
    Set FindRow = .Range("A:A").Find(What:="ProjTemp", LookIn:=xlValues)
End With

And if you solely need the row number, you can use this after:

Dim FindRowNumber As Long
.....
FindRowNumber = FindRow.Row

Parsing JSON from XmlHttpRequest.responseJSON

You can simply set xhr.responseType = 'json';

_x000D_
_x000D_
const xhr = new XMLHttpRequest();_x000D_
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1');_x000D_
xhr.responseType = 'json';_x000D_
xhr.onload = function(e) {_x000D_
  if (this.status == 200) {_x000D_
    console.log('response', this.response); // JSON response  _x000D_
  }_x000D_
};_x000D_
xhr.send();_x000D_
  
_x000D_
_x000D_
_x000D_

Documentation for responseType

How to read multiple Integer values from a single line of input in Java?

Using BufferedReader -

StringTokenizer st = new StringTokenizer(buf.readLine());

while(st.hasMoreTokens())
{
  arr[i++] = Integer.parseInt(st.nextToken());
}

Export database schema into SQL file

enter image description here

In the picture you can see. In the set script options, choose the last option: Types of data to script you click at the right side and you choose what you want. This is the option you should choose to export a schema and data

Bootstrap footer at the bottom of the page

In my case for Bootstrap4:

<body class="d-flex flex-column min-vh-100">
    <div class="wrapper flex-grow-1"></div>
    <footer></footer>
</body>

Entity Framework - Linq query with order by and group by

Try moving the order by after group by:

var groupByReference = (from m in context.Measurements
                        group m by new { m.Reference } into g
                        order by g.Avg(i => i.CreationTime)
                        select g).Take(numOfEntries).ToList();

java : convert float to String and String to float

Float to string - String.valueOf()

float amount=100.00f;
String strAmount=String.valueOf(amount);
// or  Float.toString(float)

String to Float - Float.parseFloat()

String strAmount="100.20";
float amount=Float.parseFloat(strAmount)
// or  Float.valueOf(string)

Decode Base64 data in Java

As an alternative to sun.misc.BASE64Decoder or non-core libraries, look at javax.mail.internet.MimeUtility.decode().

public static byte[] encode(byte[] b) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    OutputStream b64os = MimeUtility.encode(baos, "base64");
    b64os.write(b);
    b64os.close();
    return baos.toByteArray();
}
public static byte[] decode(byte[] b) throws Exception {
    ByteArrayInputStream bais = new ByteArrayInputStream(b);
    InputStream b64is = MimeUtility.decode(bais, "base64");
    byte[] tmp = new byte[b.length];
    int n = b64is.read(tmp);
    byte[] res = new byte[n];
    System.arraycopy(tmp, 0, res, 0, n);
    return res;
}

Link with full code: Encode/Decode to/from Base64

What is the difference between synchronous and asynchronous programming (in node.js)

The function makes the second one asynchronous.

The first one forces the program to wait for each line to finish it's run before the next one can continue. The second one allows each line to run together (and independently) at once.

Languages and frameworks (js, node.js) that allow asynchronous or concurrency is great for things that require real time transmission (eg. chat, stock applications).

Can you Run Xcode in Linux?

Nobody suggested Vagrant yet, so here it is, Vagrant box for OSX

vagrant init https://vagrant-osx.nyc3.digitaloceanspaces.com/osx-sierra-0.3.1.box
vagrant up

and you have a MACOS virtual machine. But according to Apple's EULA, you still need to run it on MacOS hardware :D But anywhere, here's one to all of you geeks who wiped MacOS and installed Ubuntu :D

Unfortunately, you can't run the editors from inside using SSH X-forwarding option.

SQL WHERE condition is not equal to?

I was just solving this problem. If you use <> or is not in on a variable, that is null, it will result in false. So instead of <> 1, you must check it like this:

 AND (isdelete is NULL or isdelete = 0)

How to run Pip commands from CMD

In my case I was trying to install Flask. I wanted to run pip install Flask command. But when I open command prompt it I goes to C:\Users[user]>. If you give here it will say pip is not recognized. I did below steps

On your desktop right click Computer and select Properties

Select Advanced Systems Settings

In popup which you see select Advanced tab and then click Environment Variables

In popup double click PATH and from popup copy variable value for variable name PATH and paste the variable value in notepad or so and look for an entry for Python.

In my case it was C:\Users\[user]\AppData\Local\Programs\Python\Python36-32

Now in my command prompt i moved to above location and gave pip install Flask

enter image description here

How can I access "static" class variables within class methods in Python?

bar is your static variable and you can access it using Foo.bar.

Basically, you need to qualify your static variable with Class name.

How do I correct "Commit Failed. File xxx is out of date. xxx path not found."

I know this is an old post, but this problem still occurs fairly frequently. The simplest way I've found to resolve it is to rename/delete the .svn/all-wcprops file in the affected folder, then run an update and commit.

What is the difference between & and && in Java?

With booleans, there is no output difference between the two. You can swap && and & or || and | and it will never change the result of your expression.

The difference lies behind the scene where the information is being processed. When you right an expression "(a != 0) & ( b != 0)" for a= 0 and b = 1, The following happens:

left side: a != 0 --> false
right side: b 1= 0 --> true
left side and right side are both true? --> false
expression returns false

When you write an expression (a != 0) && ( b != 0) when a= 0 and b = 1, the following happens:

a != 0 -->false
expression returns false

Less steps, less processing, better coding, especially when doing many boolean expression or complicated arguments.

Remove empty lines in a text file via grep

Simplest Answer -----------------------------------------

[root@node1 ~]# cat /etc/sudoers | grep -v -e ^# -e ^$
Defaults   !visiblepw
Defaults    always_set_home
Defaults    match_group_by_gid
Defaults    always_query_group_plugin
Defaults    env_reset
Defaults    env_keep =  "COLORS DISPLAY HOSTNAME HISTSIZE KDEDIR LS_COLORS"
Defaults    env_keep += "MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE"
Defaults    env_keep += "LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES"
Defaults    env_keep += "LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE"
Defaults    env_keep += "LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY"
Defaults    secure_path = /sbin:/bin:/usr/sbin:/usr/bin
root    ALL=(ALL)       ALL
%wheel  ALL=(ALL)       ALL
[root@node1 ~]#

How to read file with space separated values in pandas

If you can't get text parsing to work using the accepted answer (e.g if your text file contains non uniform rows) then it's worth trying with Python's csv library - here's an example using a user defined Dialect:

 import csv

 csv.register_dialect('skip_space', skipinitialspace=True)
 with open(my_file, 'r') as f:
      reader=csv.reader(f , delimiter=' ', dialect='skip_space')
      for item in reader:
          print(item)

How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"

u should add a theme to ur all activities (u should add theme for all application in ur <application> in ur manifest) but if u have set different theme to ur activity u can use :

 android:theme="@style/Theme.AppCompat"

or each kind of AppCompat theme!

MySQL's now() +1 day

You can use:

NOW() + INTERVAL 1 DAY

If you are only interested in the date, not the date and time then you can use CURDATE instead of NOW:

CURDATE() + INTERVAL 1 DAY

1064 error in CREATE TABLE ... TYPE=MYISAM

Try the below query

CREATE TABLE card_types (
  card_type_id int(11) NOT NULL auto_increment,
  name varchar(50) NOT NULL default '',
  PRIMARY KEY  (card_type_id),
) ENGINE = MyISAM ;

sql server Get the FULL month name from a date

If you are using SQL Server 2012 or later, you can use:

SELECT FORMAT(MyDate, 'MMMM dd yyyy')

You can view the documentation for more information on the format.

Epoch vs Iteration when training neural networks

1.Epoch is 1 complete cycle where Neural network has seen all he data.
2. One might have say 100,000 images to train the model, however memory space might not be sufficient to process all the images at once, hence we split training the model on smaller chunks of data called batches. e.g. batch size is 100.
3. We need to cover all the images using multiple batches. So we will need 1000 iterations to cover all the 100,000 images. (100 batch size * 1000 iterations)
4. Once Neural Network looks at entire data it is called 1 Epoch (Point 1). One might need multiple epochs to train the model. (let us say 10 epochs).

How to configure heroku application DNS to Godaddy Domain?

Yes, many changes at Heroku. If you're using a Heroku dyno for your webserver, you have to find way to alias from one DNS name to another DNS name (since each Heroku DNS endpoint may resolve to many IP addrs to dynamically adjust to request loads).

A CNAME record is for aliasing www.example.com -> www.example.com.herokudns.com.

You can't use CNAME for a naked domain (@), i.e. example.com (unless you find a name server that can do CNAME Flattening - which is what I did).

But really the easiest solution, that can pretty much be taken care of all in your GoDaddy account, is to create a CNAME record that does this: www.example.com -> www.example.com.herokudns.com.

And then create a permanent 301 redirect from example.com to www.example.com.

This requires only one heroku custom domain name configured in your heroku app settings: www.example.com.herokudns.com. @Jonathan Roy talks about this (above) but provides a bad link.

Is there a no-duplicate List implementation out there?

So here's what I did eventually. I hope this helps someone else.

class NoDuplicatesList<E> extends LinkedList<E> {
    @Override
    public boolean add(E e) {
        if (this.contains(e)) {
            return false;
        }
        else {
            return super.add(e);
        }
    }

    @Override
    public boolean addAll(Collection<? extends E> collection) {
        Collection<E> copy = new LinkedList<E>(collection);
        copy.removeAll(this);
        return super.addAll(copy);
    }

    @Override
    public boolean addAll(int index, Collection<? extends E> collection) {
        Collection<E> copy = new LinkedList<E>(collection);
        copy.removeAll(this);
        return super.addAll(index, copy);
    }

    @Override
    public void add(int index, E element) {
        if (this.contains(element)) {
            return;
        }
        else {
            super.add(index, element);
        }
    }
}   

How do I choose grid and block dimensions for CUDA kernels?

The answers above point out how the block size can impact performance and suggest a common heuristic for its choice based on occupancy maximization. Without wanting to provide the criterion to choose the block size, it would be worth mentioning that CUDA 6.5 (now in Release Candidate version) includes several new runtime functions to aid in occupancy calculations and launch configuration, see

CUDA Pro Tip: Occupancy API Simplifies Launch Configuration

One of the useful functions is cudaOccupancyMaxPotentialBlockSize which heuristically calculates a block size that achieves the maximum occupancy. The values provided by that function could be then used as the starting point of a manual optimization of the launch parameters. Below is a little example.

#include <stdio.h>

/************************/
/* TEST KERNEL FUNCTION */
/************************/
__global__ void MyKernel(int *a, int *b, int *c, int N) 
{ 
    int idx = threadIdx.x + blockIdx.x * blockDim.x; 

    if (idx < N) { c[idx] = a[idx] + b[idx]; } 
} 

/********/
/* MAIN */
/********/
void main() 
{ 
    const int N = 1000000;

    int blockSize;      // The launch configurator returned block size 
    int minGridSize;    // The minimum grid size needed to achieve the maximum occupancy for a full device launch 
    int gridSize;       // The actual grid size needed, based on input size 

    int* h_vec1 = (int*) malloc(N*sizeof(int));
    int* h_vec2 = (int*) malloc(N*sizeof(int));
    int* h_vec3 = (int*) malloc(N*sizeof(int));
    int* h_vec4 = (int*) malloc(N*sizeof(int));

    int* d_vec1; cudaMalloc((void**)&d_vec1, N*sizeof(int));
    int* d_vec2; cudaMalloc((void**)&d_vec2, N*sizeof(int));
    int* d_vec3; cudaMalloc((void**)&d_vec3, N*sizeof(int));

    for (int i=0; i<N; i++) {
        h_vec1[i] = 10;
        h_vec2[i] = 20;
        h_vec4[i] = h_vec1[i] + h_vec2[i];
    }

    cudaMemcpy(d_vec1, h_vec1, N*sizeof(int), cudaMemcpyHostToDevice);
    cudaMemcpy(d_vec2, h_vec2, N*sizeof(int), cudaMemcpyHostToDevice);

    float time;
    cudaEvent_t start, stop;
    cudaEventCreate(&start);
    cudaEventCreate(&stop);
    cudaEventRecord(start, 0);

    cudaOccupancyMaxPotentialBlockSize(&minGridSize, &blockSize, MyKernel, 0, N); 

    // Round up according to array size 
    gridSize = (N + blockSize - 1) / blockSize; 

    cudaEventRecord(stop, 0);
    cudaEventSynchronize(stop);
    cudaEventElapsedTime(&time, start, stop);
    printf("Occupancy calculator elapsed time:  %3.3f ms \n", time);

    cudaEventRecord(start, 0);

    MyKernel<<<gridSize, blockSize>>>(d_vec1, d_vec2, d_vec3, N); 

    cudaEventRecord(stop, 0);
    cudaEventSynchronize(stop);
    cudaEventElapsedTime(&time, start, stop);
    printf("Kernel elapsed time:  %3.3f ms \n", time);

    printf("Blocksize %i\n", blockSize);

    cudaMemcpy(h_vec3, d_vec3, N*sizeof(int), cudaMemcpyDeviceToHost);

    for (int i=0; i<N; i++) {
        if (h_vec3[i] != h_vec4[i]) { printf("Error at i = %i! Host = %i; Device = %i\n", i, h_vec4[i], h_vec3[i]); return; };
    }

    printf("Test passed\n");

}

EDIT

The cudaOccupancyMaxPotentialBlockSize is defined in the cuda_runtime.h file and is defined as follows:

template<class T>
__inline__ __host__ CUDART_DEVICE cudaError_t cudaOccupancyMaxPotentialBlockSize(
    int    *minGridSize,
    int    *blockSize,
    T       func,
    size_t  dynamicSMemSize = 0,
    int     blockSizeLimit = 0)
{
    return cudaOccupancyMaxPotentialBlockSizeVariableSMem(minGridSize, blockSize, func, __cudaOccupancyB2DHelper(dynamicSMemSize), blockSizeLimit);
}

The meanings for the parameters is the following

minGridSize     = Suggested min grid size to achieve a full machine launch.
blockSize       = Suggested block size to achieve maximum occupancy.
func            = Kernel function.
dynamicSMemSize = Size of dynamically allocated shared memory. Of course, it is known at runtime before any kernel launch. The size of the statically allocated shared memory is not needed as it is inferred by the properties of func.
blockSizeLimit  = Maximum size for each block. In the case of 1D kernels, it can coincide with the number of input elements.

Note that, as of CUDA 6.5, one needs to compute one's own 2D/3D block dimensions from the 1D block size suggested by the API.

Note also that the CUDA driver API contains functionally equivalent APIs for occupancy calculation, so it is possible to use cuOccupancyMaxPotentialBlockSize in driver API code in the same way shown for the runtime API in the example above.

compare two files in UNIX

Most easy way: sort files with sort(1) and then use diff(1).