Programs & Examples On #Decimal

Decimal is the name for our common base-ten numeral system. It may also refer to non-integer values expressed with a decimal point.

Format decimal for percentage values?

This code may help you:

double d = double.Parse(input_value);
string output= d.ToString("F2", CultureInfo.InvariantCulture) + "%";

Converting double to string with N decimals, dot as decimal separator, and no thousand separator

It's really easy to specify your own decimal separator. Just took me about 2 hours to figure it out :D. You see that you were using the current ou other culture that you specify right? Well, the only thing the parser needs is an IFormatProvider. If you give it the CultureInfo.CurrentCulture.NumberFormat as a formatter, it will format the double according to your current culture's NumberDecimalSeparator. What I did was just to create a new instance of the NumberFormatInfo class and set it's NumberDecimalSeparator property to whichever separator string I wanted. Complete code below:

double value = 2.3d;
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = "-";
string x = value.ToString(nfi);

The result? "2-3"

Python Decimals format

If you have Python 2.6 or newer, use format:

'{0:.3g}'.format(num)

For Python 2.5 or older:

'%.3g'%(num)

Explanation:

{0}tells format to print the first argument -- in this case, num.

Everything after the colon (:) specifies the format_spec.

.3 sets the precision to 3.

g removes insignificant zeros. See http://en.wikipedia.org/wiki/Printf#fprintf

For example:

tests=[(1.00, '1'),
       (1.2, '1.2'),
       (1.23, '1.23'),
       (1.234, '1.23'),
       (1.2345, '1.23')]

for num, answer in tests:
    result = '{0:.3g}'.format(num)
    if result != answer:
        print('Error: {0} --> {1} != {2}'.format(num, result, answer))
        exit()
    else:
        print('{0} --> {1}'.format(num,result))

yields

1.0 --> 1
1.2 --> 1.2
1.23 --> 1.23
1.234 --> 1.23
1.2345 --> 1.23

Using Python 3.6 or newer, you could use f-strings:

In [40]: num = 1.234; f'{num:.3g}'
Out[40]: '1.23'

Regular expression for decimal number

As I tussled with this, TryParse in 3.5 does have NumberStyles: The following code should also do the trick without Regex to ignore thousands seperator.

double.TryParse(length, NumberStyles.AllowDecimalPoint,CultureInfo.CurrentUICulture, out lengthD))

Not relevant to the original question asked but confirming that TryParse() indeed is a good option.

Convert a number to 2 decimal places in Java

Try

DecimalFormat df = new DecimalFormat("#,##0.00");

How can I format decimal property to currency?

Try this;

  string.Format(new CultureInfo("en-SG", false), "{0:c0}", 123423.083234);

It will convert 123423.083234 to $1,23,423 format.

Java decimal formatting using String.format?

Here is a small code snippet that does the job:

double a = 34.51234;

NumberFormat df = DecimalFormat.getInstance();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(4);
df.setRoundingMode(RoundingMode.DOWN);

System.out.println(df.format(a));

Double decimal formatting in Java

You can do it as follows:

double d = 4.0;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));

Force decimal point instead of comma in HTML5 number input (client-side)

Use lang attribut on the input. Locale on my web app fr_FR, lang="en_EN" on the input number and i can use indifferently a comma or a dot. Firefox always display a dot, Chrome display a comma. But both separtor are valid.

C++: Converting Hexadecimal to Decimal

I use this:

template <typename T>
bool fromHex(const std::string& hexValue, T& result)
{
    std::stringstream ss;
    ss << std::hex << hexValue;
    ss >> result;

    return !ss.fail();
}

range() for floats

You can either use:

[x / 10.0 for x in range(5, 50, 15)]

or use lambda / map:

map(lambda x: x/10.0, range(5, 50, 15))

Decimal to Hexadecimal Converter in Java

Here's mine

public static String dec2Hex(int num)
{
    String hex = "";

    while (num != 0)
    {
        if (num % 16 < 10)
            hex = Integer.toString(num % 16) + hex;
        else
            hex = (char)((num % 16)+55) + hex;
        num = num / 16;
    }

    return hex;
}

convert a JavaScript string variable to decimal/money

var formatter = new Intl.NumberFormat("ru", {
  style: "currency",
  currency: "GBP"
});

alert( formatter.format(1234.5) ); // 1 234,5 £

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat

Decimal precision and scale in EF Code First

Actual for EntityFrameworkCore 3.1.3:

some solution in OnModelCreating:

var fixDecimalDatas = new List<Tuple<Type, Type, string>>();
foreach (var entityType in builder.Model.GetEntityTypes())
{
    foreach (var property in entityType.GetProperties())
    {
        if (Type.GetTypeCode(property.ClrType) == TypeCode.Decimal)
        {
            fixDecimalDatas.Add(new Tuple<Type, Type, string>(entityType.ClrType, property.ClrType, property.GetColumnName()));
        }
    }
}

foreach (var item in fixDecimalDatas)
{
    builder.Entity(item.Item1).Property(item.Item2, item.Item3).HasColumnType("decimal(18,4)");
}

//custom decimal nullable:
builder.Entity<SomePerfectEntity>().Property(x => x.IsBeautiful).HasColumnType("decimal(18,4)");

Java String remove all non numeric characters

With guava:

String input = "abx123.5";
String result = CharMatcher.inRange('0', '9').or(CharMatcher.is('.')).retainFrom(input);

see http://code.google.com/p/guava-libraries/wiki/StringsExplained

Python: Converting string into decimal number

You will need to use strip() because of the extra bits in the strings.

A2 = [float(x.strip('"')) for x in A1]

How do you round a number to two decimal places in C#?

Wikipedia has a nice page on rounding in general.

All .NET (managed) languages can use any of the common language run time's (the CLR) rounding mechanisms. For example, the Math.Round() (as mentioned above) method allows the developer to specify the type of rounding (Round-to-even or Away-from-zero). The Convert.ToInt32() method and its variations use round-to-even. The Ceiling() and Floor() methods are related.

You can round with custom numeric formatting as well.

Note that Decimal.Round() uses a different method than Math.Round();

Here is a useful post on the banker's rounding algorithm. See one of Raymond's humorous posts here about rounding...

Integer to hex string in C++

Just print it as an hexadecimal number:

int i = /* ... */;
std::cout << std::hex << i;

Truncate/round whole number in JavaScript?

Math.trunc() function removes all the fractional digits.

For positive number it behaves exactly the same as Math.floor():

console.log(Math.trunc(89.13349)); // output is 89

For negative numbers it behaves same as Math.ceil():

console.log(Math.trunc(-89.13349)); //output is -89

How do I convert hex to decimal in Python?

You could use a literal eval:

>>> ast.literal_eval('0xdeadbeef')
3735928559

Or just specify the base as argument to int:

>>> int('deadbeef', 16)
3735928559

A trick that is not well known, if you specify the base 0 to int, then Python will attempt to determine the base from the string prefix:

>>> int("0xff", 0)
255
>>> int("0o644", 0)
420
>>> int("0b100", 0)
4
>>> int("100", 0)
100

Convert decimal to binary in python

For the sake of completion: if you want to convert fixed point representation to its binary equivalent you can perform the following operations:

  1. Get the integer and fractional part.

    from decimal import *
    a = Decimal(3.625)
    a_split = (int(a//1),a%1)
    
  2. Convert the fractional part in its binary representation. To achieve this multiply successively by 2.

    fr = a_split[1]
    str(int(fr*2)) + str(int(2*(fr*2)%1)) + ...
    

You can read the explanation here.

percentage of two int?

One of them has to be a float going in. One possible way of ensuring that is:

float percent = (float) n/v * 100;

Otherwise, you're doing integer division, which truncates the numbers. Also, you should be using double unless there's a good reason for the float.

The next issue you'll run into is that some of your percentages might look like 24.9999999999999% instead of 25%. This is due to precision loss in floating point representation. You'll have to decide how to deal with that, too. Options include a DecimalFormat to "fix" the formatting or BigDecimal to represent exact values.

Two decimal places using printf( )

Use: "%.2f" or variations on that.

See the POSIX spec for an authoritative specification of the printf() format strings. Note that it separates POSIX extras from the core C99 specification. There are some C++ sites which show up in a Google search, but some at least have a dubious reputation, judging from comments seen elsewhere on SO.

Since you're coding in C++, you should probably be avoiding printf() and its relatives.

Check if number is decimal

Simplest solution is

if(is_float(2.3)){

 echo 'true';

}

Check if decimal value is null

Assuming you are reading from a data row, what you want is:

if ( !rdrSelect.IsNull(23) ) 
{ 
   //handle parsing
}

Limit to 2 decimal places with a simple pipe

Simple solution

{{ orderTotal | number : '1.2-2'}}

//output like this

// public orderTotal = 220.45892221

//   {{ orderTotal | number : '1.2-2'}} 

// final Output
//  220.45

Formatting a float to 2 decimal places

You can pass the format in to the ToString method, e.g.:

myFloatVariable.ToString("0.00"); //2dp Number

myFloatVariable.ToString("n2"); // 2dp Number

myFloatVariable.ToString("c2"); // 2dp currency

Standard Number Format Strings

Python: Remove division decimal

def division(a, b):
    return a / b if a % b else a // b

Convert string to decimal, keeping fractions

I think your problem is when displaying the decimal, not the contents of it.

If you try

string value = "1200.00";
decimal d = decimal.Parse(s);
string s = d.ToString();

s will contain the string "1200".

However if you change your code to this

string value = "1200.00";
decimal d = decimal.Parse(s);
string s = d.ToString("0.00");

s will contain the string "1200.00" as you want it to do.

EDIT

Seems I'm braindead early in the morning today. I added the Parse statements now. However even my first code will output "1200.00", even if I expected it to output "1200". Seems like I'm learning something each day, and in this case obviously something that is quite basic.

So disregard this a an proper answer. We will probably need more code to identify your problem in this case.

Python JSON serialize a Decimal object

For anybody that wants a quick solution here is how I removed Decimal from my queries in Django

total_development_cost_var = process_assumption_objects.values('total_development_cost').aggregate(sum_dev = Sum('total_development_cost', output_field=FloatField()))
total_development_cost_var = list(total_development_cost_var.values())
  • Step 1: use , output_field=FloatField() in you r query
  • Step 2: use list eg list(total_development_cost_var.values())

Hope it helps

How do I interpret precision and scale of a number in a database?

Numeric precision refers to the maximum number of digits that are present in the number.

ie 1234567.89 has a precision of 9

Numeric scale refers to the maximum number of decimal places

ie 123456.789 has a scale of 3

Thus the maximum allowed value for decimal(5,2) is 999.99

Float vs Decimal in ActiveRecord

In Rails 4.1.0, I have faced problem with saving latitude and longitude to MySql database. It can't save large fraction number with float data type. And I change the data type to decimal and working for me.

  def change
    change_column :cities, :latitude, :decimal, :precision => 15, :scale => 13
    change_column :cities, :longitude, :decimal, :precision => 15, :scale => 13
  end

CAST to DECIMAL in MySQL

MySQL casts to Decimal:

Cast bare integer to decimal:

select cast(9 as decimal(4,2));       //prints 9.00

Cast Integers 8/5 to decimal:

select cast(8/5 as decimal(11,4));    //prints 1.6000

Cast string to decimal:

select cast(".885" as decimal(11,3));   //prints 0.885

Cast two int variables into a decimal

mysql> select 5 into @myvar1;
Query OK, 1 row affected (0.00 sec)

mysql> select 8 into @myvar2;
Query OK, 1 row affected (0.00 sec)

mysql> select @myvar1/@myvar2;   //prints 0.6250

Cast decimal back to string:

select cast(1.552 as char(10));   //shows "1.552"

How to calculate difference in hours (decimal) between two dates in SQL Server?

DATEDIFF but note it returns an integer so if you need fractions of hours use something like this:-

CAST(DATEDIFF(ss, startDate, endDate) AS decimal(precision, scale)) / 3600

How to get numbers after decimal point?

>>> n=5.55
>>> if "." in str(n):
...     print "."+str(n).split(".")[-1]
...
.55

Rounding a variable to two decimal places C#

Use System.Math.Round to rounds a decimal value to a specified number of fractional digits.

var pay = 200 + bonus;
pay = System.Math.Round(pay, 2);
Console.WriteLine(pay);

MSDN References:

Converting Decimal to Binary Java

Here is the conversion of Decimal to Binary in three different ways

import java.util.Scanner;
public static Scanner scan = new Scanner(System.in);

    public static void conversionLogical(int ip){           ////////////My Method One 
        String str="";
        do{
            str=ip%2+str;
            ip=ip/2;

        }while(ip!=1);
        System.out.print(1+str);

    }
    public static void byMethod(int ip){                /////////////Online Method
        //Integer ii=new Integer(ip);
        System.out.print(Integer.toBinaryString(ip));
    }
    public static String recursion(int ip){             ////////////Using My Recursion

        if(ip==1)
            return "1";
        return (DecToBin.recursion(ip/2)+(ip%2));


    }

    public static void main(String[] args) {            ///Main Method

        int ip;         
        System.out.println("Enter Positive Integer");
        ip = scan.nextInt();

        System.out.print("\nResult 1 = ");  
        DecToBin.conversionLogical(ip);
        System.out.print("\nResult 2 = ");
        DecToBin.byMethod(ip);
        System.out.println("\nResult 3 = "+DecToBin.recursion(ip));
    }
}

How do I convert a decimal to an int in C#?

Use Convert.ToInt32 from mscorlib as in

decimal value = 3.14m;
int n = Convert.ToInt32(value);

See MSDN. You can also use Decimal.ToInt32. Again, see MSDN. Finally, you can do a direct cast as in

decimal value = 3.14m;
int n = (int) value;

which uses the explicit cast operator. See MSDN.

Convert a string to integer with decimal in Python

How about this?

>>> s = '23.45678'
>>> int(float(s))
23

Or...

>>> int(Decimal(s))
23

Or...

>>> int(s.split('.')[0])
23

I doubt it's going to get much simpler than that, I'm afraid. Just accept it and move on.

Remove useless zero digits from decimals in PHP

$value = preg_replace('~\.0+$~','',$value);

Python convert decimal to hex

To get a pure hex value this might be useful. It's based on Joe's answer:

def gethex(decimal):
    return hex(decimal)[2:]

C++ - Decimal to binary converting

You can use std::bitset to convert a number to its binary format.

Use the following code snippet:

std::string binary = std::bitset<8>(n).to_string();

I found this on stackoverflow itself. I am attaching the link.

Cast a Double Variable to Decimal

use default convertation class: Convert.ToDecimal(Double)

Find number of decimal places in decimal value regardless of culture

I used Joe's way to solve this issue :)

decimal argument = 123.456m;
int count = BitConverter.GetBytes(decimal.GetBits(argument)[3])[2];

How do I restrict a float value to only two places after the decimal point in C?

There isn't a way to round a float to another float because the rounded float may not be representable (a limitation of floating-point numbers). For instance, say you round 37.777779 to 37.78, but the nearest representable number is 37.781.

However, you can "round" a float by using a format string function.

How to round a number to n decimal places in Java

Here is a summary of what you can use if you want the result as String:

  1. DecimalFormat#setRoundingMode():

    DecimalFormat df = new DecimalFormat("#.#####");
    df.setRoundingMode(RoundingMode.HALF_UP);
    String str1 = df.format(0.912385)); // 0.91239
    
  2. BigDecimal#setScale()

    String str2 = new BigDecimal(0.912385)
        .setScale(5, BigDecimal.ROUND_HALF_UP)
        .toString();
    

Here is a suggestion of what libraries you can use if you want double as a result. I wouldn't recommend it for string conversion, though, as double may not be able to represent what you want exactly (see e.g. here):

  1. Precision from Apache Commons Math

    double rounded = Precision.round(0.912385, 5, BigDecimal.ROUND_HALF_UP);
    
  2. Functions from Colt

    double rounded = Functions.round(0.00001).apply(0.912385)
    
  3. Utils from Weka

    double rounded = Utils.roundDouble(0.912385, 5)
    

How to insert DECIMAL into MySQL database

MySql decimal types are a little bit more complicated than just left-of and right-of the decimal point.

The first argument is precision, which is the number of total digits. The second argument is scale which is the maximum number of digits to the right of the decimal point.

Thus, (4,2) can be anything from -99.99 to 99.99.

As for why you're getting 99.99 instead of the desired 3.80, the value you're inserting must be interpreted as larger than 99.99, so the max value is used. Maybe you could post the code that you are using to insert or update the table.

Edit

Corrected a misunderstanding of the usage of scale and precision, per http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html.

Difference between decimal, float and double in .NET?

The main difference between each of these is the precision.

float is a 32-bit number, double is a 64-bit number and decimal is a 128-bit number.

Python: Binary To Decimal Conversion

You can use int casting which allows the base specification.

int(b, 2)  # Convert a binary string to a decimal int.

Java and unlimited decimal places?

I believe that you are looking for the java.lang.BigDecimal class.

decimal vs double! - Which one should I use and when?

I think that the main difference beside bit width is that decimal has exponent base 10 and double has 2

http://software-product-development.blogspot.com/2008/07/net-double-vs-decimal.html

How to convert numbers between hexadecimal and decimal

class HexToDecimal
{
    static void Main()
    {
        while (true)
        {
            Console.Write("Enter digit number to convert: ");
            int n = int.Parse(Console.ReadLine()); // set hexadecimal digit number  
            Console.Write("Enter hexadecimal number: ");
            string str = Console.ReadLine();
            str.Reverse();

            char[] ch = str.ToCharArray();
            int[] intarray = new int[n];

            decimal decimalval = 0;

            for (int i = ch.Length - 1; i >= 0; i--)
            {
                if (ch[i] == '0')
                    intarray[i] = 0;
                if (ch[i] == '1')
                    intarray[i] = 1;
                if (ch[i] == '2')
                    intarray[i] = 2;
                if (ch[i] == '3')
                    intarray[i] = 3;
                if (ch[i] == '4')
                    intarray[i] = 4;
                if (ch[i] == '5')
                    intarray[i] = 5;
                if (ch[i] == '6')
                    intarray[i] = 6;
                if (ch[i] == '7')
                    intarray[i] = 7;
                if (ch[i] == '8')
                    intarray[i] = 8;
                if (ch[i] == '9')
                    intarray[i] = 9;
                if (ch[i] == 'A')
                    intarray[i] = 10;
                if (ch[i] == 'B')
                    intarray[i] = 11;
                if (ch[i] == 'C')
                    intarray[i] = 12;
                if (ch[i] == 'D')
                    intarray[i] = 13;
                if (ch[i] == 'E')
                    intarray[i] = 14;
                if (ch[i] == 'F')
                    intarray[i] = 15;

                decimalval += intarray[i] * (decimal)Math.Pow(16, ch.Length - 1 - i);

            }

            Console.WriteLine(decimalval);
        }

    }

}

Split an integer into digits to compute an ISBN checksum

On Older versions of Python...

map(int,str(123))

On New Version 3k

list(map(int,str(123)))

Write a number with two decimal places SQL Server

Generally you can define the precision of a number in SQL by defining it with parameters. For most cases this will be NUMERIC(10,2) or Decimal(10,2) - will define a column as a Number with 10 total digits with a precision of 2 (decimal places).

Edited for clarity

Using Math.round to round to one decimal place?

A neat alternative that is much more readable in my opinion, however, arguably a tad less efficient due to the conversions between double and String:

double num = 540.512;
double sum = 1978.8;

// NOTE: This does take care of rounding
String str = String.format("%.1f", (num/sum) * 100.0); 

If you want the answer as a double, you could of course convert it back:

double ans = Double.parseDouble(str);

SQL Format as of Round off removing decimals

SELECT CONVERT(INT, 11.4)

RESULT: 11

SELECT CONVERT(INT, 11.6)

RESULT: 11

Int to Decimal Conversion - Insert decimal point at specified location

Simple math.

double result = ((double)number) / 100.0;

Although you may want to use decimal rather than double: decimal vs double! - Which one should I use and when?

How can I format a String number to have commas and round?

Here is the simplest way to get there:

String number = "10987655.876";
double result = Double.parseDouble(number);
System.out.println(String.format("%,.2f",result)); 

output: 10,987,655.88

Calculating bits required to store decimal number

For a binary number of n digits the maximum decimal value it can hold will be

2^n - 1, and 2^n is the total permutations that can be generated using these many digits.

Taking a case where you only want three digits, ie your case 1. We see that the requirements is,

2^n - 1 >= 999

Applying log to both sides,

log(2^n - 1) >= log(999)

log(2^n) - log(1) >= log(999)

n = 9.964 (approx).

Taking the ceil value of n since 9.964 can't be a valid number of digits, we get n = 10.

Get decimal portion of a number with JavaScript

A good option is to transform the number into a string and then split it.

// Decimal number
let number = 3.2;

// Convert it into a string
let string = number.toString();

// Split the dot
let array = string.split('.');

// Get both numbers
// The '+' sign transforms the string into a number again
let firstNumber  = +array[0]; // 3
let secondNumber = +array[1]; // 2

In one line of code

let [firstNumber, secondNumber] = [+number.toString().split('.')[0], +number.toString().split('.')[1]];

Remove trailing zeros from decimal in SQL Server

SELECT CONVERT(DOUBLE PRECISION, [ColumnName])

How do I display a decimal value to 2 decimal places?

decimalVar.ToString("F");

This will:

  • Round off to 2 decimal places eg. 23.456 ? 23.46
  • Ensure that there are always 2 decimal places eg. 23 ? 23.00; 12.5 ? 12.50

Ideal for displaying currency.

Check out the documentation on ToString("F") (thanks to Jon Schneider).

DOUBLE vs DECIMAL in MySQL

Actually it's quite different. DOUBLE causes rounding issues. And if you do something like 0.1 + 0.2 it gives you something like 0.30000000000000004. I personally would not trust financial data that uses floating point math. The impact may be small, but who knows. I would rather have what I know is reliable data than data that were approximated, especially when you are dealing with money values.

Remove trailing zeros

You can just set as:

decimal decNumber = 23.45600000m;
Console.WriteLine(decNumber.ToString("0.##"));

What does the M stand for in C# Decimal literal notation?

It means it's a decimal literal, as others have said. However, the origins are probably not those suggested elsewhere in this answer. From the C# Annotated Standard (the ECMA version, not the MS version):

The decimal suffix is M/m since D/d was already taken by double. Although it has been suggested that M stands for money, Peter Golde recalls that M was chosen simply as the next best letter in decimal.

A similar annotation mentions that early versions of C# included "Y" and "S" for byte and short literals respectively. They were dropped on the grounds of not being useful very often.

Best way to get whole number part of a Decimal number

   Public Function getWholeNumber(number As Decimal) As Integer
    Dim round = Math.Round(number, 0)
    If round > number Then
        Return round - 1
    Else
        Return round
    End If
End Function

What are the parameters for the number Pipe - Angular 2

The parameter has this syntax:

{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}

So your example of '1.2-2' means:

  • A minimum of 1 digit will be shown before decimal point
  • It will show at least 2 digits after decimal point
  • But not more than 2 digits

Hexadecimal To Decimal in Shell Script

Dealing with a very lightweight embedded version of busybox on Linux means many of the traditional commands are not available (bc, printf, dc, perl, python)

echo $((0x2f))
47

hexNum=2f
echo $((0x${hexNum}))
47

Credit to Peter Leung for this solution.

getch and arrow codes

By pressing one arrow key getch will push three values into the buffer:

  • '\033'
  • '['
  • 'A', 'B', 'C' or 'D'

So the code will be something like this:

if (getch() == '\033') { // if the first value is esc
    getch(); // skip the [
    switch(getch()) { // the real value
        case 'A':
            // code for arrow up
            break;
        case 'B':
            // code for arrow down
            break;
        case 'C':
            // code for arrow right
            break;
        case 'D':
            // code for arrow left
            break;
    }
}

How to extract the decimal part from a floating point number in C?

Try this:

int main() {
  double num = 23.345;
  int intpart = (int)num;
  double decpart = num - intpart;
  printf("Num = %f, intpart = %d, decpart = %f\n", num, intpart, decpart);
}

For me, it produces:

Num = 23.345000, intpart = 23, decpart = 0.345000

Which appears to be what you're asking for.

Format number to 2 decimal places

When formatting number to 2 decimal places you have two options TRUNCATE and ROUND. You are looking for TRUNCATE function.

Examples:

Without rounding:

TRUNCATE(0.166, 2)
-- will be evaluated to 0.16

TRUNCATE(0.164, 2)
-- will be evaluated to 0.16

docs: http://www.w3resource.com/mysql/mathematical-functions/mysql-truncate-function.php

With rounding:

ROUND(0.166, 2)
-- will be evaluated to 0.17

ROUND(0.164, 2)
-- will be evaluated to 0.16

docs: http://www.w3resource.com/mysql/mathematical-functions/mysql-round-function.php

String to decimal conversion: dot separation instead of comma

I ended up using this solution.

decimal weeklyWage;
decimal.TryParse(items[2],NumberStyles.Any, new NumberFormatInfo() { NumberDecimalSeparator = "."}, out weeklyWage);

How to store decimal values in SQL Server?

The settings for Decimal are its precision and scale or in normal language, how many digits can a number have and how many digits do you want to have to the right of the decimal point.

So if you put PI into a Decimal(18,0) it will be recorded as 3?

If you put PI into a Decimal(18,2) it will be recorded as 3.14?

If you put PI into Decimal(18,10) be recorded as 3.1415926535.

Sending a file over TCP sockets in Python

you may change your loop condition according to following code, when length of l is smaller than buffer size it means that it reached end of file

while (True):
    print "Receiving..."
    l = c.recv(1024)        
    f.write(l)
    if len(l) < 1024:
        break

How to use a SQL SELECT statement with Access VBA

If you wish to use the bound column value, you can simply refer to the combo:

sSQL = "SELECT * FROM MyTable WHERE ID = " & Me.MyCombo

You can also refer to the column property:

sSQL = "SELECT * FROM MyTable WHERE AText = '" & Me.MyCombo.Column(1) & "'"

Dim rs As DAO.Recordset     
Set rs = CurrentDB.OpenRecordset(sSQL)

strText = rs!AText
strText = rs.Fields(1)

In a textbox:

= DlookUp("AText","MyTable","ID=" & MyCombo)

*edited

ASP.net Repeater get current index, pointer, or counter

Add a label control to your Repeater's ItemTemplate. Handle OnItemCreated event.

ASPX

<asp:Repeater ID="rptr" runat="server" OnItemCreated="RepeaterItemCreated">
    <ItemTemplate>
        <div id="width:50%;height:30px;background:#0f0a0f;">
            <asp:Label ID="lblSr" runat="server" 
               style="width:30%;float:left;text-align:right;text-indent:-2px;" />
            <span 
               style="width:65%;float:right;text-align:left;text-indent:-2px;" >
            <%# Eval("Item") %>
            </span>
        </div>
    </ItemTemplate>
</asp:Repeater>

Code Behind:

    protected void RepeaterItemCreated(object sender, RepeaterItemEventArgs e)
    {
        Label l = e.Item.FindControl("lblSr") as Label;
        if (l != null)
            l.Text = e.Item.ItemIndex + 1+"";
    }

How to do a JUnit assert on a message in a logger

As for me you can simplify your test by using JUnit with Mockito. I propose following solution for it:

import org.apache.log4j.Appender;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.spi.LoggingEvent;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.Mockito.times;

@RunWith(MockitoJUnitRunner.class)
public class MyLogTest {
    private static final String FIRST_MESSAGE = "First message";
    private static final String SECOND_MESSAGE = "Second message";
    @Mock private Appender appender;
    @Captor private ArgumentCaptor<LoggingEvent> captor;
    @InjectMocks private MyLog;

    @Before
    public void setUp() {
        LogManager.getRootLogger().addAppender(appender);
    }

    @After
    public void tearDown() {
        LogManager.getRootLogger().removeAppender(appender);
    }

    @Test
    public void shouldLogExactlyTwoMessages() {
        testedClass.foo();

        then(appender).should(times(2)).doAppend(captor.capture());
        List<LoggingEvent> loggingEvents = captor.getAllValues();
        assertThat(loggingEvents).extracting("level", "renderedMessage").containsExactly(
                tuple(Level.INFO, FIRST_MESSAGE)
                tuple(Level.INFO, SECOND_MESSAGE)
        );
    }
}

That's why we have nice flexibility for tests with different message quantity

Set folder for classpath

If you are using Java 6 or higher you can use wildcards of this form:

java -classpath ".;c:\mylibs\*;c:\extlibs\*" MyApp

If you would like to add all subdirectories: lib\a\, lib\b\, lib\c\, there is no mechanism for this in except:

java -classpath ".;c:\lib\a\*;c:\lib\b\*;c:\lib\c\*" MyApp

There is nothing like lib\*\* or lib\** wildcard for the kind of job you want to be done.

How do I clone a Django model instance object and save it to the database?

To clone a model with multiple inheritance levels, i.e. >= 2, or ModelC below

class ModelA(models.Model):
    info1 = models.CharField(max_length=64)

class ModelB(ModelA):
    info2 = models.CharField(max_length=64)

class ModelC(ModelB):
    info3 = models.CharField(max_length=64)

Please refer the question here.

Shortcut key for commenting out lines of Python code in Spyder

On macOS:

Cmd + 1

On Windows, probably

Ctrl + (/) near right shift key

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.

Python: subplot within a loop: first panel appears in wrong position

Basically the same solution as provided by Rutger Kassies, but using a more pythonic syntax:

fig, axs = plt.subplots(2,5, figsize=(15, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)

data = np.arange(250, 260)

for ax, d in zip(axs.ravel(), data):
    ax.contourf(np.random.rand(10,10), 5, cmap=plt.cm.Oranges)
    ax.set_title(str(d))

How to display a list using ViewBag

In your view, you have to cast it back to the original type. Without the cast, it's just an object.

<td>@((ViewBag.data as ICollection<Person>).First().FirstName)</td>

ViewBag is a C# 4 dynamic type. Entities returned from it are also dynamic unless cast. However, extension methods like .First() and all the other Linq ones do not work with dynamics.

Edit - to address the comment:

If you want to display the whole list, it's as simple as this:

<ul>
    @foreach (var person in ViewBag.data)
    {
        <li>@person.FirstName</li>
    }
</ul>

Extension methods like .First() won't work, but this will.

Android - styling seek bar

check this tutorial very good

https://www.lvguowei.me/post/customize-android-seekbar-color/

simple :

<SeekBar
                android:id="@+id/seekBar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:max="100"
                android:maxHeight="3dp"
                android:minHeight="3dp"
                android:progressDrawable="@drawable/seekbar_style"
                android:thumbTint="@color/positive_color"/>

then a style file:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@android:id/background">
        <shape android:shape="rectangle" >
            <solid
                android:color="@color/positive_color" />
        </shape>
    </item>
    <item android:id="@android:id/progress">
        <clip>
            <shape android:shape="rectangle" >
                <solid
                    android:color="@color/positive_color" />
            </shape>
        </clip>
    </item>
</layer-list>

How to change the hosts file on android

adb shell
su
mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system

This assumes your /system is yaffs2 and that it's at /dev/block/mtdblock3 the easier/better way to do this on most Android phones is:

adb shell
su
mount -o remount,rw /system

Done. This just says remount /system read-write, you don't have to specify filesystem or mount location.

Could not connect to SMTP host: localhost, port: 25; nested exception is: java.net.ConnectException: Connection refused: connect

First you have to ensure that there is a SMTP server listening on port 25.

To look whether you have the service, you can try using TELNET client, such as:

C:\> telnet localhost 25

(telnet client by default is disabled on most recent versions of Windows, you have to add/enable the Windows component from Control Panel. In Linux/UNIX usually telnet client is there by default.

$ telnet localhost 25

If it waits for long then time out, that means you don't have the required SMTP service. If successfully connected you enter something and able to type something, the service is there.

If you don't have the service, you can use these:

  • A mock SMTP server that will mimic the behavior of actual SMTP server, as you are using Java, it is natural to suggest Dumbster fake SMTP server. This even can be made to work within JUnit tests (with setup/tear down/validation), or independently run as separate process for integration test.
  • If your host is Windows, you can try installing Mercury email server (also comes with WAMPP package from Apache Friends) on your local before running above code.
  • If your host is Linux or UNIX, try to enable the mail service such as Postfix,
  • Another full blown SMTP server in Java, such as Apache James mail server.

If you are sure that you already have the service, may be the SMTP requires additional security credentials. If you can tell me what SMTP server listening on port 25 I may be able to tell you more.

WhatsApp API (java/python)

This is the developers page of the Open WhatsApp official page: http://openwhatsapp.org/develop/

You can find a lot of information there about Yowsup.

Or, you can just go the the library's link (which I copied from the Open WhatsApp page anyway): https://github.com/tgalal/yowsup

Enjoy!

How to check for the type of a template parameter?

Use is_same:

#include <type_traits>

template <typename T>
void foo()
{
    if (std::is_same<T, animal>::value) { /* ... */ }  // optimizable...
}

Usually, that's a totally unworkable design, though, and you really want to specialize:

template <typename T> void foo() { /* generic implementation  */ }

template <> void foo<animal>()   { /* specific for T = animal */ }

Note also that it's unusual to have function templates with explicit (non-deduced) arguments. It's not unheard of, but often there are better approaches.

What is the default value for enum variable?

You can use this snippet :-D

using System;
using System.Reflection;

public static class EnumUtils
{
    public static T GetDefaultValue<T>()
        where T : struct, Enum
    {
        return (T)GetDefaultValue(typeof(T));
    }

    public static object GetDefaultValue(Type enumType)
    {
        var attribute = enumType.GetCustomAttribute<DefaultValueAttribute>(inherit: false);
        if (attribute != null)
            return attribute.Value;

        var innerType = enumType.GetEnumUnderlyingType();
        var zero = Activator.CreateInstance(innerType);
        if (enumType.IsEnumDefined(zero))
            return zero;

        var values = enumType.GetEnumValues();
        return values.GetValue(0);
    }
}

Example:

using System;

public enum Enum1
{
    Foo,
    Bar,
    Baz,
    Quux
}
public enum Enum2
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 0
}
public enum Enum3
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 4
}
[DefaultValue(Enum4.Bar)]
public enum Enum4
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 4
}

public static class Program 
{
    public static void Main() 
    {
        var defaultValue1 = EnumUtils.GetDefaultValue<Enum1>();
        Console.WriteLine(defaultValue1); // Foo

        var defaultValue2 = EnumUtils.GetDefaultValue<Enum2>();
        Console.WriteLine(defaultValue2); // Quux

        var defaultValue3 = EnumUtils.GetDefaultValue<Enum3>();
        Console.WriteLine(defaultValue3); // Foo

        var defaultValue4 = EnumUtils.GetDefaultValue<Enum4>();
        Console.WriteLine(defaultValue4); // Bar
    }
}

Naming returned columns in Pandas aggregate function?

such as this kind of dataframe, there are two levels of thecolumn name:

 shop_id  item_id   date_block_num item_cnt_day       
                                  target              
0   0       30          1            31               

we can use this code:

df.columns = [col[0] if col[-1]=='' else col[-1] for col in df.columns.values]

result is:

 shop_id  item_id   date_block_num target              
0   0       30          1            31 

Passing parameters to click() & bind() event in jquery?

An alternative for the bind() method.

Use the click() method, do something like this:

commentbtn.click({id: 10, name: "João"}, onClickCommentBtn);

function onClickCommentBtn(event)
{
  alert("Id=" + event.data.id + ", Name = " + event.data.name);
}

Or, if you prefer:

commentbtn.click({id: 10, name: "João"},  function (event) {
  alert("Id=" + event.data.id + ", Nome = " + event.data.name);
});

It will show an alert box with the following infos:

Id = 10, Name = João

How to increment a pointer address and pointer's value?

checked the program and the results are as,

p++;    // use it then move to next int position
++p;    // move to next int and then use it
++*p;   // increments the value by 1 then use it 
++(*p); // increments the value by 1 then use it
++*(p); // increments the value by 1 then use it
*p++;   // use the value of p then moves to next position
(*p)++; // use the value of p then increment the value
*(p)++; // use the value of p then moves to next position
*++p;   // moves to the next int location then use that value
*(++p); // moves to next location then use that value

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

use style instead like

<div style="display:none;"></div>

Git: copy all files in a directory from another branch

As you are not trying to move the files around in the tree, you should be able to just checkout the directory:

git checkout master -- dirname

How to add a new audio (not mixing) into a video using ffmpeg?

Code to add audio to video using ffmpeg.

If audio length is greater than video length it will cut the audio to video length. If you want full audio in video remove -shortest from the cmd.

String[] cmd = new String[]{"-i", selectedVideoPath,"-i",audiopath,"-map","1:a","-map","0:v","-codec","copy", ,outputFile.getPath()};

private void execFFmpegBinaryShortest(final String[] command) {



            final File outputFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/videoaudiomerger/"+"Vid"+"output"+i1+".mp4");




            String[] cmd = new String[]{"-i", selectedVideoPath,"-i",audiopath,"-map","1:a","-map","0:v","-codec","copy","-shortest",outputFile.getPath()};


            try {

                ffmpeg.execute(cmd, new ExecuteBinaryResponseHandler() {
                    @Override
                    public void onFailure(String s) {
                        System.out.println("on failure----"+s);
                    }

                    @Override
                    public void onSuccess(String s) {
                        System.out.println("on success-----"+s);
                    }

                    @Override
                    public void onProgress(String s) {
                        //Log.d(TAG, "Started command : ffmpeg "+command);
                        System.out.println("Started---"+s);

                    }

                    @Override
                    public void onStart() {


                        //Log.d(TAG, "Started command : ffmpeg " + command);
                        System.out.println("Start----");

                    }

                    @Override
                    public void onFinish() {
                        System.out.println("Finish-----");


                    }
                });
            } catch (FFmpegCommandAlreadyRunningException e) {
                // do nothing for now
                System.out.println("exceptio :::"+e.getMessage());
            }


        }

Disable button in WPF?

You could subscribe to the TextChanged event on the TextBox and if the text is empty set the Button to disabled. Or you could bind the Button.IsEnabled property to the TextBox.Text property and use a converter that returns true if there is any text and false otherwise.

Insert variable into Header Location PHP

We can also use this with the $_GET method

$employee_id = 'EMP-1234';

header('Location: employee.php?id='.$employee_id);

What command means "do nothing" in a conditional in Bash?

You can probably just use the true command:

if [ "$a" -ge 10 ]; then
    true
elif [ "$a" -le 5 ]; then
    echo "1"
else
    echo "2"
fi

An alternative, in your example case (but not necessarily everywhere) is to re-order your if/else:

if [ "$a" -le 5 ]; then
    echo "1"
elif [ "$a" -lt 10 ]; then
    echo "2"
fi

Upper memory limit?

No, there's no Python-specific limit on the memory usage of a Python application. I regularly work with Python applications that may use several gigabytes of memory. Most likely, your script actually uses more memory than available on the machine you're running on.

In that case, the solution is to rewrite the script to be more memory efficient, or to add more physical memory if the script is already optimized to minimize memory usage.

Edit:

Your script reads the entire contents of your files into memory at once (line = u.readlines()). Since you're processing files up to 20 GB in size, you're going to get memory errors with that approach unless you have huge amounts of memory in your machine.

A better approach would be to read the files one line at a time:

for u in files:
     for line in u: # This will iterate over each line in the file
         # Read values from the line, do necessary calculations

How can I get the "network" time, (from the "Automatic" setting called "Use network-provided values"), NOT the time on the phone?

This seemed to work for me:

LocationManager locMan = (LocationManager) activity.getSystemService(activity.LOCATION_SERVICE);
long networkTS = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).getTime();

Working on Android 2.2 API (Level 8)

Close virtual keyboard on button press

mMyTextView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            // hide virtual keyboard
            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(m_txtSearchText.getWindowToken(), 
                                      InputMethodManager.RESULT_UNCHANGED_SHOWN);
            return true;
        }
        return false;
    }
});

Accessing Imap in C#

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

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

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

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

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

Recommendations for a .NET component to access an email inbox

Compiling a java program into an executable

I would use GCJ (GNU Compiler for Java) in your situation. It's an AOT (ahead of time) compiler for Java, much like GCC is for C. Instead of interpreting code, or generating intermediate java code to be run at a later time by the Java VM, it generates machine code.

GCJ is available on almost any Linux system through its respective package manager (if available). After installation, the GCJ compiler should be added to the path so that it can be invoked through the terminal. If you're using Windows, you can download and install GCJ through Cygwin or MinGW.

I would strongly recommend, however, that you rewrite your source for another language that is meant to be compiled, such as C++. Java is meant to be a portable, interpreted language. Compiling it to machine code is completely against what the language was developed for.

How to Detect if I'm Compiling Code with a particular Visual Studio version?

This is a little old but should get you started:

//******************************************************************************
// Automated platform detection
//******************************************************************************

// _WIN32 is used by
// Visual C++
#ifdef _WIN32
#define __NT__
#endif

// Define __MAC__ platform indicator
#ifdef macintosh
#define __MAC__
#endif

// Define __OSX__ platform indicator
#ifdef __APPLE__
#define __OSX__
#endif

// Define __WIN16__ platform indicator 
#ifdef _Windows_
#ifndef __NT__
#define __WIN16__
#endif
#endif

// Define Windows CE platform indicator
#ifdef WIN32_PLATFORM_HPCPRO
#define __WINCE__
#endif

#if (_WIN32_WCE == 300) // for Pocket PC
#define __POCKETPC__
#define __WINCE__
//#if (_WIN32_WCE == 211) // for Palm-size PC 2.11 (Wyvern)
//#if (_WIN32_WCE == 201) // for Palm-size PC 2.01 (Gryphon)  
//#ifdef WIN32_PLATFORM_HPC2000 // for H/PC 2000 (Galileo)
#endif

Return the characters after Nth character in a string

Another formula option is to use REPLACE function to replace the first n characters with nothing, e.g. if n = 4

=REPLACE(A1,1,4,"")

Preferred way of loading resources in Java

I know it really late for another answer but I just wanted to share what helped me at the end. It will also load resources/files from the absolute path of the file system (not only the classpath's).

public class ResourceLoader {

    public static URL getResource(String resource) {
        final List<ClassLoader> classLoaders = new ArrayList<ClassLoader>();
        classLoaders.add(Thread.currentThread().getContextClassLoader());
        classLoaders.add(ResourceLoader.class.getClassLoader());

        for (ClassLoader classLoader : classLoaders) {
            final URL url = getResourceWith(classLoader, resource);
            if (url != null) {
                return url;
            }
        }

        final URL systemResource = ClassLoader.getSystemResource(resource);
        if (systemResource != null) {
            return systemResource;
        } else {
            try {
                return new File(resource).toURI().toURL();
            } catch (MalformedURLException e) {
                return null;
            }
        }
    }

    private static URL getResourceWith(ClassLoader classLoader, String resource) {
        if (classLoader != null) {
            return classLoader.getResource(resource);
        }
        return null;
    }

}

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

Use Conda instead of pip. It works perfectly

conda install PyAudio

How to add scroll bar to the Relative Layout?

The following code should do the trick:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<RelativeLayout
android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="638dp" >

<TextView
    android:id="@+id/textView1"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="64dp"
    android:text="Email" />

<TextView
    android:id="@+id/textView2"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="41dp"
    android:text="Password" />

<TextView
    android:id="@+id/textView3"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/textView2"
    android:layout_below="@+id/textView2"
    android:layout_marginTop="47dp"
    android:text="Confirm Password" />

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView1"
    android:layout_alignBottom="@+id/textView1"
    android:layout_alignParentRight="true"
    android:layout_toRightOf="@+id/textView4"
    android:inputType="textEmailAddress" >

    <requestFocus />
</EditText>

<EditText
    android:id="@+id/editText2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView2"
    android:layout_alignBottom="@+id/textView2"
    android:layout_alignLeft="@+id/editText1"
    android:layout_alignParentRight="true"
    android:inputType="textPassword" />

<EditText
    android:id="@+id/editText3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView3"
    android:layout_alignBottom="@+id/textView3"
    android:layout_alignLeft="@+id/editText2"
    android:layout_alignParentRight="true"
    android:inputType="textPassword" />


<TextView
    android:id="@+id/textView4"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/textView3"
    android:layout_marginTop="42dp"
    android:text="Date of Birth" />

<DatePicker
    android:id="@+id/datePicker1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/textView4" />

<TextView
    android:id="@+id/textView5"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/datePicker1"
    android:layout_marginTop="60dp"
    android:layout_toLeftOf="@+id/datePicker1"
    android:text="Gender" />

<RadioButton
    android:id="@+id/radioButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView5"
    android:layout_alignBottom="@+id/textView5"
    android:layout_alignLeft="@+id/editText3"
    android:layout_marginLeft="24dp"
    android:text="Male" />

<RadioButton
    android:id="@+id/radioButton2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/radioButton1"
    android:layout_below="@+id/radioButton1"
    android:layout_marginTop="14dp"
    android:text="Female" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="23dp"
    android:layout_toLeftOf="@+id/radioButton2"
    android:background="@drawable/rectbutton"
    android:text="Sign Up" />

html select only one checkbox in a group

The Code snippet below demonstrates a simple approach for selecting only one checkbox in a group.


_x000D_
_x000D_
  <!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
    <h3>Demonstration of Checkbox Toggle</h3>
    <p>
        <span><b>Letters:</b></span>
        A<input type="checkbox" name="A" >
        B<input type="checkbox" name="B" >
        C<input type="checkbox" name="C" >
        D<input type="checkbox" name="D" >
    </p>
    <p>
        <span><b>Numbers:</b></span>
        1<input type="checkbox" name="1" >
        2<input type="checkbox" name="2" >
        3<input type="checkbox" name="3" >
    </p>
     <p>
        <span><b>Birds:</b></span>
        Scarlet Ibis<input type="checkbox" name="Scarlet Ibis" >
        Cocrico <input type="checkbox" name="Cocrico" >
        hummingbird <input type="checkbox" name="hummingbird" >
    </p>
</body>

<script>
    $(function()
    {
        function toggle(choices,name) 
        {
            if(choices.includes(name))
            {
                for( i=0;i<choices.length;i++)
                {
                if(name !=choices[i])
                    $('input[name="' + choices[i] + '"]').not(this).prop('checked', false); 
                }
            }
        }
        $('input[type="checkbox"]').on('change', function() 
        {
            var letters = ["A","B","C","D"];
            var numbers = ["1", "2", "3"];
            var birds = ["Scarlet Ibis", "Cocrico", "hummingbird"];
            
            toggle(letters,this.name);
            toggle(numbers,this.name);
            toggle(birds,this.name);
        });

    });
</script>
</html>
_x000D_
_x000D_
_x000D_

Finding the length of an integer in C

You may use this -

(data_type)log10(variable_name)+1

ex:

len = (int)log10(number)+1;

jQuery - on change input text

This technique is working for me:

$('#myInputFieldId').bind('input',function(){ 
               alert("Hello");
    });

Note that according to this JQuery doc, "on" is recommended rather than bind in newer versions.

Requested bean is currently in creation: Is there an unresolvable circular reference?

In my case, I was defining a bean and autowiring it in the constructor of the same class file.

@SpringBootApplication
public class MyApplication {
    private MyBean myBean;

    public MyApplication(MyBean myBean) {
        this.myBean = myBean;
    }

    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

My solution was to move the bean definition to another class file.

@Configuration
public CustomConfig {
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

How to set IE11 Document mode to edge as default?

unchecked the "Automatically detect settings" in the Local Area Network Settings (found in "Internet Options" > Connections > LAN Settings.

Shell - How to find directory of some command?

~$ echo $PATH
/home/jack/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
~$ whereis lshw
lshw: /usr/bin/lshw /usr/share/man/man1/lshw.1.gz

Hide Signs that Meteor.js was Used

A Meteor app does not, by default, add any X-Powered-By headers to HTTP responses, as you might find in various PHP apps. The headers look like:

$ curl -I https://atmosphere.meteor.com  HTTP/1.1 200 OK content-type: text/html; charset=utf-8 date: Tue, 31 Dec 2013 23:12:25 GMT connection: keep-alive 

However, this doesn't mask that Meteor was used. Viewing the source of a Meteor app will look very distinctive.

<script type="text/javascript"> __meteor_runtime_config__ = {"meteorRelease":"0.6.3.1","ROOT_URL":"http://atmosphere.meteor.com","serverId":"62a4cf6a-3b28-f7b1-418f-3ddf038f84af","DDP_DEFAULT_CONNECTION_URL":"ddp+sockjs://ddp--****-atmosphere.meteor.com/sockjs"}; </script> 

If you're trying to avoid people being able to tell you are using Meteor even by viewing source, I don't think that's possible.

How can I generate random alphanumeric strings?

Question: Why should I waste my time using Enumerable.Range instead of typing in "ABCDEFGHJKLMNOPQRSTUVWXYZ0123456789"?

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

public class Test
{
    public static void Main()
    {
        var randomCharacters = GetRandomCharacters(8, true);
        Console.WriteLine(new string(randomCharacters.ToArray()));
    }

    private static List<char> getAvailableRandomCharacters(bool includeLowerCase)
    {
        var integers = Enumerable.Empty<int>();
        integers = integers.Concat(Enumerable.Range('A', 26));
        integers = integers.Concat(Enumerable.Range('0', 10));

        if ( includeLowerCase )
            integers = integers.Concat(Enumerable.Range('a', 26));

        return integers.Select(i => (char)i).ToList();
    }

    public static IEnumerable<char> GetRandomCharacters(int count, bool includeLowerCase)
    {
        var characters = getAvailableRandomCharacters(includeLowerCase);
        var random = new Random();
        var result = Enumerable.Range(0, count)
            .Select(_ => characters[random.Next(characters.Count)]);

        return result;
    }
}

Answer: Magic strings are BAD. Did ANYONE notice there was no "I" in my string at the top? My mother taught me not to use magic strings for this very reason...

n.b. 1: As many others like @dtb said, don't use System.Random if you need cryptographic security...

n.b. 2: This answer isn't the most efficient or shortest, but I wanted the space to separate the answer from the question. The purpose of my answer is more to warn against magic strings than to provide a fancy innovative answer.

Excel Macro : How can I get the timestamp in "yyyy-MM-dd hh:mm:ss" format?

this worked best for me:

        Cells(partcount + 5, "N").Value = Date + Time
        Cells(partcount + 5, "N").NumberFormat = "mm/dd/yy hh:mm:ss AM/PM"

How can I convert a std::string to int?

To convert from string representation to integer value, we can use std::stringstream.

if the value converted is out of range for integer data type, it returns INT_MIN or INT_MAX.

Also if the string value can’t be represented as an valid int data type, then 0 is returned.

#include 
#include 
#include 

int main() {

    std::string x = "50";
    int y;
    std::istringstream(x) >> y;
    std::cout << y << '\n';
    return 0;
}

Output: 50

As per the above output, we can see it converted from string numbers to integer number.

Source and more at string to int c++

How to format font style and color in echo

foreach($months as $key => $month){
  if(strpos($filename,$month)!==false){
        echo "<div style ='font:11px/21px Arial,tahoma,sans-serif;color:#ff0000'> Movie List for $key 2013</div>";
    }
}

How to run php files on my computer

You have to run a web server (e.g. Apache) and browse to your localhost, mostly likely on port 80.

What you really ought to do is install an all-in-one package like XAMPP, it bundles Apache, MySQL PHP, and Perl (if you were so inclined) as well as a few other tools that work with Apache and MySQL - plus it's cross platform (that's what the 'X' in 'XAMPP' stands for).

Once you install XAMPP (and there is an installer, so it shouldn't be hard) open up the control panel for XAMPP and then click the "Start" button next to Apache - note that on applications that require a database, you'll also need to start MySQL (and you'll be able to interface with it through phpMyAdmin). Once you've started Apache, you can browse to http://localhost.

Again, regardless of whether or not you choose XAMPP (which I would recommend), you should just have to start Apache.

How to split a string content into an array of strings in PowerShell?

Remove the spaces from the original string and split on semicolon

$address = "[email protected]; [email protected]; [email protected]"
$addresses = $address.replace(' ','').split(';')

Or all in one line:

$addresses = "[email protected]; [email protected]; [email protected]".replace(' ','').split(';')

$addresses becomes:

@('[email protected]','[email protected]','[email protected]')

Sass Nesting for :hover does not work

For concatenating selectors together when nesting, you need to use the parent selector (&):

.class {
    margin:20px;
    &:hover {
        color:yellow;
    }
}

PHP array: count or sizeof?

According to phpbench:

Is it worth the effort to calculate the length of the loop in advance?

//pre-calculate the size of array
$size = count($x); //or $size = sizeOf($x);

for ($i=0; $i<$size; $i++) {
    //...
}

//don't pre-calculate
for ($i=0; $i<count($x); $i++) { //or $i<sizeOf($x);
    //...
}

A loop with 1000 keys with 1 byte values are given.

                  +---------+----------+
                  | count() | sizeof() |
+-----------------+---------+----------+
| With precalc    |     152 |      212 |
| Without precalc |   70401 |    50644 |
+-----------------+---------+----------+  (time in µs)

So I personally prefer to use count() instead of sizeof() with pre calc.

Dividing two integers to produce a float result

Cast the operands to floats:

float ans = (float)a / (float)b;

BigDecimal to string

// Convert BigDecimal number To String by using below method //

public static String RemoveTrailingZeros(BigDecimal tempDecimal)
{
    tempDecimal = tempDecimal.stripTrailingZeros();
    String tempString = tempDecimal.toPlainString();
    return tempString;
}

// Recall RemoveTrailingZeros
BigDecimal output = new BigDecimal(0);
String str = RemoveTrailingZeros(output);

How to duplicate a git repository? (without forking)

I have noticed some of the other answers here use a bare clone and then mirror push to the new repository, however this does not work for me and when I open the new repository after that, the files look mixed up and not as I expect.

Here is a solution that definitely works for copying the files, although it does not preserve the original repository's revision history.

  1. git clone the repository onto your local machine.
  2. cd into the project directory and then run rm -rf .git to remove all the old git metadata including commit history, etc.
  3. Initialize a fresh git repository by running git init.
  4. Run git add . ; git commit -am "Initial commit" - Of course you can call this commit what you want.
  5. Set the origin to your new repository git remote add origin https://github.com/user/repo-name (replace the url with the url to your new repository)
  6. Push it to your new repository with git push origin master.

How to find tag with particular text with Beautiful Soup?

You can pass a regular expression to the text parameter of findAll, like so:

import BeautifulSoup
import re

columns = soup.findAll('td', text = re.compile('your regex here'), attrs = {'class' : 'pos'})

How to change current working directory using a batch file

Try this

chdir /d D:\Work\Root

Enjoy rooting ;)

How do you get an iPhone's device name

For swift4.0 and above used below code:

    let udid = UIDevice.current.identifierForVendor?.uuidString
    let name = UIDevice.current.name
    let version = UIDevice.current.systemVersion
    let modelName = UIDevice.current.model
    let osName = UIDevice.current.systemName
    let localized = UIDevice.current.localizedModel
    
    print(udid ?? "")
    print(name)
    print(version)
    print(modelName)
    print(osName)
    print(localized)

Git submodule head 'reference is not a tree' error

This error can mean that a commit is missing in the submodule. That is, the repository (A) has a submodule (B). A wants to load B so that it is pointing to a certain commit (in B). If that commit is somehow missing, you'll get that error. Once possible cause: the reference to the commit was pushed in A, but the actual commit was not pushed from B. So I'd start there.

Less likely, there's a permissions problem, and the commit cannot be pulled (possible if you're using git+ssh).

Make sure the submodule paths look ok in .git/config and .gitmodules.

One last thing to try - inside the submodule directory: git reset HEAD --hard

Command to open file with git

I know this is ancient, but I need to do this at the end of a git helper script (alias that creates aliases from a template), and found what I think is the real answer:

There is a porcelain-ish helper called git-sh-setup that, when sourced, gives you a git_editor function that

runs an editor of user’s choice (GIT_EDITOR, core.editor, VISUAL or EDITOR) on a given file, but error out if no editor is specified and the terminal is dumb.

The git-sh-setup documentation description basically tells you not to use it, and that's probably good advice in this case.

Fortunately, the git-sh-setup is a shell script and the git_editor portion of it is pretty small, and we can just copy that:

git_editor() {
    if test -z "${GIT_EDITOR:+set}"
    then
        GIT_EDITOR="$(git var GIT_EDITOR)" || return $?
    fi
    eval "$GIT_EDITOR" '"$@"'
}

You should be able to put that in your own scripts or turn it into a bash alias and then call it like git_editor file1.txt file2.txt ...

ExecuteNonQuery: Connection property has not been initialized.

Opening and closing the connection takes a lot of time. And use the "using" as another member suggested. I changed your code slightly, but put the SQL creation and opening and closing OUTSIDE your loop. Which should speed up the execution a bit.

  static void Main()
        {
            EventLog alog = new EventLog();
            alog.Log = "Application";
            alog.MachineName = ".";
            /*  ALSO: USE the USING Statement as another member suggested
            using (SqlConnection connection1 = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=syslog2;Integrated Security=True")
            {

                using (SqlCommand comm = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ", connection1))
                {
                    // add the code in here
                    // AND REMEMBER: connection1.Open();

                }
            }*/
            SqlConnection connection1 = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=syslog2;Integrated Security=True");
            SqlDataAdapter cmd = new SqlDataAdapter();
            // Do it one line
            cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ", connection1);
            // OR YOU CAN DO IN SEPARATE LINE :
            // cmd.InsertCommand.Connection = connection1;
            connection1.Open();

            // CREATE YOUR SQLCONNECTION ETC OUTSIDE YOUR FOREACH LOOP
            foreach (EventLogEntry entry in alog.Entries)
            {
                cmd.InsertCommand.Parameters.Add("@EventLog", SqlDbType.VarChar).Value = alog.Log;
                cmd.InsertCommand.Parameters.Add("@TimeGenerated", SqlDbType.DateTime).Value = entry.TimeGenerated;
                cmd.InsertCommand.Parameters.Add("@EventType", SqlDbType.VarChar).Value = entry.EntryType;
                cmd.InsertCommand.Parameters.Add("@SourceName", SqlDbType.VarChar).Value = entry.Source;
                cmd.InsertCommand.Parameters.Add("@ComputerName", SqlDbType.VarChar).Value = entry.MachineName;
                cmd.InsertCommand.Parameters.Add("@InstanceId", SqlDbType.VarChar).Value = entry.InstanceId;
                cmd.InsertCommand.Parameters.Add("@Message", SqlDbType.VarChar).Value = entry.Message;
                int rowsAffected = cmd.InsertCommand.ExecuteNonQuery();
            }
            connection1.Close(); // AND CLOSE IT ONCE, AFTER THE LOOP
        }

How can I get the SQL of a PreparedStatement?

To do this you need a JDBC Connection and/or driver that supports logging the sql at a low level.

Take a look at log4jdbc

Android: ScrollView force to bottom

Sometimes scrollView.post doesn't work

 scrollView.post(new Runnable() {
        @Override
        public void run() {
            scrollView.fullScroll(ScrollView.FOCUS_DOWN);
        }
    });

BUT if you use scrollView.postDelayed, it will definitely work

 scrollView.postDelayed(new Runnable() {
        @Override
        public void run() {
            scrollView.fullScroll(ScrollView.FOCUS_DOWN);
        }
    },1000);

Spark: Add column to dataframe conditionally

My bad, I had missed one part of the question.

Best, cleanest way is to use a UDF. Explanation within the code.

// create some example data...BY DataFrame
// note, third record has an empty string
case class Stuff(a:String,b:Int)
val d= sc.parallelize(Seq( ("a",1),("b",2),
     ("",3) ,("d",4)).map { x => Stuff(x._1,x._2)  }).toDF

// now the good stuff.
import org.apache.spark.sql.functions.udf
// function that returns 0 is string empty 
val func = udf( (s:String) => if(s.isEmpty) 0 else 1 )
// create new dataframe with added column named "notempty"
val r = d.select( $"a", $"b", func($"a").as("notempty") )

    scala> r.show
+---+---+--------+
|  a|  b|notempty|
+---+---+--------+
|  a|  1|    1111|
|  b|  2|    1111|
|   |  3|       0|
|  d|  4|    1111|
+---+---+--------+

Extension methods must be defined in a non-generic static class

Try changing

public class LinqHelper

to

 public static class LinqHelper

How can I detect if a selector returns null?

This is in the JQuery documentation:

http://learn.jquery.com/using-jquery-core/faq/how-do-i-test-whether-an-element-exists/

  alert( $( "#notAnElement" ).length ? 'Not null' : 'Null' );

Postman: How to make multiple requests at the same time

I don't know if this question is still relevant, but there is such possibility in Postman now. They added it a few months ago.

All you need is create simple .js file and run it via node.js. It looks like this:

var path = require('path'),
  async = require('async'), //https://www.npmjs.com/package/async
  newman = require('newman'),

  parametersForTestRun = {
    collection: path.join(__dirname, 'postman_collection.json'), // your collection
    environment: path.join(__dirname, 'postman_environment.json'), //your env
  };

parallelCollectionRun = function(done) {
  newman.run(parametersForTestRun, done);
};

// Runs the Postman sample collection thrice, in parallel.
async.parallel([
    parallelCollectionRun,
    parallelCollectionRun,
    parallelCollectionRun
  ],
  function(err, results) {
    err && console.error(err);

    results.forEach(function(result) {
      var failures = result.run.failures;
      console.info(failures.length ? JSON.stringify(failures.failures, null, 2) :
        `${result.collection.name} ran successfully.`);
    });
  });

Then just run this .js file ('node fileName.js' in cmd).

More details here

Store multiple values in single key in json

{
  "number" : ["1","2","3"],
  "alphabet" : ["a", "b", "c"]
}

How do I resolve "Cannot find module" error using Node.js?

Using npm install installs the module into the current directory only (in a subdirectory called node_modules). Is app.js located under home/dave/src/server/? If not and you want to use the module from any directory, you need to install it globally using npm install -g.

I usually install most packages locally so that they get checked in along with my project code.

Update (8/2019):

Nowadays you can use package-lock.json file, which is automatically generated when npm modifies your node_modules directory. Therefore you can leave out checking in packages, because the package-lock.json tracks the exact versions of your node_modules, you're currently using. To install packages from package-lock.json instead of package.json use the command npm ci.

Update (3/2016):

I've received a lot of flak for my response, specifically that I check in the packages that my code depends on. A few days ago, somebody unpublished all of their packages (https://kodfabrik.com/journal/i-ve-just-liberated-my-modules) which broke React, Babel, and just about everything else. Hopefully it's clear now that if you have production code, you can't rely on NPM actually maintaining your dependencies for you.

How to count number of files in each directory?

This prints the file count per directory for the current directory level:

du -a | cut -d/ -f2 | sort | uniq -c | sort -nr

Force browser to clear cache

I had similiar problem and this is how I solved it:

  1. In index.html file I've added manifest:

    <html manifest="cache.manifest">
    
  2. In <head> section included script updating the cache:

    <script type="text/javascript" src="update_cache.js"></script>
    
  3. In <body> section I've inserted onload function:

    <body onload="checkForUpdate()">
    
  4. In cache.manifest I've put all files I want to cache. It is important now that it works in my case (Apache) just by updating each time the "version" comment. It is also an option to name files with "?ver=001" or something at the end of name but it's not needed. Changing just # version 1.01 triggers cache update event.

    CACHE MANIFEST
    # version 1.01
    style.css
    imgs/logo.png
    #all other files
    

    It's important to include 1., 2. and 3. points only in index.html. Otherwise

    GET http://foo.bar/resource.ext net::ERR_FAILED
    

    occurs because every "child" file tries to cache the page while the page is already cached.

  5. In update_cache.js file I've put this code:

    function checkForUpdate()
    {
        if (window.applicationCache != undefined && window.applicationCache != null)
        {
            window.applicationCache.addEventListener('updateready', updateApplication);
        }
    }
    function updateApplication(event)
    {
        if (window.applicationCache.status != 4) return;
        window.applicationCache.removeEventListener('updateready', updateApplication);
        window.applicationCache.swapCache();
        window.location.reload();
    }
    

Now you just change files and in manifest you have to update version comment. Now visiting index.html page will update the cache.

The parts of solution aren't mine but I've found them through internet and put together so that it works.

How to convert empty spaces into null values, using SQL Server?

Maybe something like this?

UPDATE [MyTable]
SET [SomeField] = NULL
WHERE [SomeField] is not NULL
AND LEN(LTRIM(RTRIM([SomeField]))) = 0

UICollectionView cell selection and cell reuse

Changing the cell property such as the cell's background colors shouldn't be done on the UICollectionViewController itself, it should be done inside you CollectionViewCell class. Don't use didSelect and didDeselect, just use this:

class MyCollectionViewCell: UICollectionViewCell 
{
     override var isSelected: Bool
     {
         didSet
         {
            // Your code
         }
     } 
}

Angular 2 Cannot find control with unspecified name attribute on formArrays

In my case I solved the issue by putting the name of the formControl in double and sinlge quotes so that it is interpreted as a string:

[formControlName]="'familyName'"

similar to below:

formControlName="familyName"

HTML SELECT - Change selected option by VALUE using JavaScript

If you are using jQuery:

$('#sel').val('bike');

What's the difference between nohup and ampersand

Correct me if I'm wrong

  nohup myprocess.out &

nohup catches the hangup signal, which mean it will send a process when terminal closed.

 myprocess.out &

Process can run but will stopped once the terminal is closed.

nohup myprocess.out

Process able to run even terminal closed, but you are able to stop the process by pressing ctrl + z in terminal. Crt +z not working if & is existing.

Equivalent function for DATEADD() in Oracle

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

Error: Cannot find module '../lib/utils/unsupported.js' while using Ionic

Yes you should re-install node:

sudo rm -rf /usr/local/lib/node_modules/npm
 brew uninstall --force node                
 brew install node

How to print without newline or space?

Or have a function like:

def Print(s):
   return sys.stdout.write(str(s))

Then now:

for i in range(10): # or `xrange` for python 2 version
   Print(i)

Outputs:

0123456789

How to run PowerShell in CMD

Try just:

powershell.exe -noexit D:\Work\SQLExecutor.ps1 -gettedServerName "MY-PC"

How do I write good/correct package __init__.py files

Your __init__.py should have a docstring.

Although all the functionality is implemented in modules and subpackages, your package docstring is the place to document where to start. For example, consider the python email package. The package documentation is an introduction describing the purpose, background, and how the various components within the package work together. If you automatically generate documentation from docstrings using sphinx or another package, the package docstring is exactly the right place to describe such an introduction.

For any other content, see the excellent answers by firecrow and Alex Martelli.

How do I format a number to a dollar amount in PHP

If you just want something simple:

'$' . number_format($money, 2);

number_format()

How to add a border to a widget in Flutter?

As stated in the documentation, flutter prefer composition over parameters. Most of the time what you're looking for is not a property, but instead a wrapper (and sometimes a few helpers/"builder")

For borders what you want is DecoratedBox, which has a decoration property that defines borders ; but also background images or shadows.

Alternatively like @Aziza said, you can use Container. Which is the combination of DecoratedBox, SizedBox and a few other useful widgets.

Apache giving 403 forbidden errors

Check that :

  • Apache can physically access the file (the user that run apache, probably www-data or apache, can access the file in the filesystem)
  • Apache can list the content of the folder (read permission)
  • Apache has a "Allow" directive for that folder. There should be one for /var/www/, you can check default vhost for example.

Additionally, you can look at the error.log file (usually located at /var/log/apache2/error.log) which will describe why you get the 403 error exactly.

Finally, you may want to restart apache, just to be sure all that configuration is applied. This can be generally done with /etc/init.d/apache2 restart. On some system, the script will be called httpd. Just figure out.

Register comdlg32.dll gets Regsvr32: DllRegisterServer entry point was not found

comdlg32.dll is not a COM DLL and cannot be registered.

One way to confirm this for yourself is to run this command:

dumpbin /exports comdlg32.dll

You'll see that comdlg32.dll doesn't contain a DllRegisterServer method. Hence RegSvr32.exe won't work.

That's your answer.


ComDlg32.dll is a a system component. (exists in both c:\windows\system32 and c:\windows\syswow64) Trying to replace it or override any registration with an older version could corrupt the rest of Windows.


I can help more, but I need to know what MSComDlg.CommonDialog is. What does it do and how is it supposed to work? And what version of ComDlg32.dll are you trying to register (and where did you get it)?

How to make a vertical line in HTML

You can draw a vertical line by simply using height / width with any html element.

_x000D_
_x000D_
#verticle-line {_x000D_
  width: 1px;_x000D_
  min-height: 400px;_x000D_
  background: red;_x000D_
}
_x000D_
<div id="verticle-line"></div>
_x000D_
_x000D_
_x000D_

How to return a specific status code and no contents from Controller?

The best way to do it is:

return this.StatusCode(StatusCodes.Status418ImATeapot, "Error message");

'StatusCodes' has every kind of return status and you can see all of them in this link https://httpstatuses.com/

Once you choose your StatusCode, return it with a message.

How to update a record using sequelize for node?

And for people looking for an answer in December 2018, this is the correct syntax using promises:

Project.update(
    // Values to update
    {
        title:  'a very different title now'
    },
    { // Clause
        where: 
        {
            id: 1
        }
    }
).then(count => {
    console.log('Rows updated ' + count);
});

Delete from two tables in one query

no need for JOINS:

DELETE m, um FROM messages m, usersmessages um

WHERE m.messageid = 1 

AND m.messageid = um.messageid 

PHP order array by date?

Use usort:

usort($array, function($a1, $a2) {
   $v1 = strtotime($a1['date']);
   $v2 = strtotime($a2['date']);
   return $v1 - $v2; // $v2 - $v1 to reverse direction
});

Create the perfect JPA entity

My 2 cents addition to the answers here are:

  1. With reference to Field or Property access (away from performance considerations) both are legitimately accessed by means of getters and setters, thus, my model logic can set/get them in the same manner. The difference comes to play when the persistence runtime provider (Hibernate, EclipseLink or else) needs to persist/set some record in Table A which has a foreign key referring to some column in Table B. In case of a Property access type, the persistence runtime system uses my coded setter method to assign the cell in Table B column a new value. In case of a Field access type, the persistence runtime system sets the cell in Table B column directly. This difference is not of importance in the context of a uni-directional relationship, yet it is a MUST to use my own coded setter method (Property access type) for a bi-directional relationship provided the setter method is well designed to account for consistency. Consistency is a critical issue for bi-directional relationships refer to this link for a simple example for a well-designed setter.

  2. With reference to Equals/hashCode: It is impossible to use the Eclipse auto-generated Equals/hashCode methods for entities participating in a bi-directional relationship, otherwise they will have a circular reference resulting in a stackoverflow Exception. Once you try a bidirectional relationship (say OneToOne) and auto-generate Equals() or hashCode() or even toString() you will get caught in this stackoverflow exception.

How to convert ZonedDateTime to Date?

You can convert ZonedDateTime to an instant, which you can use directly with Date.

Date.from(java.time.ZonedDateTime.now().toInstant());

Recommendations of Python REST (web services) framework?

Surprised no one mentioned flask.

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()

Converting std::__cxx11::string to std::string

I got this, the only way I found to fix this was to update all of mingw-64 (I did this using pacman on msys2 for your information).

Getting "Cannot call a class as a function" in my React Project

Happened to me because I used

PropTypes.arrayOf(SomeClass)

instead of

PropTypes.arrayOf(PropTypes.instanceOf(SomeClass))

Volley - POST/GET parameters

Dealing with GET parameters I iterated on Andrea Motto' solution. The problem was that Volley called GetUrl several times and his solution, using an Iterator, destroyed original Map object. The subsequent Volley internal calls had an empty params object.

I added also the encode of parameters.

This is an inline usage (no subclass).

public void GET(String url, Map<String, String> params, Response.Listener<String> response_listener, Response.ErrorListener error_listener, String API_KEY, String stringRequestTag) {
    final Map<String, String> mParams = params;
    final String mAPI_KEY = API_KEY;
    final String mUrl = url;

    StringRequest stringRequest = new StringRequest(
            Request.Method.GET,
            mUrl,
            response_listener,
            error_listener
    ) {
        @Override
        protected Map<String, String> getParams() {
            return mParams;
        }

        @Override
        public String getUrl() {
            StringBuilder stringBuilder = new StringBuilder(mUrl);
            int i = 1;
            for (Map.Entry<String,String> entry: mParams.entrySet()) {
                String key;
                String value;
                try {
                    key = URLEncoder.encode(entry.getKey(), "UTF-8");
                    value = URLEncoder.encode(entry.getValue(), "UTF-8");
                    if(i == 1) {
                        stringBuilder.append("?" + key + "=" + value);
                    } else {
                        stringBuilder.append("&" + key + "=" + value);
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                i++;

            }
            String url = stringBuilder.toString();

            return url;
        }

        @Override
        public Map<String, String> getHeaders() {
            Map<String, String> headers = new HashMap<>();
            if (!(mAPI_KEY.equals(""))) {
                headers.put("X-API-KEY", mAPI_KEY);
            }
            return headers;
        }
    };

    if (stringRequestTag != null) {
        stringRequest.setTag(stringRequestTag);
    }

    mRequestQueue.add(stringRequest);
}

This function uses headers to pass an APIKEY and sets a TAG to the request useful to cancel it before its completion.

Hope this helps.

How do you Change a Package's Log Level using Log4j?

I encountered the exact same problem today, Ryan.

In my src (or your root) directory, my log4j.properties file now has the following addition

# https://issues.apache.org/jira/browse/AXIS2-4363
log4j.category.org.apache.axiom=WARN

Thanks for the heads up as to how to do this, Benjamin.

Passing 'this' to an onclick event

The code that you have would work, but is executed from the global context, which means that this refers to the global object.

<script type="text/javascript">
var foo = function(param) {
    param.innerHTML = "Not a button";
};
</script>
<button onclick="foo(this)" id="bar">Button</button>

You can also use the non-inline alternative, which attached to and executed from the specific element context which allows you to access the element from this.

<script type="text/javascript">
document.getElementById('bar').onclick = function() {
    this.innerHTML = "Not a button";
};
</script>
<button id="bar">Button</button>

How to add an item to an ArrayList in Kotlin?

For people just migrating from java, In Kotlin List is by default immutable and mutable version of Lists is called MutableList.

Hence if you have something like :

val list: List<String> = ArrayList()

In this case you will not get an add() method as list is immutable. Hence you will have to declare a MutableList as shown below :

val list: MutableList<String> = ArrayList()

Now you will see an add() method and you can add elements to any list.

gcc: undefined reference to

However, avpicture_get_size is defined.

No, as the header (<libavcodec/avcodec.h>) just declares it.

The definition is in the library itself.

So you might like to add the linker option to link libavcodec when invoking gcc:

-lavcodec

Please also note that libraries need to be specified on the command line after the files needing them:

gcc -I$HOME/ffmpeg/include program.c -lavcodec

Not like this:

gcc -lavcodec -I$HOME/ffmpeg/include program.c

Referring to Wyzard's comment, the complete command might look like this:

gcc -I$HOME/ffmpeg/include program.c -L$HOME/ffmpeg/lib -lavcodec

For libraries not stored in the linkers standard location the option -L specifies an additional search path to lookup libraries specified using the -l option, that is libavcodec.x.y.z in this case.


For a detailed reference on GCC's linker option, please read here.

Passing string parameter in JavaScript function

document.write(`<td width='74'><button id='button' type='button' onclick='myfunction(\``+ name + `\`)'>click</button></td>`)

Better to use `` than "". This is a more dynamic answer.

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value

Error: The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.

This error occurred when due to NOT assigning any value against a NOT NULL date column in SQL DB using EF and was resolved by assigning the same.

Hope this helps!

JavaScript: replace last occurrence of text in a string

Simple solution would be to use substring method. Since string is ending with list element, we can use string.length and calculate end index for substring without using lastIndexOf method

str = str.substring(0, str.length - list[i].length) + "finish"

Generate a UUID on iOS from Swift

Each time the same will be generated:

if let uuid = UIDevice.current.identifierForVendor?.uuidString {
    print(uuid)
}

Each time a new one will be generated:

let uuid = UUID().uuidString
print(uuid)

Proper usage of .net MVC Html.CheckBoxFor

I had trouble getting this to work and added another solution for anyone wanting/ needing to use FromCollection.

Instead of:

@Html.CheckBoxFor(model => true, item.TemplateId) 

Format html helper like so:

@Html.CheckBoxFor(model => model.SomeProperty, new { @class = "form-control", Name = "SomeProperty"})

Then in the viewmodel/model wherever your logic is:

public void Save(FormCollection frm)
{   
    // to do instantiate object.

    instantiatedItem.SomeProperty = (frm["SomeProperty"] ?? "").Equals("true", StringComparison.CurrentCultureIgnoreCase);

    // to do and save changes in database.
}

What techniques can be used to define a class in JavaScript, and what are their trade-offs?

JavaScript is object-oriented, but it's radically different than other OOP languages like Java, C# or C++. Don't try to understand it like that. Throw that old knowledge out and start anew. JavaScript needs a different thinking.

I'd suggest to get a good manual or something on the subject. I myself found ExtJS Tutorials the best for me, although I haven't used the framework before or after reading it. But it does give a good explanation about what is what in JavaScript world. Sorry, it seems that that content has been removed. Here's a link to archive.org copy instead. Works today. :P

Difference between F5, Ctrl + F5 and click on refresh button?

F5 and the refresh button will look at your browser cache before asking the server for content.

Ctrl + F5 forces a load from the server.

You can set content expiration headers and/or meta tags to ensure the browser doesn't cache anything (perhaps something you can do only for the development environment).

How do I escape only single quotes?

Here is how I did it. Silly, but simple.

$singlequote = "'";
$picturefile = getProductPicture($id);

echo showPicture('.$singlequote.$picturefile.$singlequote.');

I was working on outputting HTML that called JavaScript code to show a picture...

How to Merge Two Eloquent Collections?

Creating a new base collection for each eloquent collection the merge works for me.

$foo = collect(Foo::all());
$bar = collect(Bar::all());
$merged = $foo->merge($bar);

In this case don't have conflits by its primary keys.

How to prevent long words from breaking my div?

after all the word wraps and breaks, preserve your overflow and see if this solves your issue. simply change your div's display to: display: inline;

Getting a machine's external IP address with Python

If the machine is being a firewall then your solution is a very sensible one: the alternative being able to query the firewall which ends-up being very dependent on the type of firewall (if at all possible).

Google Chrome Full Black Screen

If you have the Adblock extension, make sure you add the domain into the exception list. I had that problem with Google Analytics

How to read a PEM RSA private key from .NET

With respect to easily importing the RSA private key, without using 3rd party code such as BouncyCastle, I think the answer is "No, not with a PEM of the private key alone."

However, as alluded to above by Simone, you can simply combine the PEM of the private key (*.key) and the certificate file using that key (*.crt) into a *.pfx file which can then be easily imported.

To generate the PFX file from the command line:

openssl pkcs12 -in a.crt -inkey a.key -export -out a.pfx

Then use normally with the .NET certificate class such as:

using System.Security.Cryptography.X509Certificates;

X509Certificate2 combinedCertificate = new X509Certificate2(@"C:\path\to\file.pfx");

Now you can follow the example from MSDN for encrypting and decrypting via RSACryptoServiceProvider:

I left out that for decrypting you would need to import using the PFX password and the Exportable flag. (see: BouncyCastle RSAPrivateKey to .NET RSAPrivateKey)

X509KeyStorageFlags flags = X509KeyStorageFlags.Exportable;
X509Certificate2 cert = new X509Certificate2("my.pfx", "somepass", flags);

RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PrivateKey;
RSAParameters rsaParam = rsa.ExportParameters(true); 

How to list the files inside a JAR file?

A jar file is just a zip file with a structured manifest. You can open the jar file with the usual java zip tools and scan the file contents that way, inflate streams, etc. Then use that in a getResourceAsStream call, and it should be all hunky dory.

EDIT / after clarification

It took me a minute to remember all the bits and pieces and I'm sure there are cleaner ways to do it, but I wanted to see that I wasn't crazy. In my project image.jpg is a file in some part of the main jar file. I get the class loader of the main class (SomeClass is the entry point) and use it to discover the image.jpg resource. Then some stream magic to get it into this ImageInputStream thing and everything is fine.

InputStream inputStream = SomeClass.class.getClassLoader().getResourceAsStream("image.jpg");
JPEGImageReaderSpi imageReaderSpi = new JPEGImageReaderSpi();
ImageReader ir = imageReaderSpi.createReaderInstance();
ImageInputStream iis = new MemoryCacheImageInputStream(inputStream);
ir.setInput(iis);
....
ir.read(0); //will hand us a buffered image

How to add class active on specific li on user click with jQuery

        // Remove active for all items.
        $('.sidebar-menu li').removeClass('active');
        // highlight submenu item
        $('li a[href="' + this.location.pathname + '"]').parent().addClass('active');
        // Highlight parent menu item.
        $('ul a[href="' + this.location.pathname + '"]').parents('li').addClass('active')

How can I use the HTML5 canvas element in IE?

I just used flashcanvas, and I got that working. If you encounter problems, just make sure to read the caveats and whatnot. Particularly, if you create canvas elements dynamically, you need to initialize them explicitly:

if (typeof FlashCanvas != "undefined") {
    FlashCanvas.initElement(canvas);
}

Why is visible="false" not working for a plain html table?

Who "they"? I don't think there's a visible attribute in html.

How do I get the directory from a file's full path?

If you've definitely got an absolute path, use Path.GetDirectoryName(path).

If you might only get a relative name, use new FileInfo(path).Directory.FullName.

Note that Path and FileInfo are both found in the namespace System.IO.

Android ADT error, dx.jar was not loaded from the SDK folder

It happened to me, either, and it happens because I've changed to win7, and install the latest ADT to eclipse, but I used my old Android SDK. Finally, I fix this problem by updating my Android SDK to the latest version.

SELECT * FROM X WHERE id IN (...) with Dapper ORM

Example for postgres:

string sql = "SELECT * FROM SomeTable WHERE id = ANY(@ids)"
var results = conn.Query(sql, new { ids = new[] { 1, 2, 3, 4, 5 }});

Get loop counter/index using for…of syntax in JavaScript

As others have said, you shouldn't be using for..in to iterate over an array.

for ( var i = 0, len = myArray.length; i < len; i++ ) { ... }

If you want cleaner syntax, you could use forEach:

myArray.forEach( function ( val, i ) { ... } );

If you want to use this method, make sure that you include the ES5 shim to add support for older browsers.

Check/Uncheck a checkbox on datagridview

The code you are trying here will flip the states (if true then became false vice versa) of the checkboxes irrespective of the user selected checkbox because here the foreach is selecting each checkbox and performing the operations.

To make it clear, store the index of the user selected checkbox before performing the foreach operation and after the foreach operation call the checkbox by mentioning the stored index and check it (In your case, make it True -- I think).

This is just logic and I am damn sure it is correct. I will try to implement some sample code if possible.

Modify your foreach something like this:

    //Store the index of the selected checkbox here as Integer (you can use e.RowIndex or e.ColumnIndex for it).
    private void chkItems_CheckedChanged(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in datagridview1.Rows)
        {
            DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[1];
            if (chk.Selected == true)
            {
                chk.Selected = false;
            }
            else
            {
                chk.Selected = true;
            }
        }
    }
    //write the function for checking(making true) the user selected checkbox by calling the stored Index

The above function makes all the checkboxes true including the user selected CheckBox. I think this is what you want..

Change div height on button click

You have to set height as a string value when you use pixels.

document.getElementById('chartdiv').style.height = "200px"

Also try adding a DOCTYPE to your HTML for Internet Explorer.

<!DOCTYPE html>
<html> ...

How can I get form data with JavaScript/jQuery?

If you are using jQuery, here is a little function that will do what you are looking for.

First, add an ID to your form (unless it is the only form on the page, then you can just use 'form' as the dom query)

<form id="some-form">
 <input type="radio" name="foo" value="1" checked="checked" />
 <input type="radio" name="foo" value="0" />
 <input name="bar" value="xxx" />
 <select name="this">
  <option value="hi" selected="selected">Hi</option>
  <option value="ho">Ho</option>
</form>

<script>
//read in a form's data and convert it to a key:value object
function getFormData(dom_query){
    var out = {};
    var s_data = $(dom_query).serializeArray();
    //transform into simple data/value object
    for(var i = 0; i<s_data.length; i++){
        var record = s_data[i];
        out[record.name] = record.value;
    }
    return out;
}

console.log(getFormData('#some-form'));
</script>

The output would look like:

{
 "foo": "1",
 "bar": "xxx",
 "this": "hi"
}

Undefined index error PHP

Hey this is happening because u r trying to display value before assignnig it U just fill in the values and submit form it will display correct output Or u can write ur php code below form tags It ll run without any errors

Extension gd is missing from your system - laravel composer Update

if you are working in PHP version 7.2 then you have to install

sudo apt-get install php7.2-gd

Undefined function mysql_connect()

I was getting this error because the project I was working on was developed on php 5.6 and after install, the project was unable to run on php7.1.

Just for anyone that uses Vagrant with ubuntu/nginx, in the nginx directory(/etc/nginx/), there is a directory named "sites-available" which contains a file named like the url configured for the vagrant maschine. In my case was homestead.app. Within this file there is a line that says something like

    fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;

There you can change the php version to the desired for that particular site.

Googled this but wasnt really able to find a simple answer that said where to look and what to change.

Hope that this helps anyone. Thanks.

Virtual network interface in Mac OS X

ifconfig interfacename create will create a virtual interface,

Difference between Node object and Element object?

Node is used to represent tags in general. Divided to 3 types:

Attribute Note: is node which inside its has attributes. Exp: <p id=”123”></p>

Text Node: is node which between the opening and closing its have contian text content. Exp: <p>Hello</p>

Element Node : is node which inside its has other tags. Exp: <p><b></b></p>

Each node may be types simultaneously, not necessarily only of a single type.

Element is simply a element node.

How to apply font anti-alias effects in CSS?

Works the best. If you want to use it sitewide, without having to add this syntax to every class or ID, add the following CSS to your css body:

body { 
    -webkit-font-smoothing: antialiased;
    text-shadow: 1px 1px 1px rgba(0,0,0,0.004);
    background: url('./images/background.png');
    text-align: left;
    margin: auto;

}

Using Google maps API v3 how do I get LatLng with a given address?

There is a pretty good example on https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple

To shorten it up a little:

geocoder = new google.maps.Geocoder();

function codeAddress() {

    //In this case it gets the address from an element on the page, but obviously you  could just pass it to the method instead
    var address = document.getElementById( 'address' ).value;

    geocoder.geocode( { 'address' : address }, function( results, status ) {
        if( status == google.maps.GeocoderStatus.OK ) {

            //In this case it creates a marker, but you can get the lat and lng from the location.LatLng
            map.setCenter( results[0].geometry.location );
            var marker = new google.maps.Marker( {
                map     : map,
                position: results[0].geometry.location
            } );
        } else {
            alert( 'Geocode was not successful for the following reason: ' + status );
        }
    } );
}

Date / Timestamp to record when a record was added to the table?

You can create a non-nullable DATETIME column on your table, and create a DEFAULT constraint on it to auto populate when a row is added.

e.g.

CREATE TABLE Example
(
SomeField INTEGER,
DateCreated DATETIME NOT NULL DEFAULT(GETDATE())
)

Using Eloquent ORM in Laravel to perform search of database using LIKE

If you need to frequently use LIKE, you can simplify the problem a bit. A custom method like () can be created in the model that inherits the Eloquent ORM:

public  function scopeLike($query, $field, $value){
        return $query->where($field, 'LIKE', "%$value%");
}

So then you can use this method in such way:

User::like('name', 'Tomas')->get();

Pandas percentage of total with groupby

The most elegant way to find percentages across columns or index is to use pd.crosstab.

Sample Data

df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
               'office_id': list(range(1, 7)) * 2,
               'sales': [np.random.randint(100000, 999999) for _ in range(12)]})

The output dataframe is like this

print(df)

        state   office_id   sales
    0   CA  1   764505
    1   WA  2   313980
    2   CO  3   558645
    3   AZ  4   883433
    4   CA  5   301244
    5   WA  6   752009
    6   CO  1   457208
    7   AZ  2   259657
    8   CA  3   584471
    9   WA  4   122358
    10  CO  5   721845
    11  AZ  6   136928

Just specify the index, columns and the values to aggregate. The normalize keyword will calculate % across index or columns depending upon the context.

result = pd.crosstab(index=df['state'], 
                     columns=df['office_id'], 
                     values=df['sales'], 
                     aggfunc='sum', 
                     normalize='index').applymap('{:.2f}%'.format)




print(result)
office_id   1   2   3   4   5   6
state                       
AZ  0.00%   0.20%   0.00%   0.69%   0.00%   0.11%
CA  0.46%   0.00%   0.35%   0.00%   0.18%   0.00%
CO  0.26%   0.00%   0.32%   0.00%   0.42%   0.00%
WA  0.00%   0.26%   0.00%   0.10%   0.00%   0.63%

The storage engine for the table doesn't support repair. InnoDB or MyISAM?

You have the wrong table set on the command. You should use the following on your setup:

ALTER TABLE scode_tracker.ap_visits ENGINE=MyISAM;

I want to get the type of a variable at runtime

I think the question is incomplete. if you meant that you wish to get the type information of some typeclass then below:

If you wish to print as you have specified then:

scala>  def manOf[T: Manifest](t: T): Manifest[T] = manifest[T]
manOf: [T](t: T)(implicit evidence$1: Manifest[T])Manifest[T]

scala> val x = List(1,2,3)
x: List[Int] = List(1, 2, 3)

scala> println(manOf(x))
scala.collection.immutable.List[Int]

If you are in repl mode then

scala> :type List(1,2,3)
List[Int]

Or if you just wish to know what the class type then as @monkjack explains "string".getClass might solve the purpose

Passing arguments to JavaScript function from code-behind

Response.Write("<scrip" + "t>test(" + x + "," + y + ");</script>");

breaking up the script keyword because VStudio / asp.net compiler doesn't like it

jQuery + client-side template = "Syntax error, unrecognized expression"

EugeneXa mentioned it in a comment, but it deserves to be an answer:

var template = $("#modal_template").html().trim();

This trims the offending whitespace from the beginning of the string. I used it with Mustache, like so:

var markup = Mustache.render(template, data);
$(markup).appendTo(container);

Convert utf8-characters to iso-88591 and back in PHP

First of all, don't use different encodings. It leads to a mess, and UTF-8 is definitely the one you should be using everywhere.

Chances are your input is not ISO-8859-1, but something else (ISO-8859-15, Windows-1252). To convert from those, use iconv or mb_convert_encoding.

Nevertheless, utf8_encode and utf8_decode should work for ISO-8859-1. It would be nice if you could post a link to a file or a uuencoded or base64 example string for which the conversion fails or yields unexpected results.

Entity Framework Query for inner join

In case anyone's interested in the Method syntax, if you have a navigation property, it's way easy:

db.Services.Where(s=>s.ServiceAssignment.LocationId == 1);

If you don't, unless there's some Join() override I'm unaware of, I think it looks pretty gnarly (and I'm a Method syntax purist):

db.Services.Join(db.ServiceAssignments, 
     s => s.Id,
     sa => sa.ServiceId, 
     (s, sa) => new {service = s, asgnmt = sa})
.Where(ssa => ssa.asgnmt.LocationId == 1)
.Select(ssa => ssa.service);

Max length for client ip address

As described in the IPv6 Wikipedia article,

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

A typical IPv6 address:

2001:0db8:85a3:0000:0000:8a2e:0370:7334

This is 39 characters long. IPv6 addresses are 128 bits long, so you could conceivably use a binary(16) column, but I think I'd stick with an alphanumeric representation.

Converting string to Date and DateTime

Since no one mentioned this, here's another way:

$date = date_create_from_format("m-d-Y", "10-16-2003")->format("Y-m-d");

how to send multiple data with $.ajax() jquery

var my_arr = new Array(listingID, site_click, browser, dimension);
    var AjaxURL = 'http://example.com';
    var jsonString = JSON.stringify(my_arr);
    $.ajax({
        type: "POST",
        url: AjaxURL,
        data: {data: jsonString},
        success: function(result) {
            window.console.log('Successful');
        }
    });

This has been working for me for quite some time.

How does DISTINCT work when using JPA and Hibernate

I agree with kazanaki's answer, and it helped me. I wanted to select the whole entity, so I used

 select DISTINCT(c) from Customer c

In my case I have many-to-many relationship, and I want to load entities with collections in one query.

I used LEFT JOIN FETCH and at the end I had to make the result distinct.

How to write to the Output window in Visual Studio?

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>

wstring outputMe = L"can" + L" concatenate\n";
OutputDebugString(outputMe.c_str());

how to convert 2d list to 2d numpy array?

just use following code

c = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix([[1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]])

Then it will give you

you can check shape and dimension of matrix by using following code

c.shape

c.ndim

MySQL pivot table query with dynamic columns

Here's stored procedure, which will generate the table based on data from one table and column and data from other table and column.

The function 'sum(if(col = value, 1,0)) as value ' is used. You can choose from different functions like MAX(if()) etc.

delimiter //

  create procedure myPivot(
    in tableA varchar(255),
    in columnA varchar(255),
    in tableB varchar(255),
    in columnB varchar(255)
)
begin
  set @sql = NULL;
    set @sql = CONCAT('select group_concat(distinct concat(
            \'SUM(IF(', 
        columnA, 
        ' = \'\'\',',
        columnA,
        ',\'\'\', 1, 0)) AS \'\'\',',
        columnA, 
            ',\'\'\'\') separator \', \') from ',
        tableA, ' into @sql');
    -- select @sql;

    PREPARE stmt FROM @sql;
    EXECUTE stmt;

    DEALLOCATE PREPARE stmt;
    -- select @sql;

    SET @sql = CONCAT('SELECT p.', 
        columnB, 
        ', ', 
        @sql, 
        ' FROM ', tableB, ' p GROUP BY p.',
        columnB,'');

    -- select @sql;

    /* */
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    /* */
    DEALLOCATE PREPARE stmt;
end//

delimiter ;

Upload Progress Bar in PHP

Implementation of the upload progress bar is easy and doesn't require any additional PHP extension, JavaScript or Flash. But you need PHP 5.4 and newer.

You have to enable collecting of the upload progress information by setting the directive session.upload_progress.enabled to On in php.ini.

Then add a hidden input to the HTML upload form just before any other file inputs. HTML attribute name of that hidden input should be the same as the value of the directive session.upload_progress.name from php.ini (eventually preceded by session.upload_progress.prefix). The value attribute is up to you, it will be used as part of the session key.

HTML form could looks like this:

<form action="upload.php" method="POST" enctype="multipart/form-data">
   <input type="hidden" name="<?php echo ini_get('session.upload_progress.prefix').ini_get('session.upload_progress.name'); ?>" value="myupload" />
   <input type="file" name="file1" />
   <input type="submit" />
</form>

When you send this form, PHP should create a new key in the $_SESSION superglobal structure which will be populated with the upload status information. The key is concatenated name and value of the hidden input.

In PHP you can take a look at populated upload information:

var_dump($_SESSION[
    ini_get('session.upload_progress.prefix')
   .ini_get('session.upload_progress.name')
   .'_myupload'
]);

The output will look similarly to the following:

$_SESSION["upload_progress_myupload"] = array(
  "start_time" => 1234567890,   // The request time
  "content_length" => 57343257, // POST content length
  "bytes_processed" => 54321,   // Amount of bytes received and processed
  "done" => false,              // true when the POST handler has finished, successfully or not
  "files" => array(
    0 => array(
      "field_name" => "file1",    // Name of the <input /> field
      // The following 3 elements equals those in $_FILES
      "name" => "filename.ext",
      "tmp_name" => "/tmp/phpxxxxxx",
      "error" => 0,
      "done" => false,            // True when the POST handler has finished handling this file
      "start_time" => 1234567890, // When this file has started to be processed
      "bytes_processed" => 54321, // Number of bytes received and processed for this file
    )
  )
);

There is all the information needed to create a progress bar — you have the information if the upload is still in progress, the information how many bytes is going to be transferred in total and how many bytes has been transferred already.

To present the upload progress to the user, write an another PHP script than the uploading one, which will only look at the upload information in the session and return it in the JSON format, for example. This script can be called periodically, for example every second, using AJAX and information presented to the user.

You are even able to cancel the upload by setting the $_SESSION[$key]['cancel_upload'] to true.

For detailed information, additional settings and user's comments see PHP manual.

pip install - locale.Error: unsupported locale setting

[This answer is target on linux platform only]

The first thing you should know is most of the locale config file located path can be get from localedef --help :

$ localedef --help | tail -n 5
System's directory for character maps : /usr/share/i18n/charmaps
                       repertoire maps: /usr/share/i18n/repertoiremaps
                       locale path    : /usr/lib/locale:/usr/share/i18n
For bug reporting instructions, please see:
<https://bugs.launchpad.net/ubuntu/+source/glibc/+bugs>

See the last /usr/share/i18n ? This is where your xx_XX.UTF-8 config file located:

$ ls /usr/share/i18n/locales/zh_*
/usr/share/i18n/locales/zh_CN  /usr/share/i18n/locales/zh_HK  /usr/share/i18n/locales/zh_SG  /usr/share/i18n/locales/zh_TW

Now what ? We need to compile them into archive binary. One of the way, e.g. assume I have /usr/share/i18n/locales/en_LOVE, I can add it into compile list, i.e. /etc/locale-gen file:

$ tail -1 /etc/locale.gen 
en_LOVE.UTF-8 UTF-8

And compile it to binary with sudo locale-gen:

$ sudo locale-gen 
Generating locales (this might take a while)...
  en_AG.UTF-8... done
  en_AU.UTF-8... done
  en_BW.UTF-8... done
  ...
  en_LOVE.UTF-8... done
Generation complete.

And now update the system default locale with desired LANG, LC_ALL ...etc with this update-locale:

sudo update-locale LANG=en_LOVE.UTF-8

update-locale actually also means to update this /etc/default/locale file which will source by system on login to setup environment variables:

$ head /etc/default/locale 
#  File generated by update-locale
LANG=en_LOVE.UTF-8
LC_NUMERIC="en_US.UTF-8"
...

But we may not want to reboot to take effect, so we can just source it to environment variable in current shell session:

$ . /etc/default/locale

How about sudo dpkg-reconfigure locales ? If you play around it you will know this command basically act as GUI to simplify the above steps, i.e. Edit /etc/locale.gen -> sudo locale-gen -> sudo update-locale LANG=en_LOVE.UTF-8

For python, as long as /etc/locale.gen contains that locale candidate and locale.gen get compiled, setlocale(category, locale) should work without throws locale.Error: unsupoorted locale setting. You can check the correct string en_US.UTF-8/en_US/....etc to be set in setlocale(), by observing /etc/locale.gen file, and then uncomment and compile it as desired. zh_CN GB2312 without dot in that file means the correct string is zh_CN and zh_CN.GB2312.

Add new row to dataframe, at specific row-index, not appended?

The .before argument in dplyr::add_row can be used to specify the row.

dplyr::add_row(
  cars,
  speed = 0,
  dist = 0,
  .before = 3
)
#>    speed dist
#> 1      4    2
#> 2      4   10
#> 3      0    0
#> 4      7    4
#> 5      7   22
#> 6      8   16
#> ...

Can I run multiple versions of Google Chrome on the same machine? (Mac or Windows)

As professional testers, my friends use Spoon.net browsers section to test compatibility of site in various browsers. Hope this should help you.

Determine Pixel Length of String in Javascript/jQuery?

The contexts used for HTML Canvases have a built-in method for checking the size of a font. This method returns a TextMetrics object, which has a width property that contains the width of the text.

function getWidthOfText(txt, fontname, fontsize){
    if(getWidthOfText.c === undefined){
        getWidthOfText.c=document.createElement('canvas');
        getWidthOfText.ctx=getWidthOfText.c.getContext('2d');
    }
    var fontspec = fontsize + ' ' + fontname;
    if(getWidthOfText.ctx.font !== fontspec)
        getWidthOfText.ctx.font = fontspec;
    return getWidthOfText.ctx.measureText(txt).width;
}

Or, as some of the other users have suggested, you can wrap it in a span element:

function getWidthOfText(txt, fontname, fontsize){
    if(getWidthOfText.e === undefined){
        getWidthOfText.e = document.createElement('span');
        getWidthOfText.e.style.display = "none";
        document.body.appendChild(getWidthOfText.e);
    }
    if(getWidthOfText.e.style.fontSize !== fontsize)
        getWidthOfText.e.style.fontSize = fontsize;
    if(getWidthOfText.e.style.fontFamily !== fontname)
        getWidthOfText.e.style.fontFamily = fontname;
    getWidthOfText.e.innerText = txt;
    return getWidthOfText.e.offsetWidth;
}

EDIT 2020: added font name+size caching at Igor Okorokov's suggestion.

Prevent flex items from overflowing a container

It's not suitable for every situation, because not all items can have a non-proportional maximum, but slapping a good ol' max-width on the offending element/container can put it back in line.

Reverse a string in Java

public static String reverseIt(String source) {
    int i, len = source.length();
    StringBuilder dest = new StringBuilder(len);

    for (i = (len - 1); i >= 0; i--){
        dest.append(source.charAt(i));
    }

    return dest.toString();
}

http://www.java2s.com/Code/Java/Language-Basics/ReverseStringTest.htm

what does -zxvf mean in tar -zxvf <filename>?

Instead of wading through the description of all the options, you can jump to 3.4.3 Short Options Cross Reference under the info tar command.

x means --extract. v means --verbose. f means --file. z means --gzip. You can combine one-letter arguments together, and f takes an argument, the filename. There is something you have to watch out for:

Short options' letters may be clumped together, but you are not required to do this (as compared to old options; see below). When short options are clumped as a set, use one (single) dash for them all, e.g., ''tar' -cvf'. Only the last option in such a set is allowed to have an argument(1).


This old way of writing 'tar' options can surprise even experienced users. For example, the two commands:

 tar cfz archive.tar.gz file
 tar -cfz archive.tar.gz file

are quite different. The first example uses 'archive.tar.gz' as the value for option 'f' and recognizes the option 'z'. The second example, however, uses 'z' as the value for option 'f' -- probably not what was intended.

check for null date in CASE statement, where have I gone wrong?

select Id, StartDate,
Case IsNull (StartDate , '01/01/1800')
When '01/01/1800' then
  'Awaiting'
Else
  'Approved'
END AS StartDateStatus
From MyTable

Converting Pandas dataframe into Spark dataframe error

I made this script, It worked for my 10 pandas Data frames

from pyspark.sql.types import *

# Auxiliar functions
def equivalent_type(f):
    if f == 'datetime64[ns]': return TimestampType()
    elif f == 'int64': return LongType()
    elif f == 'int32': return IntegerType()
    elif f == 'float64': return FloatType()
    else: return StringType()

def define_structure(string, format_type):
    try: typo = equivalent_type(format_type)
    except: typo = StringType()
    return StructField(string, typo)

# Given pandas dataframe, it will return a spark's dataframe.
def pandas_to_spark(pandas_df):
    columns = list(pandas_df.columns)
    types = list(pandas_df.dtypes)
    struct_list = []
    for column, typo in zip(columns, types): 
      struct_list.append(define_structure(column, typo))
    p_schema = StructType(struct_list)
    return sqlContext.createDataFrame(pandas_df, p_schema)

You can see it also in this gist

With this you just have to call spark_df = pandas_to_spark(pandas_df)

Groovy: How to check if a string contains any element of an array?

def valid = pointAddress.findAll { a ->
    validPointTypes.any { a.contains(it) }
}

Should do it

Remove '\' char from string c#

         while ((line = stringReader.ReadLine()) != null)
         {
             // split the lines
             for (int c = 0; c < line.Length; c++)
             {
                 line = line.Replace("\\", "");
                 lineBreakOne = line.Substring(1, c - 2);
                 lineBreakTwo = line.Substring(c + 2, line.Length - 2);
             }
         }

LIKE operator in LINQ

@adobrzyc had this great custom LIKE function - I just wanted to share the IEnumerable version of it.

public static class LinqEx
{
    private static readonly MethodInfo ContainsMethod = typeof(string).GetMethod("Contains");
    private static readonly MethodInfo StartsWithMethod = typeof(string).GetMethod("StartsWith", new[] { typeof(string) });
    private static readonly MethodInfo EndsWithMethod = typeof(string).GetMethod("EndsWith", new[] { typeof(string) });

    private static Func<TSource, bool> LikeExpression<TSource, TMember>(Expression<Func<TSource, TMember>> property, string value)
    {
        var param = Expression.Parameter(typeof(TSource), "t");
        var propertyInfo = GetPropertyInfo(property);
        var member = Expression.Property(param, propertyInfo.Name);

        var startWith = value.StartsWith("%");
        var endsWith = value.EndsWith("%");

        if (startWith)
            value = value.Remove(0, 1);

        if (endsWith)
            value = value.Remove(value.Length - 1, 1);

        var constant = Expression.Constant(value);
        Expression exp;

        if (endsWith && startWith)
        {
            exp = Expression.Call(member, ContainsMethod, constant);
        }
        else if (startWith)
        {
            exp = Expression.Call(member, EndsWithMethod, constant);
        }
        else if (endsWith)
        {
            exp = Expression.Call(member, StartsWithMethod, constant);
        }
        else
        {
            exp = Expression.Equal(member, constant);
        }

        return Expression.Lambda<Func<TSource, bool>>(exp, param).Compile();
    }

    public static IEnumerable<TSource> Like<TSource, TMember>(this IEnumerable<TSource> source, Expression<Func<TSource, TMember>> parameter, string value)
    {
        return source.Where(LikeExpression(parameter, value));
    }


    private static PropertyInfo GetPropertyInfo(Expression expression)
    {
        var lambda = expression as LambdaExpression;
        if (lambda == null)
            throw new ArgumentNullException("expression");

        MemberExpression memberExpr = null;

        switch (lambda.Body.NodeType)
        {
            case ExpressionType.Convert:
                memberExpr = ((UnaryExpression)lambda.Body).Operand as MemberExpression;
                break;
            case ExpressionType.MemberAccess:
                memberExpr = lambda.Body as MemberExpression;
                break;
        }

        if (memberExpr == null)
            throw new InvalidOperationException("Specified expression is invalid. Unable to determine property info from expression.");


        var output = memberExpr.Member as PropertyInfo;

        if (output == null)
            throw new InvalidOperationException("Specified expression is invalid. Unable to determine property info from expression.");

        return output;
    }
}

Plotting of 1-dimensional Gaussian distribution function

The correct form, based on the original syntax, and correctly normalized is:

def gaussian(x, mu, sig):
    return 1./(np.sqrt(2.*np.pi)*sig)*np.exp(-np.power((x - mu)/sig, 2.)/2)

How to change password using TortoiseSVN?

On the server.. In our environment, we're running Apache2 on Windows Server 2003.
Suppose Apache is serving our repository from C:\repo\MyProject

The actual repository is in C:\repo\MyProject\db

and the configuration is in C:\repo\MyProject\conf

So the passwords are in: C:\repo\MyProject.htaccess

They're encrypted, a tool similar to this: http://tools.dynamicdrive.com/password/

How to convert a python numpy array to an RGB image with Opencv 2.4?

You are looking for scipy.misc.toimage:

import scipy.misc
rgb = scipy.misc.toimage(np_array)

It seems to be also in scipy 1.0, but has a deprecation warning. Instead, you can use pillow and PIL.Image.fromarray

Hash function that produces short hashes?

If you need "sub-10-character hash" you could use Fletcher-32 algorithm which produces 8 character hash (32 bits), CRC-32 or Adler-32.

CRC-32 is slower than Adler32 by a factor of 20% - 100%.

Fletcher-32 is slightly more reliable than Adler-32. It has a lower computational cost than the Adler checksum: Fletcher vs Adler comparison.

A sample program with a few Fletcher implementations is given below:

    #include <stdio.h>
    #include <string.h>
    #include <stdint.h> // for uint32_t

    uint32_t fletcher32_1(const uint16_t *data, size_t len)
    {
            uint32_t c0, c1;
            unsigned int i;

            for (c0 = c1 = 0; len >= 360; len -= 360) {
                    for (i = 0; i < 360; ++i) {
                            c0 = c0 + *data++;
                            c1 = c1 + c0;
                    }
                    c0 = c0 % 65535;
                    c1 = c1 % 65535;
            }
            for (i = 0; i < len; ++i) {
                    c0 = c0 + *data++;
                    c1 = c1 + c0;
            }
            c0 = c0 % 65535;
            c1 = c1 % 65535;
            return (c1 << 16 | c0);
    }

    uint32_t fletcher32_2(const uint16_t *data, size_t l)
    {
        uint32_t sum1 = 0xffff, sum2 = 0xffff;

        while (l) {
            unsigned tlen = l > 359 ? 359 : l;
            l -= tlen;
            do {
                sum2 += sum1 += *data++;
            } while (--tlen);
            sum1 = (sum1 & 0xffff) + (sum1 >> 16);
            sum2 = (sum2 & 0xffff) + (sum2 >> 16);
        }
        /* Second reduction step to reduce sums to 16 bits */
        sum1 = (sum1 & 0xffff) + (sum1 >> 16);
        sum2 = (sum2 & 0xffff) + (sum2 >> 16);
        return (sum2 << 16) | sum1;
    }

    int main()
    {
        char *str1 = "abcde";  
        char *str2 = "abcdef";

        size_t len1 = (strlen(str1)+1) / 2; //  '\0' will be used for padding 
        size_t len2 = (strlen(str2)+1) / 2; // 

        uint32_t f1 = fletcher32_1(str1,  len1);
        uint32_t f2 = fletcher32_2(str1,  len1);

        printf("%u %X \n",    f1,f1);
        printf("%u %X \n\n",  f2,f2);

        f1 = fletcher32_1(str2,  len2);
        f2 = fletcher32_2(str2,  len2);

        printf("%u %X \n",f1,f1);
        printf("%u %X \n",f2,f2);

        return 0;
    }

Output:

4031760169 F04FC729                                                                                                                                                                                                                              
4031760169 F04FC729                                                                                                                                                                                                                              

1448095018 56502D2A                                                                                                                                                                                                                              
1448095018 56502D2A                                                                                                                                                                                                                              

Agrees with Test vectors:

"abcde"  -> 4031760169 (0xF04FC729)
"abcdef" -> 1448095018 (0x56502D2A)

Adler-32 has a weakness for short messages with few hundred bytes, because the checksums for these messages have a poor coverage of the 32 available bits. Check this:

The Adler32 algorithm is not complex enough to compete with comparable checksums.

how to re-format datetime string in php?

https://en.functions-online.com/date.html?command={"format":"l jS \\of F Y h:i:s A"}

ORA-30926: unable to get a stable set of rows in the source tables

I was not able to resolve this after several hours. Eventually I just did a select with the two tables joined, created an extract and created individual SQL update statements for the 500 rows in the table. Ugly but beats spending hours trying to get a query to work.

Append text using StreamWriter

Also look at log4net, which makes logging to 1 or more event stores — whether it's the console, the Windows event log, a text file, a network pipe, a SQL database, etc. — pretty trivial. You can even filter stuff in its configuration, for instance, so that only log records of a particular severity (say ERROR or FATAL) from a single component or assembly are directed to a particular event store.

http://logging.apache.org/log4net/

Rails 4 - passing variable to partial

Syntactically a little different but it looks cleaner in my opinion:

render 'my_partial', locals: { title: "My awesome title" }

# not a big fan of the arrow key syntax
render 'my_partial', :locals => { :title => "My awesome title" }

Regular Expressions and negating a whole character group

Using a regex as you described is the simple way (as far as I am aware). If you want a range you could use [^a-f].

Check if an element is a child of a parent

Ended up using .closest() instead.

$(document).on("click", function (event) {
    if($(event.target).closest(".CustomControllerMainDiv").length == 1)
    alert('element is a child of the custom controller')
});

how to remove key+value from hash in javascript

Another option may be this John Resig remove method. can better fit what you need. if you know the index in the array.

how to delete files from amazon s3 bucket?

I'm surprised there isn't this easy way : key.delete() :

from boto.s3.connection import S3Connection, Bucket, Key

conn = S3Connection(AWS_ACCESS_KEY, AWS_SECERET_KEY)
bucket = Bucket(conn, S3_BUCKET_NAME)
k = Key(bucket = bucket, name=path_to_file)
k.delete()

C#: Dynamic runtime cast

I think you're confusing the issues of casting and converting here.

  • Casting: The act of changing the type of a reference which points to an object. Either moving up or down the object hierarchy or to an implemented interface
  • Converting: Creating a new object from the original source object of a different type and accessing it through a reference to that type.

It's often hard to know the difference between the 2 in C# because both of them use the same C# operator: the cast.

In this situation you are almost certainly not looking for a cast operation. Casting a dynamic to another dynamic is essentially an identity conversion. It provides no value because you're just getting a dynamic reference back to the same underlying object. The resulting lookup would be no different.

Instead what you appear to want in this scenario is a conversion. That is morphing the underlying object to a different type and accessing the resulting object in a dynamic fashion. The best API for this is Convert.ChangeType.

public static dynamic Convert(dynamic source, Type dest) {
  return Convert.ChangeType(source, dest);
}

EDIT

The updated question has the following line:

obj definitely implements castTo

If this is the case then the Cast method doesn't need to exist. The source object can simply be assigned to a dynamic reference.

dynamic d = source;

It sounds like what you're trying to accomplish is to see a particular interface or type in the hierarchy of source through a dynamic reference. That is simply not possible. The resulting dynamic reference will see the implementation object directly. It doesn't look through any particular type in the hierarchy of source. So the idea of casting to a different type in the hierarchy and then back to dynamic is exactly identical to just assigning to dynamic in the first place. It will still point to the same underlying object.

Disabling tab focus on form elements

Similar to Yipio, I added notab="notab" as an attribute to any element I wanted to disable the tab too. My jQuery is then one line.

$('input[notab=notab]').on('keydown', function(e){ if (e.keyCode == 9)  e.preventDefault() });

Btw, keypress doesn't work for many control keys.

Relay access denied on sending mail, Other domain outside of network

Set your SMTP auth to true if using the PHPmailer class:

$mail->SMTPAuth = true;

Possible to change where Android Virtual Devices are saved?

Another way to specify ANDROID_SDK_HOME without messing around with environment variables (especially when using ec2) is simply create a shortcut of eclipse and add the following as target

C:\Windows\System32\cmd.exe /C "setx ANDROID_SDK_HOME YOUR AVD PATH /M & YOUR ECLIPSE.EXE PATH"

This will set ANDROID_SDK_HOME as system variable whenever you launch eclipse.

HTH Paul

Make XAMPP / Apache serve file outside of htdocs folder

You can set Apache to serve pages from anywhere with any restrictions but it's normally distributed in a more secure form.

Editing your apache files (http.conf is one of the more common names) will allow you to set any folder so it appears in your webroot.

EDIT:

alias myapp c:\myapp\

I've edited my answer to include the format for creating an alias in the http.conf file which is sort of like a shortcut in windows or a symlink under un*x where Apache 'pretends' a folder is in the webroot. This is probably going to be more useful to you in the long term.

How do I disable the security certificate check in Python requests

From the documentation:

requests can also ignore verifying the SSL certificate if you set verify to False.

>>> requests.get('https://kennethreitz.com', verify=False)
<Response [200]>

If you're using a third-party module and want to disable the checks, here's a context manager that monkey patches requests and changes it so that verify=False is the default and suppresses the warning.

import warnings
import contextlib

import requests
from urllib3.exceptions import InsecureRequestWarning


old_merge_environment_settings = requests.Session.merge_environment_settings

@contextlib.contextmanager
def no_ssl_verification():
    opened_adapters = set()

    def merge_environment_settings(self, url, proxies, stream, verify, cert):
        # Verification happens only once per connection so we need to close
        # all the opened adapters once we're done. Otherwise, the effects of
        # verify=False persist beyond the end of this context manager.
        opened_adapters.add(self.get_adapter(url))

        settings = old_merge_environment_settings(self, url, proxies, stream, verify, cert)
        settings['verify'] = False

        return settings

    requests.Session.merge_environment_settings = merge_environment_settings

    try:
        with warnings.catch_warnings():
            warnings.simplefilter('ignore', InsecureRequestWarning)
            yield
    finally:
        requests.Session.merge_environment_settings = old_merge_environment_settings

        for adapter in opened_adapters:
            try:
                adapter.close()
            except:
                pass

Here's how you use it:

with no_ssl_verification():
    requests.get('https://wrong.host.badssl.com/')
    print('It works')

    requests.get('https://wrong.host.badssl.com/', verify=True)
    print('Even if you try to force it to')

requests.get('https://wrong.host.badssl.com/', verify=False)
print('It resets back')

session = requests.Session()
session.verify = True

with no_ssl_verification():
    session.get('https://wrong.host.badssl.com/', verify=True)
    print('Works even here')

try:
    requests.get('https://wrong.host.badssl.com/')
except requests.exceptions.SSLError:
    print('It breaks')

try:
    session.get('https://wrong.host.badssl.com/')
except requests.exceptions.SSLError:
    print('It breaks here again')

Note that this code closes all open adapters that handled a patched request once you leave the context manager. This is because requests maintains a per-session connection pool and certificate validation happens only once per connection so unexpected things like this will happen:

>>> import requests
>>> session = requests.Session()
>>> session.get('https://wrong.host.badssl.com/', verify=False)
/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py:857: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning)
<Response [200]>
>>> session.get('https://wrong.host.badssl.com/', verify=True)
/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py:857: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning)
<Response [200]>

INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE

MySQL will assume the part before the equals references the columns named in the INSERT INTO clause, and the second part references the SELECT columns.

INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct, 
                inact, inadur, inadist, 
                smlct, smldur, smldist, 
                larct, lardur, lardist, 
                emptyct, emptydur)
SELECT id, uid, t.location, t.animal, t.starttime, t.endtime, t.entct, 
       t.inact, t.inadur, t.inadist, 
       t.smlct, t.smldur, t.smldist, 
       t.larct, t.lardur, t.lardist, 
       t.emptyct, t.emptydur 
FROM tmp t WHERE uid=x
ON DUPLICATE KEY UPDATE entct=t.entct, inact=t.inact, ...

Javascript Click on Element by Class

If you want to click on all elements selected by some class, you can use this example (used on last.fm on the Loved tracks page to Unlove all).

var divs = document.querySelectorAll('.love-button.love-button--loved'); 

for (i = 0; i < divs.length; ++i) {
  divs[i].click();
};

With ES6 and Babel (cannot be run in the browser console directly)

[...document.querySelectorAll('.love-button.love-button--loved')]
   .forEach(div => { div.click(); })

How to access environment variable values?

To check if the key exists (returns True or False)

'HOME' in os.environ

You can also use get() when printing the key; useful if you want to use a default.

print(os.environ.get('HOME', '/home/username/'))

where /home/username/ is the default

How to perform Join between multiple tables in LINQ lambda

What you've seen is what you get - and it's exactly what you asked for, here:

(ppc, c) => new { productproductcategory = ppc, category = c}

That's a lambda expression returning an anonymous type with those two properties.

In your CategorizedProducts, you just need to go via those properties:

CategorizedProducts catProducts = query.Select(
      m => new { 
             ProdId = m.productproductcategory.product.Id, 
             CatId = m.category.CatId, 
             // other assignments 
           });

How do I remove files saying "old mode 100755 new mode 100644" from unstaged changes in Git?

This usually happens when the repo is cloned between Windows and Linux/Unix machines.

Just tell git to ignore filemode change. Here are several ways to do so:

  1. Config ONLY for current repo:

     git config core.filemode false
    
  2. Config globally:

     git config --global core.filemode false
    
  3. Add in ~/.gitconfig:

     [core]
          filemode = false
    

Just select one of them.

What is the size of an enum in C?

Consider this code:

enum value{a,b,c,d,e,f,g,h,i,j,l,m,n};
value s;
cout << sizeof(s) << endl;

It will give 4 as output. So no matter the number of elements an enum contains, its size is always fixed.

Homebrew: Could not symlink, /usr/local/bin is not writable

If you go to the folder in finder, right click and select "Get Info" you can go to the "Sharing and Permissions" section for the folder and allow "Read & Write" to "everyone"

This is what I do to make symlinks pass with this error. Also brew seems to reset the permissions on the folder also as if you hadn't altered anything

Ordering issue with date values when creating pivot tables

Your problem is that excel does not recognize your text strings of "mm/dd/yyyy" as date objects in it's internal memory. Therefore when you create pivottable it doesn't consider these strings to be dates.

You'll need to first convert your dates to actual date values before creating the pivottable. This is a good resource for that: http://office.microsoft.com/en-us/excel-help/convert-dates-stored-as-text-to-dates-HP001162867.aspx

In your spreadsheet I created a second date column in B with the formula =DATEVALUE(A2). Creating a pivot table with this new date column and Count of Sales then sorts correctly in the pivot table (option becomes Sort Oldest to Newest instead of Sort A to Z).

Load Image from javascript

<span>
    <img id="my_image" src="#" />
</span>

<span class="spanloader">

    <span>set Loading Image Image</span>


</span>

<input type="button" id="btnnext" value="Next" />


<script type="text/javascript">

    $('#btnnext').click(function () {
        $(".spanloader").hide();
        $("#my_image").attr("src", "1.jpg");
    });

</script>

Change value of variable with dplyr

We can use replace to change the values in 'mpg' to NA that corresponds to cyl==4.

mtcars %>%
     mutate(mpg=replace(mpg, cyl==4, NA)) %>%
     as.data.frame()

TLS 1.2 not working in cURL

TLS 1.1 and TLS 1.2 are supported since OpenSSL 1.0.1

Forcing TLS 1.1 and 1.2 are only supported since curl 7.34.0

You should consider an upgrade.

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

There are several other posts about this now and they all point to enabling TLS 1.2. Anything less is unsafe.

You can do this in .NET 3.5 with a patch.
You can do this in .NET 4.0 and 4.5 with a single line of code

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // .NET 4.5
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; // .NET 4.0

In .NET 4.6, it automatically uses TLS 1.2.

See here for more details: .NET support for TLS

BAT file to open CMD in current directory

this code works for me name it cmd.bat

@echo off
title This is Only A Test
echo.
:Loop
set /p the="%cd%"
%the%
echo.
goto loop

Android background music service

Do it without service

https://web.archive.org/web/20181116173307/http://www.rbgrn.net/content/307-light-racer-20-days-61-64-completion

If you are so serious about doing it with services using mediaplayer

Intent svc=new Intent(this, BackgroundSoundService.class);
startService(svc);

public class BackgroundSoundService extends Service {
    private static final String TAG = null;
    MediaPlayer player;
    public IBinder onBind(Intent arg0) {

        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        player = MediaPlayer.create(this, R.raw.idil);
        player.setLooping(true); // Set looping
        player.setVolume(100,100);

    }
    public int onStartCommand(Intent intent, int flags, int startId) {
        player.start();
        return 1;
    }

    public void onStart(Intent intent, int startId) {
        // TO DO
    }
    public IBinder onUnBind(Intent arg0) {
        // TO DO Auto-generated method
        return null;
    }

    public void onStop() {

    }
    public void onPause() {

    }
    @Override
    public void onDestroy() {
        player.stop();
        player.release();
    }

    @Override
    public void onLowMemory() {

    }
}

Please call this service in Manifest Make sure there is no space at the end of the .BackgroundSoundService string

<service android:enabled="true" android:name=".BackgroundSoundService" />

Java - removing first character of a string

I came across a situation where I had to remove not only the first character (if it was a #, but the first set of characters.

String myString = ###Hello World could be the starting point, but I would only want to keep the Hello World. this could be done as following.

while (myString.charAt(0) == '#') { // Remove all the # chars in front of the real string
    myString = myString.substring(1, myString.length());
}

For OP's case, replace while with if and it works aswell.

Difference between 'cls' and 'self' in Python classes?

This is very good question but not as wanting as question. There is difference between 'self' and 'cls' used method though analogically they are at same place

def moon(self, moon_name):
    self.MName = moon_name

#but here cls method its use is different 

@classmethod
def moon(cls, moon_name):
    instance = cls()
    instance.MName = moon_name

Now you can see both are moon function but one can be used inside class while other function name moon can be used for any class.

For practical programming approach :

While designing circle class we use area method as cls instead of self because we don't want area to be limited to particular class of circle only .

How to pass parameters to ThreadStart method in Thread?

Look at this example:

public void RunWorker()
{
    Thread newThread = new Thread(WorkerMethod);
    newThread.Start(new Parameter());
}

public void WorkerMethod(object parameterObj)
{
    var parameter = (Parameter)parameterObj;
    // do your job!
}

You are first creating a thread by passing delegate to worker method and then starts it with a Thread.Start method which takes your object as parameter.

So in your case you should use it like this:

    Thread thread = new Thread(download);
    thread.Start(filename);

But your 'download' method still needs to take object, not string as a parameter. You can cast it to string in your method body.

How do I iterate over the words of a string?

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>

int main() {
    using namespace std;
   int n=8;
    string sentence = "10 20 30 40 5 6 7 8";
    istringstream iss(sentence);

  vector<string> tokens;
copy(istream_iterator<string>(iss),
     istream_iterator<string>(),
     back_inserter(tokens));

     for(int i=0;i<n;i++){
        cout<<tokens.at(i);
     }


}