Programs & Examples On #Locale

In computing, locale is a set of parameters that defines the user's language, country and any special variant preferences that the user wants to see in their user interface. Usually a locale identifier consists of at least a language identifier and a region identifier.

SimpleDateFormat and locale based format string

Java 8 Style for a given date

LocalDate today = LocalDate.of(1982, Month.AUGUST, 31);
System.out.println(today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(Locale.ENGLISH)));
System.out.println(today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(Locale.FRENCH)));
System.out.println(today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(Locale.JAPANESE)));

Setting java locale settings

You could call during init or whatever Locale.setDefault() or -Duser.language=, -Duser.country=, and -Duser.variant= at the command line. Here's something on Sun's site.

List of All Locales and Their Short Codes?

From http://www.w3.org/International/articles/language-tags/

"Language tag syntax is defined by the IETF's BCP 47. BCP stands for 'Best Current Practice', and is a persistent name for a series of RFCs whose numbers change as they are updated. The latest RFC describing language tag syntax is RFC 5646, Tags for the Identification of Languages, and it obsoletes the older RFCs 4646, 3066 and 1766.

You used to find subtags by consulting the lists of codes in various ISO standards, but now you can find all subtags in the IANA Language Subtag Registry."

AFAIK most locale-aware applications (that are written by professionals) abide by this standard. It isn't just something somebody threw together and that different people interpret differently.

I'd strongly suggest you investigate the internationalization features of your particular development language, as you'll probably end up reinventing the wheel if you don't.

How can I get my Android device country code without using GPS?

I have created a utility function (tested once on a device where I was getting an incorrect country code based on locale).

Reference: CountryCodePicker.java

fun getDetectedCountry(context: Context, defaultCountryIsoCode: String): String {

    detectSIMCountry(context)?.let {
        return it
    }

    detectNetworkCountry(context)?.let {
        return it
    }

    detectLocaleCountry(context)?.let {
        return it
    }

    return defaultCountryIsoCode
}

private fun detectSIMCountry(context: Context): String? {
    try {
        val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        Log.d(TAG, "detectSIMCountry: ${telephonyManager.simCountryIso}")
        return telephonyManager.simCountryIso
    }
    catch (e: Exception) {
        e.printStackTrace()
    }
    return null
}

private fun detectNetworkCountry(context: Context): String? {
    try {
        val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        Log.d(TAG, "detectNetworkCountry: ${telephonyManager.simCountryIso}")
        return telephonyManager.networkCountryIso
    }
    catch (e: Exception) {
        e.printStackTrace()
    }
    return null
}

private fun detectLocaleCountry(context: Context): String? {
    try {
        val localeCountryISO = context.getResources().getConfiguration().locale.getCountry()
        Log.d(TAG, "detectNetworkCountry: $localeCountryISO")
        return localeCountryISO
    }
    catch (e: Exception) {
        e.printStackTrace()
    }
    return null
}

Python locale error: unsupported locale setting

If I were you, I would use BABEL: http://babel.pocoo.org/en/latest/index.html

I got the same issue here using Docker, I've tried every single step and didn't work well, always getting locale error, so I decided to use BABEL, and everything worked well.

How can I format date by locale in Java?

Take a look at java.text.DateFormat. Easier to use (with a bit less power) is the derived class, java.text.SimpleDateFormat

And here is a good intro to Java internationalization: http://java.sun.com/docs/books/tutorial/i18n/index.html (the "Formatting" section addressing your problem, and more).

How to fix a locale setting warning from Perl

For macOS & Mac OS X users only

I was getting the same warning while using Git

To resolve this warning Uncheck the Set locale environment variable on startup option and restart your terminal. Below screen shot represents my terminal settings.

enter image description here

How can I convert an Integer to localized month name in Java?

tl;dr

Month.of( yourMonthNumber )           // Represent a month by its number, 1-12 for January-December. 
  .getDisplayName(                    // Generate text of the name of the month automatically localized. 
      TextStyle.SHORT_STANDALONE ,    // Specify how long or abbreviated the name of month should be.
      new Locale( "es" , "MX" )       // Locale determines (a) the human language used in translation, and (b) the cultural norms used in deciding issues of abbreviation, capitalization, punctuation, and so on.
  )                                   // Returns a String.

java.time.Month

Much easier to do now in the java.time classes that supplant these troublesome old legacy date-time classes.

The Month enum defines a dozen objects, one for each month.

The months are numbered 1-12 for January-December.

Month month = Month.of( 2 );  // 2 ? February.

Ask the object to generate a String of the name of the month, automatically localized.

Adjust the TextStyle to specify how long or abbreviated you want the name. Note that in some languages (not English) the month name varies if used alone or as part of a complete date. So each text style has a …_STANDALONE variant.

Specify a Locale to determine:

  • Which human language should be used in translation.
  • What cultural norms should decide issues such as abbreviation, punctuation, and capitalization.

Example:

Locale l = new Locale( "es" , "MX" );
String output = Month.FEBRUARY.getDisplayName( TextStyle.SHORT_STANDALONE , l );  // Or Locale.US, Locale.CANADA_FRENCH. 

Name ? Month object

FYI, going the other direction (parsing a name-of-month string to get a Month enum object) is not built-in. You could write your own class to do so. Here is my quick attempt at such a class. Use at your own risk. I gave this code no serious thought nor any serious testing.

Usage.

Month m = MonthDelocalizer.of( Locale.CANADA_FRENCH ).parse( "janvier" ) ;  // Month.JANUARY

Code.

package com.basilbourque.example;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.time.Month;
import java.time.format.TextStyle;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

// For a given name of month in some language, determine the matching `java.time.Month` enum object.
// This class is the opposite of `Month.getDisplayName` which generates a localized string for a given `Month` object.
// Usage… MonthDelocalizer.of( Locale.CANADA_FRENCH ).parse( "janvier" ) ? Month.JANUARY
// Assumes `FormatStyle.FULL`, for names without abbreviation.
// About `java.time.Month` enum: https://docs.oracle.com/javase/9/docs/api/java/time/Month.html
// USE AT YOUR OWN RISK. Provided without guarantee or warranty. No serious testing or code review was performed.
public class MonthDelocalizer
{
    @NotNull
    private Locale locale;

    @NotNull
    private List < String > monthNames, monthNamesStandalone; // Some languages use an alternate spelling for a “standalone” month name used without the context of a date.

    // Constructor. Private, for static factory method.
    private MonthDelocalizer ( @NotNull Locale locale )
    {
        this.locale = locale;

        // Populate the pair of arrays, each having the translated month names.
        int countMonthsInYear = 12; // Twelve months in the year.
        this.monthNames = new ArrayList <>( countMonthsInYear );
        this.monthNamesStandalone = new ArrayList <>( countMonthsInYear );

        for ( int i = 1 ; i <= countMonthsInYear ; i++ )
        {
            this.monthNames.add( Month.of( i ).getDisplayName( TextStyle.FULL , this.locale ) );
            this.monthNamesStandalone.add( Month.of( i ).getDisplayName( TextStyle.FULL_STANDALONE , this.locale ) );
        }
//        System.out.println( this.monthNames );
//        System.out.println( this.monthNamesStandalone );
    }

    // Constructor. Private, for static factory method.
    // Personally, I think it unwise to default implicitly to a `Locale`. But I included this in case you disagree with me, and to follow the lead of the *java.time* classes. --Basil Bourque
    private MonthDelocalizer ( )
    {
        this( Locale.getDefault() );
    }

    // static factory method, instead of  constructors.
    // See article by Dr. Joshua Bloch. http://www.informit.com/articles/article.aspx?p=1216151
    // The `Locale` argument determines the human language and cultural norms used in de-localizing input strings.
    synchronized static public MonthDelocalizer of ( @NotNull Locale localeArg )
    {
        MonthDelocalizer x = new MonthDelocalizer( localeArg ); // This class could be optimized by caching this object.
        return x;
    }

    // Attempt to translate the name of a month to look-up a matching `Month` enum object.
    // Returns NULL if the passed String value is not found to be a valid name of month for the human language and cultural norms of the `Locale` specified when constructing this parent object, `MonthDelocalizer`.
    @Nullable
    public Month parse ( @NotNull String input )
    {
        int index = this.monthNames.indexOf( input );
        if ( - 1 == index )
        { // If no hit in the contextual names, try the standalone names.
            index = this.monthNamesStandalone.indexOf( input );
        }
        int ordinal = ( index + 1 );
        Month m = ( ordinal > 0 ) ? Month.of( ordinal ) : null;  // If we have a hit, determine the `Month` enum object. Else return null.
        if ( null == m )
        {
            throw new java.lang.IllegalArgumentException( "The passed month name: ‘" + input + "’ is not valid for locale: " + this.locale.toString() );
        }
        return m;
    }

    // `Object` class overrides.

    @Override
    public boolean equals ( Object o )
    {
        if ( this == o ) return true;
        if ( o == null || getClass() != o.getClass() ) return false;

        MonthDelocalizer that = ( MonthDelocalizer ) o;

        return locale.equals( that.locale );
    }

    @Override
    public int hashCode ( )
    {
        return locale.hashCode();
    }

    public static void main ( String[] args )
    {
        // Usage example:
        MonthDelocalizer monthDelocJapan = MonthDelocalizer.of( Locale.JAPAN );
        try
        {
            Month m = monthDelocJapan.parse( "pink elephant" ); // Invalid input.
        } catch ( IllegalArgumentException e )
        {
            // … handle error
            System.out.println( "ERROR: " + e.getLocalizedMessage() );
        }

        // Ignore exception. (not recommended)
        if ( MonthDelocalizer.of( Locale.CANADA_FRENCH ).parse( "janvier" ).equals( Month.JANUARY ) )
        {
            System.out.println( "GOOD - In locale "+Locale.CANADA_FRENCH+", the input ‘janvier’ parses to Month.JANUARY." );
        }
    }
}

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Set Locale programmatically

For those who tried everything but not not working. Please check that if you set darkmode with AppCompatDelegate.setDefaultNightMode and the system is not dark, then Configuration.setLocale will not work above Andorid 7.0.

Add this code in your every activity to solve this issue:

override fun applyOverrideConfiguration(overrideConfiguration: Configuration?) {
  if (overrideConfiguration != null) {
    val uiMode = overrideConfiguration.uiMode
    overrideConfiguration.setTo(baseContext.resources.configuration)
    overrideConfiguration.uiMode = uiMode
  }
  super.applyOverrideConfiguration(overrideConfiguration)
}

Android get current Locale, not default

From getDefault's documentation:

Returns the user's preferred locale. This may have been overridden for this process with setDefault(Locale).

Also from the Locale docs:

The default locale is appropriate for tasks that involve presenting data to the user.

Seems like you should just use it.

How to get Locale from its String representation in Java?

See the Locale.getLanguage(), Locale.getCountry()... Store this combination in the database instead of the "programatic name"...
When you want to build the Locale back, use public Locale(String language, String country)

Here is a sample code :)

// May contain simple syntax error, I don't have java right now to test..
// but this is a bigger picture for your algo...
public String localeToString(Locale l) {
    return l.getLanguage() + "," + l.getCountry();
}

public Locale stringToLocale(String s) {
    StringTokenizer tempStringTokenizer = new StringTokenizer(s,",");
    if(tempStringTokenizer.hasMoreTokens())
    String l = tempStringTokenizer.nextElement();
    if(tempStringTokenizer.hasMoreTokens())
    String c = tempStringTokenizer.nextElement();
    return new Locale(l,c);
}

Changing Locale within the app itself

Through the original question is not exactly about the locale itself all other locale related questions are referencing to this one. That's why I wanted to clarify the issue here. I used this question as a starting point for my own locale switching code and found out that the method is not exactly correct. It works, but only until any configuration change (e.g. screen rotation) and only in that particular Activity. Playing with a code for a while I have ended up with the following approach:

I have extended android.app.Application and added the following code:

public class MyApplication extends Application
{
    private Locale locale = null;

    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        super.onConfigurationChanged(newConfig);
        if (locale != null)
        {
            newConfig.locale = locale;
            Locale.setDefault(locale);
            getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics());
        }
    }

    @Override
    public void onCreate()
    {
        super.onCreate();

        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);

        Configuration config = getBaseContext().getResources().getConfiguration();

        String lang = settings.getString(getString(R.string.pref_locale), "");
        if (! "".equals(lang) && ! config.locale.getLanguage().equals(lang))
        {
            locale = new Locale(lang);
            Locale.setDefault(locale);
            config.locale = locale;
            getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
        }
    }
}

This code ensures that every Activity will have custom locale set and it will not be reset on rotation and other events.

I have also spent a lot of time trying to make the preference change to be applied immediately but didn't succeed: the language changed correctly on Activity restart, but number formats and other locale properties were not applied until full application restart.

Changes to AndroidManifest.xml

Don't forget to add android:configChanges="layoutDirection|locale" to every activity at AndroidManifest, as well as the android:name=".MyApplication" to the <application> element.

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

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

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

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

Submitting HTML form using Jquery AJAX

If you add:

jquery.form.min.js

You can simply do this:

<script>
$('#myform').ajaxForm(function(response) {
  alert(response);
});

// this will register the AJAX for <form id="myform" action="some_url">
// and when you submit the form using <button type="submit"> or $('myform').submit(), then it will send your request and alert response
</script>

NOTE:

You could use simple $('FORM').serialize() as suggested in post above, but that will not work for FILE INPUTS... ajaxForm() will.

Python string prints as [u'String']

If accessing/printing single element lists (e.g., sequentially or filtered):

my_list = [u'String'] # sample element
my_list = [str(my_list[0])]

SimpleDateFormat parse loses timezone

OP's solution to his problem, as he says, has dubious output. That code still shows confusion about representations of time. To clear up this confusion, and make code that won't lead to wrong times, consider this extension of what he did:

public static void _testDateFormatting() {
    SimpleDateFormat sdfGMT1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    sdfGMT1.setTimeZone(TimeZone.getTimeZone("GMT"));
    SimpleDateFormat sdfGMT2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
    sdfGMT2.setTimeZone(TimeZone.getTimeZone("GMT"));

    SimpleDateFormat sdfLocal1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    SimpleDateFormat sdfLocal2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");

    try {
        Date d = new Date();
        String s1 = d.toString();
        String s2 = sdfLocal1.format(d);
        // Store s3 or s4 in database.
        String s3 = sdfGMT1.format(d);
        String s4 = sdfGMT2.format(d);
        // Retrieve s3 or s4 from database, using LOCAL sdf.
        String s5 = sdfLocal1.parse(s3).toString();
        //EXCEPTION String s6 = sdfLocal2.parse(s3).toString();
        String s7 = sdfLocal1.parse(s4).toString();
        String s8 = sdfLocal2.parse(s4).toString();
        // Retrieve s3 from database, using GMT sdf.
        // Note that this is the SAME sdf that created s3.
        Date d2 = sdfGMT1.parse(s3);
        String s9 = d2.toString();
        String s10 = sdfGMT1.format(d2);
        String s11 = sdfLocal2.format(d2);
    } catch (Exception e) {
        e.printStackTrace();
    }       
}

examining values in a debugger:

s1  "Mon Sep 07 06:11:53 EDT 2015" (id=831698113128)    
s2  "2015.09.07 06:11:53" (id=831698114048) 
s3  "2015.09.07 10:11:53" (id=831698114968) 
s4  "2015.09.07 10:11:53 GMT+00:00" (id=831698116112)   
s5  "Mon Sep 07 10:11:53 EDT 2015" (id=831698116944)    
s6  -- omitted, gave parse exception    
s7  "Mon Sep 07 10:11:53 EDT 2015" (id=831698118680)    
s8  "Mon Sep 07 06:11:53 EDT 2015" (id=831698119584)    
s9  "Mon Sep 07 06:11:53 EDT 2015" (id=831698120392)    
s10 "2015.09.07 10:11:53" (id=831698121312) 
s11 "2015.09.07 06:11:53 EDT" (id=831698122256) 

sdf2 and sdfLocal2 include time zone, so we can see what is really going on. s1 & s2 are at 06:11:53 in zone EDT. s3 & s4 are at 10:11:53 in zone GMT -- equivalent to the original EDT time. Imagine we save s3 or s4 in a data base, where we are using GMT for consistency, so we can have times from anywhere in the world, without storing different time zones.

s5 parses the GMT time, but treats it as a local time. So it says "10:11:53" -- the GMT time -- but thinks it is 10:11:53 in local time. Not good.

s7 parses the GMT time, but ignores the GMT in the string, so still treats it as a local time.

s8 works, because now we include GMT in the string, and the local zone parser uses it to convert from one time zone to another.

Now suppose you don't want to store the zone, you want to be able to parse s3, but display it as a local time. The answer is to parse using the same time zone it was stored in -- so use the same sdf as it was created in, sdfGMT1. s9, s10, & s11 are all representations of the original time. They are all "correct". That is, d2 == d1. Then it is only a question of how you want to DISPLAY it. If you want to display what is stored in DB -- GMT time -- then you need to format it using a GMT sdf. Ths is s10.

So here is the final solution, if you don't want to explicitly store with " GMT" in the string, and want to display in GMT format:

public static void _testDateFormatting() {
    SimpleDateFormat sdfGMT1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    sdfGMT1.setTimeZone(TimeZone.getTimeZone("GMT"));

    try {
        Date d = new Date();
        String s3 = sdfGMT1.format(d);
        // Store s3 in DB.
        // ...
        // Retrieve s3 from database, using GMT sdf.
        Date d2 = sdfGMT1.parse(s3);
        String s10 = sdfGMT1.format(d2);
    } catch (Exception e) {
        e.printStackTrace();
    }       
}

Freeze the top row for an html table only (Fixed Table Header Scrolling)

You can use CSS position: sticky; for the first row of the table MDN ref:

.table-class tr:first-child>td{
    position: sticky;
    top: 0;
}

python mpl_toolkits installation issue

if anyone has a problem on Mac, can try this

sudo pip install --upgrade matplotlib --ignore-installed six

Anonymous method in Invoke call

Actually you do not need to use delegate keyword. Just pass lambda as parameter:

control.Invoke((MethodInvoker)(() => {this.Text = "Hi"; }));

Changing one character in a string

if your world is 100% ascii/utf-8(a lot of use cases fit in that box):

b = bytearray(s, 'utf-8')
# process - e.g., lowercasing: 
#    b[0] = b[i+1] - 32
s = str(b, 'utf-8')

python 3.7.3

Google Play on Android 4.0 emulator

For future visitors.

As of now Android 4.2.2 platform includes Google Play services. Just use an emulator running Jelly Bean. Details can be found here:

Setup Google Play Services SDK

EDIT:

Another option is to use Genymotion (runs way faster)

EDIT 2:

As @gdw2 commented: "setting up the Google Play Services SDK does not install a working Google Play app -- it just enables certain services provided by the SDK"

After version 2.0 Genymotion does not come with Play Services by default, but it can be easily installed manually. Just download the right version from here and drag and drop into the virtual device (emulador).

curl : (1) Protocol https not supported or disabled in libcurl

Solved this problem with flag --with-darwinssl

Go to folder with curl source code

Download it here https://curl.haxx.se/download.html

sudo ./configure --with-darwinssl
make
make install

restart your console and it is done!

Print array to a file

However op needs to write array as it is on file I have landed this page to find out a solution where I can write a array to file and than can easily read later using php again.

I have found solution my self by using json_encode so anyone else is looking for the same here is the code:

file_put_contents('array.tmp', json_encode($array));

than read

$array = file_get_contents('array.tmp');
$array = json_decode($array,true);

WCF named pipe minimal example

I just found this excellent little tutorial. broken link (Cached version)

I also followed Microsoft's tutorial which is nice, but I only needed pipes as well.

As you can see, you don't need configuration files and all that messy stuff.

By the way, he uses both HTTP and pipes. Just remove all code lines related to HTTP, and you'll get a pure pipe example.

Unstage a deleted file in git

I tried the above solutions and I was still having difficulties. I had other files staged with two files that were deleted accidentally.

To undo the two deleted files I had to unstage all of the files:

git reset HEAD .

At that point I was able to do the checkout of the deleted items:

git checkout -- WorkingFolder/FileName.ext

Finally I was able to restage the rest of the files and continue with my commit.

How to read multiple text files into a single RDD?

You can use a single textFile call to read multiple files. Scala:

sc.textFile(','.join(files)) 

Shared-memory objects in multiprocessing

If you use an operating system that uses copy-on-write fork() semantics (like any common unix), then as long as you never alter your data structure it will be available to all child processes without taking up additional memory. You will not have to do anything special (except make absolutely sure you don't alter the object).

The most efficient thing you can do for your problem would be to pack your array into an efficient array structure (using numpy or array), place that in shared memory, wrap it with multiprocessing.Array, and pass that to your functions. This answer shows how to do that.

If you want a writeable shared object, then you will need to wrap it with some kind of synchronization or locking. multiprocessing provides two methods of doing this: one using shared memory (suitable for simple values, arrays, or ctypes) or a Manager proxy, where one process holds the memory and a manager arbitrates access to it from other processes (even over a network).

The Manager approach can be used with arbitrary Python objects, but will be slower than the equivalent using shared memory because the objects need to be serialized/deserialized and sent between processes.

There are a wealth of parallel processing libraries and approaches available in Python. multiprocessing is an excellent and well rounded library, but if you have special needs perhaps one of the other approaches may be better.

JSON forEach get Key and Value

Use forEach in combo with Object.entries().

_x000D_
_x000D_
const WALLPAPERS = [{
  WALLPAPER_KEY: 'wallpaper.image',
  WALLPAPER_VALID_KEY: 'wallpaper.image.valid',
}, {
  WALLPAPER_KEY: 'lockscreen.image',
  WALLPAPER_VALID_KEY: 'lockscreen.image.valid',
}];

WALLPAPERS.forEach((obj) => {
  for (const [key, value] of Object.entries(obj)) {
    console.log(`${key} - ${value}`);
  }
});
_x000D_
_x000D_
_x000D_

Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate

Old post but as you said "why is it not using the correct certificate" I would like to offer an way to find out which SSL certificate is used for SMTP (see here) which required openssl:

openssl s_client -connect exchange01.int.contoso.com:25 -starttls smtp

This will outline the used SSL certificate for the SMTP service. Based on what you see here you can replace the wrong certificate (like you already did) with a correct one (or trust the certificate manually).

difference between variables inside and outside of __init__()

class foo(object):
    mStatic = 12

    def __init__(self):
        self.x = "OBj"

Considering that foo has no access to x at all (FACT)

the conflict now is in accessing mStatic by an instance or directly by the class .

think of it in the terms of Python's memory management :

12 value is on the memory and the name mStatic (which accessible from the class)

points to it .

c1, c2 = foo(), foo() 

this line makes two instances , which includes the name mStatic that points to the value 12 (till now) .

foo.mStatic = 99 

this makes mStatic name pointing to a new place in the memory which has the value 99 inside it .

and because the (babies) c1 , c2 are still following (daddy) foo , they has the same name (c1.mStatic & c2.mStatic ) pointing to the same new value .

but once each baby decides to walk alone , things differs :

c1.mStatic ="c1 Control"
c2.mStatic ="c2 Control"

from now and later , each one in that family (c1,c2,foo) has its mStatica pointing to different value .

[Please, try use id() function for all of(c1,c2,foo) in different sates that we talked about , i think it will make things better ]

and this is how our real life goes . sons inherit some beliefs from their father and these beliefs still identical to father's ones until sons decide to change it .

HOPE IT WILL HELP

Get size of a View in React Native

Maybe you can use measure:

measureProgressBar() {
    this.refs.welcome.measure(this.logProgressBarLayout);
},

logProgressBarLayout(ox, oy, width, height, px, py) {
  console.log("ox: " + ox);
  console.log("oy: " + oy);
  console.log("width: " + width);
  console.log("height: " + height);
  console.log("px: " + px);
  console.log("py: " + py);
}

Remove "whitespace" between div element

Add line-height: 0px; to your parent div

jsfiddle: http://jsfiddle.net/majZt/

How to remove ASP.Net MVC Default HTTP Headers?

Check this blog Don't use code to remove headers. It is unstable according Microsoft

My take on this:

<system.webServer>          
    <httpProtocol>
    <!-- Security Hardening of HTTP response headers -->
    <customHeaders>
        <!--Sending the new X-Content-Type-Options response header with the value 'nosniff' will prevent 
                Internet Explorer from MIME-sniffing a response away from the declared content-type. -->
        <add name="X-Content-Type-Options" value="nosniff" />

        <!-- X-Frame-Options tells the browser whether you want to allow your site to be framed or not. 
                 By preventing a browser from framing your site you can defend against attacks like clickjacking. 
                 Recommended value "x-frame-options: SAMEORIGIN" -->
        <add name="X-Frame-Options" value="SAMEORIGIN" />

        <!-- Setting X-Permitted-Cross-Domain-Policies header to “master-only” will instruct Flash and PDF files that 
                 they should only read the master crossdomain.xml file from the root of the website. 
                 https://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html -->
        <add name="X-Permitted-Cross-Domain-Policies" value="master-only" />

        <!-- X-XSS-Protection sets the configuration for the cross-site scripting filter built into most browsers. 
                 Recommended value "X-XSS-Protection: 1; mode=block". -->
        <add name="X-Xss-Protection" value="1; mode=block" />

        <!-- Referrer-Policy allows a site to control how much information the browser includes with navigations away from a document and should be set by all sites. 
                 If you have sensitive information in your URLs, you don't want to forward to other domains 
                 https://scotthelme.co.uk/a-new-security-header-referrer-policy/ -->
        <add name="Referrer-Policy" value="no-referrer-when-downgrade" />

        <!-- Remove x-powered-by in the response header, required by OWASP A5:2017 - Do not disclose web server configuration -->
        <remove name="X-Powered-By" />

        <!-- Ensure the cache-control is public, some browser won't set expiration without that  -->
        <add name="Cache-Control" value="public" />
    </customHeaders>
</httpProtocol>

<!-- Prerequisite for the <rewrite> section
            Install the URL Rewrite Module on the Web Server https://www.iis.net/downloads/microsoft/url-rewrite -->
<rewrite>
    <!-- Remove Server response headers (OWASP Security Measure) -->
    <outboundRules rewriteBeforeCache="true">
        <rule name="Remove Server header">
            <match serverVariable="RESPONSE_Server" pattern=".+" />

            <!-- Use custom value for the Server info -->
            <action type="Rewrite" value="Your Custom Value Here." />
        </rule>
    </outboundRules>
</rewrite>
</system.webServer>

C++ convert string to hexadecimal and vice versa

string ToHex(const string& s, bool upper_case /* = true */)
{
    ostringstream ret;

    for (string::size_type i = 0; i < s.length(); ++i)
        ret << std::hex << std::setfill('0') << std::setw(2) << (upper_case ? std::uppercase : std::nouppercase) << (int)s[i];

    return ret.str();
}

int FromHex(const string &s) { return strtoul(s.c_str(), NULL, 16); }

How return error message in spring mvc @Controller

return new ResponseEntity<>(GenericResponseBean.newGenericError("Error during the calling the service", -1L), HttpStatus.EXPECTATION_FAILED);

XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header

This bug cost me 2 days. I checked my Server log, the Preflight Option request/response between browser Chrome/Edge and Server was ok. The main reason is that GET/POST/PUT/DELETE server response for XHTMLRequest must also have the following header:

access-control-allow-origin: origin  

"origin" is in the request header (Browser will add it to request for you). for example:

Origin: http://localhost:4221

you can add response header like the following to accept for all:

access-control-allow-origin: *  

or response header for a specific request like:

access-control-allow-origin: http://localhost:4221 

The message in browsers is not clear to understand: "...The requested resource"

note that: CORS works well for localhost. different port means different Domain. if you get error message, check the CORS config on the server side.

How can I inspect element in an Android browser?

You can inspect elements of a website in your Android device using Chrome browser.

Open your Chrome browser and go to the website you want to inspect.

Go to the address bar and type "view-source:" before the "HTTP" and reload the page.

The whole elements of the page will be shown.

Can someone give an example of cosine similarity, in a very simple, graphical way?

Using @Bill Bell example, two ways to do this in [R]

a = c(2,1,0,2,0,1,1,1)

b = c(2,1,1,1,1,0,1,1)

d = (a %*% b) / (sqrt(sum(a^2)) * sqrt(sum(b^2)))

or taking advantage of crossprod() method's performance...

e = crossprod(a, b) / (sqrt(crossprod(a, a)) * sqrt(crossprod(b, b)))

javascript convert int to float

JavaScript only has a Number type that stores floating point values.

There is no int.

Edit:

If you want to format the number as a string with two digits after the decimal point use:

(4).toFixed(2)

Unmarshaling nested JSON objects

Combining map and struct allow unmarshaling nested JSON objects where the key is dynamic. => map[string]

For example: stock.json

{
  "MU": {
    "symbol": "MU",
    "title": "micro semiconductor",
    "share": 400,
    "purchase_price": 60.5,
    "target_price": 70
  },
  "LSCC":{
    "symbol": "LSCC",
    "title": "lattice semiconductor",
    "share": 200,
    "purchase_price": 20,
    "target_price": 30
  }
}

Go application

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "os"
)

type Stock struct {
    Symbol        string  `json:"symbol"`
    Title         string  `json:"title"`
    Share         int     `json:"share"`
    PurchasePrice float64 `json:"purchase_price"`
    TargetPrice   float64 `json:"target_price"`
}
type Account map[string]Stock

func main() {
    raw, err := ioutil.ReadFile("stock.json")
    if err != nil {
        fmt.Println(err.Error())
        os.Exit(1)
    }
    var account Account
    log.Println(account)
}

The dynamic key in the hash is handle a string, and the nested object is represented by a struct.

How to save as a new file and keep working on the original one in Vim?

After save new file press

Ctrl-6

This is shortcut to alternate file

Sending arrays with Intent.putExtra

final static String EXTRA_MESSAGE = "edit.list.message";

Context context;
public void onClick (View view)
{   
    Intent intent = new Intent(this,display.class);
    RelativeLayout relativeLayout = (RelativeLayout) view.getParent();

    TextView textView = (TextView) relativeLayout.findViewById(R.id.textView1);
    String message = textView.getText().toString();

    intent.putExtra(EXTRA_MESSAGE,message);
    startActivity(intent);
}

jquery .live('click') vs .click()

(Note 29/08/2017: live was deprecated many versions ago and removed in v1.9. delegate was deprecated in v3.0. In both cases, use the delegating signature of on instead [also covered below].)


live happens by capturing the event when it's bubbled all the way up the DOM to the document root, and then looking at the source element. click happens by capturing the event on the element itself. So if you're using live, and one of the ancestor elements is hooking the event directly (and preventing it continuing to bubble), you'll never see the event on your element. Whereas normally, the element nearest the event (click or whatever) gets first grab at it, the mix of live and non-live events can change that in subtle ways.

For example:

_x000D_
_x000D_
jQuery(function($) {_x000D_
_x000D_
  $('span').live('click', function() {_x000D_
    display("<tt>live</tt> caught a click!");_x000D_
  });_x000D_
_x000D_
  $('#catcher').click(function() {_x000D_
    display("Catcher caught a click and prevented <tt>live</tt> from seeing it.");_x000D_
    return false;_x000D_
  });_x000D_
_x000D_
  function display(msg) {_x000D_
    $("<p>").html(msg).appendTo(document.body);_x000D_
  }_x000D_
_x000D_
});
_x000D_
<div>_x000D_
  <span>Click me</span>_x000D_
  <span>or me</span>_x000D_
  <span>or me</span>_x000D_
  <div>_x000D_
    <span>I'm two levels in</span>_x000D_
    <span>so am I</span>_x000D_
  </div>_x000D_
  <div id='catcher'>_x000D_
    <span>I'm two levels in AND my parent interferes with <tt>live</tt></span>_x000D_
    <span>me too</span>_x000D_
  </div>_x000D_
</div>_x000D_
<!-- Using an old version because `live` was removed in v1.9 -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">_x000D_
</script>
_x000D_
_x000D_
_x000D_

I'd recommend using delegate over live when you can, so you can more thoroughly control the scope; with delegate, you control the root element that captures the bubbling event (e.g., live is basically delegate using the document root as the root). Also, recommend avoiding (where possible) having delegate or live interacting with non-delegated, non-live event handling.


Here several years later, you wouldn't use either live or delegate; you'd use the delegating signature of on, but the concept is still the same: The event is hooked on the element you call on on, but then fired only when descendants match the selector given after the event name:

_x000D_
_x000D_
jQuery(function($) {_x000D_
_x000D_
  $(document).on('click', 'span', function() {_x000D_
    display("<tt>live</tt> caught a click!");_x000D_
  });_x000D_
_x000D_
  $('#catcher').click(function() {_x000D_
    display("Catcher caught a click and prevented <tt>live</tt> from seeing it.");_x000D_
    return false;_x000D_
  });_x000D_
_x000D_
  function display(msg) {_x000D_
    $("<p>").html(msg).appendTo(document.body);_x000D_
  }_x000D_
_x000D_
});
_x000D_
<div>_x000D_
  <span>Click me</span>_x000D_
  <span>or me</span>_x000D_
  <span>or me</span>_x000D_
  <div>_x000D_
    <span>I'm two levels in</span>_x000D_
    <span>so am I</span>_x000D_
  </div>_x000D_
  <div id='catcher'>_x000D_
    <span>I'm two levels in AND my parent interferes with <tt>live</tt></span>_x000D_
    <span>me too</span>_x000D_
  </div>_x000D_
</div>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

How to trigger an event after using event.preventDefault()

The accepted solution wont work in case you are working with an anchor tag. In this case you wont be able to click the link again after calling e.preventDefault(). Thats because the click event generated by jQuery is just layer on top of native browser events. So triggering a 'click' event on an anchor tag wont follow the link. Instead you could use a library like jquery-simulate that will allow you to launch native browser events.

More details about this can be found in this link

How can I convert a VBScript to an executable (EXE) file?

More info

To find a compiler, you'll have 1 per .net version installed, type in a command prompt.

dir c:\Windows\Microsoft.NET\vbc.exe /a/s

Windows Forms

For a Windows Forms version (no console window and we don't get around to actually creating any forms - though you can if you want).

Compile line in a command prompt.

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe "%userprofile%\desktop\VBS2Exe.vb"

Text for VBS2EXE.vb

Imports System.Windows.Forms 

Partial Class MyForm : Inherits Form 

Private Sub InitializeComponent() 


End Sub

Public Sub New() 

InitializeComponent() 

End Sub

Public Shared Sub Main() 

Dim sc as object 
Dim Scrpt as string

sc = createObject("MSScriptControl.ScriptControl")

Scrpt = "msgbox " & chr(34) & "Hi there I'm a form" & chr(34)

With SC 
.Language = "VBScript" 
.UseSafeSubset = False 
.AllowUI = True 
End With


sc.addcode(Scrpt)


End Sub

End Class

Using these optional parameters gives you an icon and manifest. A manifest allows you to specify run as normal, run elevated if admin, only run elevated.

/win32icon: Specifies a Win32 icon file (.ico) for the default Win32 resources.

/win32manifest: The provided file is embedded in the manifest section of the output PE.

In theory, I have UAC off so can't test, but put this text file on the desktop and call it vbs2exe.manifest, save as UTF-8.

The command line

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe /win32manifest:"%userprofile%\desktop\VBS2Exe.manifest" "%userprofile%\desktop\VBS2Exe.vb"

The manifest

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
  <assembly xmlns="urn:schemas-microsoft-com:asm.v1" 
  manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" 
  processorArchitecture="*" name="VBS2EXE" type="win32" /> 
  <description>Script to Exe</description> 
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> 
  <security> <requestedPrivileges> 
  <requestedExecutionLevel level="requireAdministrator" 
  uiAccess="false" /> </requestedPrivileges> 
  </security> </trustInfo> </assembly>

Hopefully it will now ONLY run as admin.

Give Access To a Host's Objects

Here's an example giving the vbscript access to a .NET object.

Imports System.Windows.Forms 

Partial Class MyForm : Inherits Form 

Private Sub InitializeComponent() 


End Sub 

Public Sub New() 

InitializeComponent() 

End Sub 

Public Shared Sub Main() 

Dim sc as object
Dim Scrpt as string 

sc = createObject("MSScriptControl.ScriptControl") 

Scrpt = "msgbox " & chr(34) & "Hi there I'm a form" & chr(34) & ":msgbox meScript.state" 

With SC
.Language = "VBScript"
.UseSafeSubset = False
.AllowUI = True
.addobject("meScript", SC, true)
End With 


sc.addcode(Scrpt) 


End Sub 

End Class 

To Embed version info

Download vbs2exe.res file from https://skydrive.live.com/redir?resid=E2F0CE17A268A4FA!121 and put on desktop.

Download ResHacker from http://www.angusj.com/resourcehacker

Open vbs2exe.res file in ResHacker. Edit away. Click Compile button. Click File menu - Save.

Type

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe /win32manifest:"%userprofile%\desktop\VBS2Exe.manifest" /win32resource:"%userprofile%\desktop\VBS2Exe.res" "%userprofile%\desktop\VBS2Exe.vb"

How do I use modulus for float/double?

Unlike C, Java allows using the % for both integer and floating point and (unlike C89 and C++) it is well-defined for all inputs (including negatives):

From JLS §15.17.3:

The result of a floating-point remainder operation is determined by the rules of IEEE arithmetic:

  • If either operand is NaN, the result is NaN.
  • If the result is not NaN, the sign of the result equals the sign of the dividend.
  • If the dividend is an infinity, or the divisor is a zero, or both, the result is NaN.
  • If the dividend is finite and the divisor is an infinity, the result equals the dividend.
  • If the dividend is a zero and the divisor is finite, the result equals the dividend.
  • In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, the floating-point remainder r from the division of a dividend n by a divisor d is defined by the mathematical relation r=n-(d·q) where q is an integer that is negative only if n/d is negative and positive only if n/d is positive, and whose magnitude is as large as possible without exceeding the magnitude of the true mathematical quotient of n and d.

So for your example, 0.5/0.3 = 1.6... . q has the same sign (positive) as 0.5 (the dividend), and the magnitude is 1 (integer with largest magnitude not exceeding magnitude of 1.6...), and r = 0.5 - (0.3 * 1) = 0.2

Return multiple fields as a record in PostgreSQL with PL/pgSQL

you can do this using OUT parameter and CROSS JOIN

CREATE OR REPLACE FUNCTION get_object_fields(my_name text, OUT f1 text, OUT f2 text)
AS $$
SELECT t1.name, t2.name
FROM  table1 t1 
CROSS JOIN table2 t2 
WHERE t1.name = my_name AND t2.name = my_name;
$$ LANGUAGE SQL;

then use it as a table:

select get_object_fields( 'Pending') ;
get_object_fields
-------------------
(Pending,code)
(1 row)

or

select * from get_object_fields( 'Pending');
f1    |   f
---------+---------
Pending | code
(1 row)

or

select (get_object_fields( 'Pending')).f1;
f1
---------
Pending
(1 row)

How to find foreign key dependencies in SQL Server?

One that I really like to use is called SQL Dependency Tracker by Red Gate Software. You can put in any database object(s) such as tables, stored procedures, etc. and it will then automatically draw the relationship lines between all the other objects that rely on your selected item(s).

Gives a very good graphical representation of the dependencies in your schema.

How to check if a file exists in Documents folder?

NSArray *directoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *imagePath =  [directoryPath objectAtIndex:0];
//If you have superate folder
imagePath= [imagePath stringByAppendingPathComponent:@"ImagesFolder"];//Get docs dir path with folder name
_imageName = [_imageName stringByAppendingString:@".jpg"];//Assign image name
imagePath= [imagePath stringByAppendingPathComponent:_imageName];
NSLog(@"%@", imagePath);

//Method 1:
BOOL file = [[NSFileManager defaultManager] fileExistsAtPath: imagePath];
if (file == NO){
    NSLog("File not exist");
} else {
    NSLog("File exist");
}

//Method 2:
NSData *data = [NSData dataWithContentsOfFile:imagePath];
UIImage *image = [UIImage imageWithData:data];
if (!(image == nil)) {//Check image exist or not
    cell.photoImageView.image = image;//Display image
}

function to return a string in java

Your code is fine. There's no problem with returning Strings in this manner.

In Java, a String is a reference to an immutable object. This, coupled with garbage collection, takes care of much of the potential complexity: you can simply pass a String around without worrying that it would disapper on you, or that someone somewhere would modify it.

If you don't mind me making a couple of stylistic suggestions, I'd modify the code like so:

public String time_to_string(long t) // time in milliseconds
{
    if (t < 0)
    {
        return "-";
    }
    else
    {
        int secs = (int)(t/1000);
        int mins = secs/60;
        secs = secs - (mins * 60);
        return String.format("%d:%02d", mins, secs);
    }
}

As you can see, I've pushed the variable declarations as far down as I could (this is the preferred style in C++ and Java). I've also eliminated ans and have replaced the mix of string concatenation and String.format() with a single call to String.format().

How can I override the OnBeforeUnload dialog and replace it with my own?

I faced the same problem, I was ok to get its own dialog box with my message, but the problem I faced was : 1) It was giving message on all navigations I want it only for close click. 2) with my own confirmation message if user selects cancel it still shows the browser's default dialog box.

Following is the solutions code I found, which I wrote on my Master page.

function closeMe(evt) {
    if (typeof evt == 'undefined') {
        evt = window.event; }
    if (evt && evt.clientX >= (window.event.screenX - 150) &&
        evt.clientY >= -150 && evt.clientY <= 0) {
        return "Do you want to log out of your current session?";
    }
}
window.onbeforeunload = closeMe;

Changing Tint / Background color of UITabBar

When you just use addSubview your buttons will lose clickability, so instead of

[[self tabBar] addSubview:v];

use:

[[self tabBar] insertSubview:v atIndex:0];

How do I create an abstract base class in JavaScript?

Animal = function () { throw "abstract class!" }
Animal.prototype.name = "This animal";
Animal.prototype.sound = "...";
Animal.prototype.say = function() {
    console.log( this.name + " says: " + this.sound );
}

Cat = function () {
    this.name = "Cat";
    this.sound = "meow";
}

Dog = function() {
    this.name = "Dog";
    this.sound  = "woof";
}

Cat.prototype = Object.create(Animal.prototype);
Dog.prototype = Object.create(Animal.prototype);

new Cat().say();    //Cat says: meow
new Dog().say();    //Dog says: woof 
new Animal().say(); //Uncaught abstract class! 

How does EL empty operator work in JSF?

Using BalusC's suggestion of implementing Collection i can now hide my primefaces p:dataTable using not empty operator on my dataModel that extends javax.faces.model.ListDataModel

Code sample:

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import javax.faces.model.ListDataModel;
import org.primefaces.model.SelectableDataModel;

public class EntityDataModel extends ListDataModel<Entity> implements
        Collection<Entity>, SelectableDataModel<Entity>, Serializable {

    public EntityDataModel(List<Entity> data) { super(data); }

    @Override
    public Entity getRowData(String rowKey) {
        // In a real app, a more efficient way like a query by rowKey should be
        // implemented to deal with huge data
        List<Entity> entitys = (List<Entity>) getWrappedData();
        for (Entity entity : entitys) {
            if (Integer.toString(entity.getId()).equals(rowKey)) return entity;
        }
        return null;
    }

    @Override
    public Object getRowKey(Entity entity) {
        return entity.getId();
    }

    @Override
    public boolean isEmpty() {
        List<Entity> entity = (List<Entity>) getWrappedData();
        return (entity == null) || entity.isEmpty();
    }
    // ... other not implemented methods of Collection...
}

Google Maps API throws "Uncaught ReferenceError: google is not defined" only when using AJAX

What worked for me after following all your workarounds was to call the API:

 <script async defer src="https://maps.googleapis.com/maps/api/js?key=you_API_KEY&callback=initMap&libraries=places"
            type="text/javascript"></script>

before my : <div id="map"></div>

I am using .ASP NET (MVC)

How to square or raise to a power (elementwise) a 2D numpy array?

The fastest way is to do a*a or a**2 or np.square(a) whereas np.power(a, 2) showed to be considerably slower.

np.power() allows you to use different exponents for each element if instead of 2 you pass another array of exponents. From the comments of @GarethRees I just learned that this function will give you different results than a**2 or a*a, which become important in cases where you have small tolerances.

I've timed some examples using NumPy 1.9.0 MKL 64 bit, and the results are shown below:

In [29]: a = np.random.random((1000, 1000))

In [30]: timeit a*a
100 loops, best of 3: 2.78 ms per loop

In [31]: timeit a**2
100 loops, best of 3: 2.77 ms per loop

In [32]: timeit np.power(a, 2)
10 loops, best of 3: 71.3 ms per loop

Issue with parsing the content from json file with Jackson & message- JsonMappingException -Cannot deserialize as out of START_ARRAY token

JsonMappingException: out of START_ARRAY token exception is thrown by Jackson object mapper as it's expecting an Object {} whereas it found an Array [{}] in response.

This can be solved by replacing Object with Object[] in the argument for geForObject("url",Object[].class). References:

  1. Ref.1
  2. Ref.2
  3. Ref.3

running multiple bash commands with subprocess

You have to use shell=True in subprocess and no shlex.split:

def subprocess_cmd(command):
    process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
    proc_stdout = process.communicate()[0].strip()
    print proc_stdout

subprocess_cmd('echo a; echo b')

returns:

a
b

Node.js request CERT_HAS_EXPIRED

Try to temporarily modify request.js and harcode everywhere rejectUnauthorized = true, but it would be better to get the certificate extended as a long-term solution.

How to get the unique ID of an object which overrides hashCode()?

I came up with this solution which works in my case where I have objects created on multiple threads and are serializable:

public abstract class ObjBase implements Serializable
    private static final long serialVersionUID = 1L;
    private static final AtomicLong atomicRefId = new AtomicLong();

    // transient field is not serialized
    private transient long refId;

    // default constructor will be called on base class even during deserialization
    public ObjBase() {
       refId = atomicRefId.incrementAndGet()
    }

    public long getRefId() {
        return refId;
    }
}

Change the Blank Cells to "NA"

For those wondering about a solution using the data.table way, here is one I wrote a function for, available on my Github:

library(devtools)
source_url("https://github.com/YoannPa/Miscellaneous/blob/master/datatable_pattern_substitution.R?raw=TRUE")
dt.sub(DT = dat2, pattern = "^$|^ $",replacement = NA)
dat2

The function goes through each column, to identify which column contains pattern matches. Then gsub() is aplied only on columns containing matches for the pattern "^$|^ $", to substitutes matches by NAs.

I will keep improving this function to make it faster.

How to increase editor font size?

Done, you can try this(on Mac): Preferences --> Editor --> Colors & Fonts, in the right side, then click "save as...", this will create a new Scheme, we name it such as "Custom", then all fields become to editable, font, space, color, etc.

Postgres - Transpose Rows to Columns

If anyone else that finds this question and needs a dynamic solution for this where you have an undefined number of columns to transpose to and not exactly 3, you can find a nice solution here: https://github.com/jumpstarter-io/colpivot

Get all photos from Instagram which have a specific hashtag with PHP

I have set a php code which can help in case you want to access Instagram images without api on basis of hashtag

Php Code for Instagram hashtag images

How to find the statistical mode?

One more solution, which works for both numeric & character/factor data:

Mode <- function(x) {
  ux <- unique(x)
  ux[which.max(tabulate(match(x, ux)))]
}

On my dinky little machine, that can generate & find the mode of a 10M-integer vector in about half a second.

If your data set might have multiple modes, the above solution takes the same approach as which.max, and returns the first-appearing value of the set of modes. To return all modes, use this variant (from @digEmAll in the comments):

Modes <- function(x) {
  ux <- unique(x)
  tab <- tabulate(match(x, ux))
  ux[tab == max(tab)]
}

How to read Excel cell having Date with Apache POI?

You need the DateUtils: see this article for details.

Or, better yet, use Andy Khan's JExcel instead of POI.

How to checkout in Git by date?

git rev-list -n 1 --before="2009-07-27 13:37" origin/master

take the printed string (for instance XXXX) and do:

git checkout XXXX

Bootstrap 3: Using img-circle, how to get circle from non-square image?

You have to give height and width to that image.

eg. height : 200px and width : 200px also give border-radius:50%;

to create circle you have to give equal height and width

if you are using bootstrap then give height and width and img-circle class to img

How do I determine scrollHeight?

Correct ways in jQuery are -

  • $('#test').prop('scrollHeight') OR
  • $('#test')[0].scrollHeight OR
  • $('#test').get(0).scrollHeight

creating array without declaring the size - java

Using Java.util.ArrayList or LinkedList is the usual way of doing this. With arrays that's not possible as I know.

Example:

List<Float> unindexedVectors = new ArrayList<Float>();

unindexedVectors.add(2.22f);

unindexedVectors.get(2);

XSL xsl:template match="/"

It's worth noting, since it's confusing for people new to XML, that the root (or document node) of an XML document is not the top-level element. It's the parent of the top-level element. This is confusing because it doesn't seem like the top-level element can have a parent. Isn't it the top level?

But look at this, a well-formed XML document:

<?xml-stylesheet href="my_transform.xsl" type="text/xsl"?>
<!-- Comments and processing instructions are XML nodes too, remember. -->
<TopLevelElement/>

The root of this document has three children: a processing instruction, a comment, and an element.

So, for example, if you wanted to write a transform that got rid of that comment, but left in any comments appearing anywhere else in the document, you'd add this to the identity transform:

<xsl:template match="/comment()"/>

Even simpler (and more commonly useful), here's an XPath pattern that matches the document's top-level element irrespective of its name: /*.

What bitrate is used for each of the youtube video qualities (360p - 1080p), in regards to flowplayer?

Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:

                   240p       360p        480p        720p        1080p
Resolution      426 x 240   640 x 360   854x480     1280x720    1920x1080
Video Bitrates                   
Maximum         700 Kbps    1000 Kbps   2000 Kbps   4000 Kbps   6000 Kbps
Recommended     400 Kbps    750 Kbps    1000 Kbps   2500 Kbps   4500 Kbps
Minimum         300 Kbps    400 Kbps    500 Kbps    1500 Kbps   3000 Kbps

It would appear as though this is the case, although the numbers dont sync up to the google table above:

// the bitrates, video width and file names for this clip
      bitrates: [
        { url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
        { url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
        { url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video
      ],

Installing NumPy via Anaconda in Windows

Yep you should start anaconda's python in order to use python libs which come with anaconda. Or otherwise you have to manually add anaconda\lib to pythonpath which is less trivial. You can start anaconda's python by a full path:

path\to\anaconda\python.exe

or you can run the following two commands as an admin in cmd to make windows pipe every .py file to anaconda's python:

assoc .py=Python.File
ftype Python.File=C:\path\to\Anaconda\python.exe "%1" %*

after this you'll be able just to call python scripts without specifying the python executable at all.

How to get an element by its href in jquery?

var myElement = $("a[href='http://www.stackoverflow.com']");

http://api.jquery.com/attribute-equals-selector/

Should CSS always preceed Javascript?

Updated 2017-12-16

I was not sure about the tests in OP. I decided to experiment a little and ended up busting some of the myths.

Synchronous <script src...> will block downloading of the resources below it until it is downloaded and executed

This is no longer true. Have a look at the waterfall generated by Chrome 63:

<head>
<script src="//alias-0.redacted.com/payload.php?type=js&amp;delay=333&amp;rand=1"></script>
<script src="//alias-1.redacted.com/payload.php?type=js&amp;delay=333&amp;rand=2"></script>
<script src="//alias-2.redacted.com/payload.php?type=js&amp;delay=333&amp;rand=3"></script>
</head>

Chrome net inspector -> waterfall

<link rel=stylesheet> will not block download and execution of scripts below it

This is incorrect. The stylesheet will not block download but it will block execution of the script (little explanation here). Have a look at performance chart generated by Chrome 63:

<link href="//alias-0.redacted.com/payload.php?type=css&amp;delay=666" rel="stylesheet">
<script src="//alias-1.redacted.com/payload.php?type=js&amp;delay=333&amp;block=1000"></script>

Chrome dev tools -> performance


Keeping the above in mind, the results in OP can be explained as follows:

CSS First:

CSS Download  500ms:<------------------------------------------------>
JS Download   400ms:<-------------------------------------->
JS Execution 1000ms:                                                  <-------------------------------------------------------------------------------------------------->
DOM Ready   @1500ms:                                                                                                                                                      ?

JS First:

JS Download   400ms:<-------------------------------------->
CSS Download  500ms:<------------------------------------------------>
JS Execution 1000ms:                                        <-------------------------------------------------------------------------------------------------->
DOM Ready   @1400ms:                                                                                                                                            ?

How to capitalize first letter of each word, like a 2-word city?

There's a good answer here:

function toTitleCase(str) {
    return str.replace(/\w\S*/g, function(txt){
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
}

or in ES6:

var text = "foo bar loo zoo moo";
text = text.toLowerCase()
    .split(' ')
    .map((s) => s.charAt(0).toUpperCase() + s.substring(1))
    .join(' ');

Keeping it simple and how to do multiple CTE in a query

You can have multiple CTEs in one query, as well as reuse a CTE:

WITH    cte1 AS
        (
        SELECT  1 AS id
        ),
        cte2 AS
        (
        SELECT  2 AS id
        )
SELECT  *
FROM    cte1
UNION ALL
SELECT  *
FROM    cte2
UNION ALL
SELECT  *
FROM    cte1

Note, however, that SQL Server may reevaluate the CTE each time it is accessed, so if you are using values like RAND(), NEWID() etc., they may change between the CTE calls.

Setting a system environment variable from a Windows batch file?

SetX is the command that you'll need in most of the cases.Though its possible to use REG or REGEDIT

Using registry editing commands you can avoid some of the restrictions of the SetX command - different data types, variables containing = in their name and so on.

@echo off

:: requires admin elevated permissions
::setting system variable
REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v MyVar /D MyVal
::expandable variable
REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /T REG_EXPAND_SZ /v MyVar /D MyVal


:: does not require admin permissions
::setting user variable
REG ADD "HKEY_CURRENT_USER\Environment" /v =C: /D "C:\\test"

REG is the pure registry client but its possible also to import the data with REGEDIT though it allows using only hard coded values (or generation of a temp files). The example here is a hybrid file that contains both batch code and registry data (should be saved as .bat - mind that in batch ; are ignored as delimiters while they are used as comments in .reg files):

REGEDIT4

; @ECHO OFF
; CLS
; REGEDIT.EXE /S "%~f0"
; EXIT

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment]
"SystemVariable"="GlobalValue"

[HKEY_CURRENT_USER\Environment]
"UserVariable"="SomeValue"

How to implement Enums in Ruby?

Check out the ruby-enum gem, https://github.com/dblock/ruby-enum.

class Gender
  include Enum

  Gender.define :MALE, "male"
  Gender.define :FEMALE, "female"
end

Gender.all
Gender::MALE

Pythonic way to find maximum value and its index in a list?

Here is a complete solution to your question using Python's built-in functions:

# Create the List
numbers = input("Enter the elements of the list. Separate each value with a comma. Do not put a comma at the end.\n").split(",") 

# Convert the elements in the list (treated as strings) to integers
numberL = [int(element) for element in numbers] 

# Loop through the list with a for-loop

for elements in numberL:
    maxEle = max(numberL)
    indexMax = numberL.index(maxEle)

print(maxEle)
print(indexMax)

How do I fix a "Performance counter registry hive consistency" when installing SQL Server R2 Express?

You can skip the Performance counter check in the setup altogether:

setup.exe /ACTION=install /SKIPRULES=PerfMonCounterNotCorruptedCheck

Access cell value of datatable

You can also try (first cell in 4th column):

dt.Rows[0][3]

Angular 2 http post params and body

And it works, thanks @trichetriche. The problem was in my RequestOptions, apparently, you can not pass params or body to the RequestOptions while using the post. Removing one of them gives me an error, removing both and it works. Still no final solution to my problem, but I now have something to work with. Final working code.

public post(cmd: string, data: string): Observable<any> {

    const options = new RequestOptions({
      headers: this.getAuthorizedHeaders(),
      responseType: ResponseContentType.Json,
      withCredentials: false
    });

    console.log('Options: ' + JSON.stringify(options));

    return this.http.post(this.BASE_URL, JSON.stringify({
      cmd: cmd,
      data: data}), options)
      .map(this.handleData)
      .catch(this.handleError);
  }

How to get tf.exe (TFS command line client)?

I'm in a virtual machine, and am trying to keep my VHD as small as possible, so I find Team Explorer is a really heavyweight solution (300+ MB install). As an alternative, I've had some luck copying a minimal set of EXEs/DLLs from a Team Explorer installation to a clean machine (.NET 4.0 is still required, of course).

I've only tried a handful of operations so far, but this set of files (about 8.5 MB) has been enough to get basic source-control functionality via tf.exe:

  • TF.exe
  • TF.exe.config
  • Microsoft.TeamFoundation.dll
  • Microsoft.TeamFoundation.Client.dll
  • Microsoft.TeamFoundation.Common.dll
  • Microsoft.TeamFoundation.Common.Library.dll
  • Microsoft.TeamFoundation.VersionControl.Client.dll
  • Microsoft.TeamFoundation.VersionControl.Common.dll
  • Microsoft.TeamFoundation.VersionControl.Controls.dll

(It should go without saying that this is a completely unsupported solution, and it doesn't free you from the normal TFS licensing requirements.)

Depending on the operations you perform, you may find that additional DLLs are required. Fortunately, tf.exe will produce a nice error message telling you exactly which ones are missing.

Passing multiple values for a single parameter in Reporting Services

The below solution worked for me.

  1. In the parameter tab of your dataset properties click on the expression icon (!http://chittagongit.com//images/fx-icon/fx-icon-16.jpg [fx symbol]) beside the parameter you need to allow comma delimited entry for.

  2. In the expression window that appears, use the Split function (Common Functions -> Text). Example shown below:

=Split(Parameters!ParameterName.Value,",")

How can I get a list of Git branches, ordered by most recent commit?

Another variation:

git branch -r --sort=-committerdate --format='%(HEAD)%(color:yellow)%(refname:short)|%(color:bold green)%(committerdate:relative)|%(color:blue)%(subject)|%(color:magenta)%(authorname)%(color:reset)' --color=always | column -ts'|'

Worth noting that even though it's looking at changes in remote branches, it's worth syncing with origin before running the command (can use git fetch), as I found it can return out of date information if your local Git folder hasn't been updated in a while.

Also, this is a version that works in Windows cmd and PowerShell (didn't get output displayed in columns, would be interested to see if anyone gets this working):

git branch -r --sort=-committerdate --format="%(HEAD)%(color:yellow)%(refname:short)|%(color:bold green)%(committerdate:relative)|%(color:blue)%(subject)|%(color:magenta)%(authorname)%(color:reset)" --color=always

Python convert tuple to string

This works:

''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))

It will produce:

'abcdgxre'

You can also use a delimiter like a comma to produce:

'a,b,c,d,g,x,r,e'

By using:

','.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))

Where is the .NET Framework 4.5 directory?

The webpage is incorrect and I have pointed this out to MS and they will get it changed.

As already stated above .NET 4.5 is an in-place upgrade of 4.0 so you will only have Microsoft.NET\Framework\v4.0.30319.

The ToolVersion for MSBuild remains at "4.0".

jQuery vs. javascript?

It's all about performance and development speed. Of course, if you are a good programmer and design something that is really tailored to your needs, you might achieve better performance than if you had used a Javascript framework. But do you have the time to do it all by yourself?

My personal opinion is that Javascript is incredibly useful and overused, but that if you really need it, a framework is the way to go.

Now comes the choice of the framework. For what benchmarks are worth, you can find one at http://ejohn.org/files/142/ . It also depends on which plugins are available and what you intend to do with them. I started using jQuery because it seemed to be maintained and well featured, even though it wasn't the fastest at that moment. I do not regret it but I didn't test anything else since then.

tsconfig.json: Build:No inputs were found in config file

I had to add the files item to the tsconfig.json file, like so:

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "sourceMap": true,
    },
    "files": [
        "../MyFile.ts"
    ] 
}

More details here: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html

cc1plus: error: unrecognized command line option "-std=c++11" with g++

you should try this

g++-4.4 -std=c++0x or g++-4.7 -std=c++0x

What are the main differences between JWT and OAuth authentication?

TL;DR If you have very simple scenarios, like a single client application, a single API then it might not pay off to go OAuth 2.0, on the other hand, lots of different clients (browser-based, native mobile, server-side, etc) then sticking to OAuth 2.0 rules might make it more manageable than trying to roll your own system.


As stated in another answer, JWT (Learn JSON Web Tokens) is just a token format, it defines a compact and self-contained mechanism for transmitting data between parties in a way that can be verified and trusted because it is digitally signed. Additionally, the encoding rules of a JWT also make these tokens very easy to use within the context of HTTP.

Being self-contained (the actual token contains information about a given subject) they are also a good choice for implementing stateless authentication mechanisms (aka Look mum, no sessions!). When going this route and the only thing a party must present to be granted access to a protected resource is the token itself, the token in question can be called a bearer token.

In practice, what you're doing can already be classified as based on bearer tokens. However, do consider that you're not using bearer tokens as specified by the OAuth 2.0 related specs (see RFC 6750). That would imply, relying on the Authorization HTTP header and using the Bearer authentication scheme.

Regarding the use of the JWT to prevent CSRF without knowing exact details it's difficult to ascertain the validity of that practice, but to be honest it does not seem correct and/or worthwhile. The following article (Cookies vs Tokens: The Definitive Guide) may be a useful read on this subject, particularly the XSS and XSRF Protection section.

One final piece of advice, even if you don't need to go full OAuth 2.0, I would strongly recommend on passing your access token within the Authorization header instead of going with custom headers. If they are really bearer tokens, follow the rules of RFC 6750. If not, you can always create a custom authentication scheme and still use that header.

Authorization headers are recognized and specially treated by HTTP proxies and servers. Thus, the usage of such headers for sending access tokens to resource servers reduces the likelihood of leakage or unintended storage of authenticated requests in general, and especially Authorization headers.

(source: RFC 6819, section 5.4.1)

How to change the icon of an Android app in Eclipse?

Rob R.'s answer was definitely the way to go. I tried copying the ic_launcher.png files from another project and Eclipse still wouldn't read them. Going through the manifest is much quicker and easier.

Class Not Found Exception when running JUnit test

Earlier, in this case, I always did mvn eclipse:eclipse and restarted my Eclipse and it worked. After migrating to GIT, it stopped working for me which is somewhat weird.

Basic problem here is Mr Eclipse does not find the compiled class. Then, I set the output folder as Project/target/test-classes which is by default generated by mvn clean install without skipping the test and proceeded with following workaround:

Option 1: Set classpath for each test case

Eclipse ->Run ->Run Configurations ->under JUnit->select mytest -> under classpath tab->Select User Entries->Advanced->Add Folder -> Select ->Apply->Run

Option 2: Create classpath variable and include it in classpath for all the test cases

Eclipse ->Windows ->Classpath Variables ->New->[Name : Junit_test_cases_cp | path : ]->ok Then go to Eclipse->Run ->Run Configurations ->JUnit->select mytest ->under classpath tab ->Select User Entries->Advanced->Add classpath variables->Select Junit_test_cases_cp->ok->Apply->Run

This is the only thing currently working for me after trying all the suggestions online.

What is the best method of handling currency/money?

Just a little update and a cohesion of all the answers for some aspiring juniors/beginners in RoR development that will surely come here for some explanations.

Working with money

Use :decimal to store money in the DB, as @molf suggested (and what my company uses as a golden standard when working with money).

# precision is the total number of digits
# scale is the number of digits to the right of the decimal point
add_column :items, :price, :decimal, precision: 8, scale: 2

Few points:

  • :decimal is going to be used as BigDecimal which solves a lot of issues.

  • precision and scale should be adjusted, depending on what you are representing

    • If you work with receiving and sending payments, precision: 8 and scale: 2 gives you 999,999.99 as the highest amount, which is fine in 90% of cases.

    • If you need to represent the value of a property or a rare car, you should use a higher precision.

    • If you work with coordinates (longitude and latitude), you will surely need a higher scale.

How to generate a migration

To generate the migration with the above content, run in terminal:

bin/rails g migration AddPriceToItems price:decimal{8-2}

or

bin/rails g migration AddPriceToItems 'price:decimal{5,2}'

as explained in this blog post.

Currency formatting

KISS the extra libraries goodbye and use built-in helpers. Use number_to_currency as @molf and @facundofarias suggested.

To play with number_to_currency helper in Rails console, send a call to the ActiveSupport's NumberHelper class in order to access the helper.

For example:

ActiveSupport::NumberHelper.number_to_currency(2_500_000.61, unit: '€', precision: 2, separator: ',', delimiter: '', format: "%n%u")

gives the following output

2500000,61€

Check the other options of number_to_currency helper.

Where to put it

You can put it in an application helper and use it inside views for any amount.

module ApplicationHelper    
  def format_currency(amount)
    number_to_currency(amount, unit: '€', precision: 2, separator: ',', delimiter: '', format: "%n%u")
  end
end

Or you can put it in the Item model as an instance method, and call it where you need to format the price (in views or helpers).

class Item < ActiveRecord::Base
  def format_price
    number_to_currency(price, unit: '€', precision: 2, separator: ',', delimiter: '', format: "%n%u")
  end
end

And, an example how I use the number_to_currency inside a contrroler (notice the negative_format option, used to represent refunds)

def refund_information
  amount_formatted = 
    ActionController::Base.helpers.number_to_currency(@refund.amount, negative_format: '(%u%n)')
  {
    # ...
    amount_formatted: amount_formatted,
    # ...
  }
end

How to export SQL Server 2005 query to CSV

In Management Studio, select the database, right-click and select Tasks->Export Data. There you will see options to export to different kinds of formats including CSV, Excel, etc.

You can also run your query from the Query window and save the results to CSV.

Convert bytes to bits in python

Here how to do it using format()

print "bin_signedDate : ", ''.join(format(x, '08b') for x in bytevector)

It is important the 08b . That means it will be a maximum of 8 leading zeros be appended to complete a byte. If you don't specify this then the format will just have a variable bit length for each converted byte.

What is the easiest way to encrypt a password when I save it to the registry?

Please also consider "salting" your hash (not a culinary concept!). Basically, that means appending some random text to the password before you hash it.

"The salt value helps to slow an attacker perform a dictionary attack should your credential store be compromised, giving you additional time to detect and react to the compromise."

To store password hashes:

a) Generate a random salt value:

byte[] salt = new byte[32];
System.Security.Cryptography.RNGCryptoServiceProvider.Create().GetBytes(salt);

b) Append the salt to the password.

// Convert the plain string pwd into bytes
byte[] plainTextBytes = System.Text UnicodeEncoding.Unicode.GetBytes(plainText);
// Append salt to pwd before hashing
byte[] combinedBytes = new byte[plainTextBytes.Length + salt.Length];
System.Buffer.BlockCopy(plainTextBytes, 0, combinedBytes, 0, plainTextBytes.Length);
System.Buffer.BlockCopy(salt, 0, combinedBytes, plainTextBytes.Length, salt.Length);

c) Hash the combined password & salt:

// Create hash for the pwd+salt
System.Security.Cryptography.HashAlgorithm hashAlgo = new System.Security.Cryptography.SHA256Managed();
byte[] hash = hashAlgo.ComputeHash(combinedBytes);

d) Append the salt to the resultant hash.

// Append the salt to the hash
byte[] hashPlusSalt = new byte[hash.Length + salt.Length];
System.Buffer.BlockCopy(hash, 0, hashPlusSalt, 0, hash.Length);
System.Buffer.BlockCopy(salt, 0, hashPlusSalt, hash.Length, salt.Length);

e) Store the result in your user store database.

This approach means you don't need to store the salt separately and then recompute the hash using the salt value and the plaintext password value obtained from the user.

Edit: As raw computing power becomes cheaper and faster, the value of hashing -- or salting hashes -- has declined. Jeff Atwood has an excellent 2012 update too lengthy to repeat in its entirety here which states:

This (using salted hashes) will provide the illusion of security more than any actual security. Since you need both the salt and the choice of hash algorithm to generate the hash, and to check the hash, it's unlikely an attacker would have one but not the other. If you've been compromised to the point that an attacker has your password database, it's reasonable to assume they either have or can get your secret, hidden salt.

The first rule of security is to always assume and plan for the worst. Should you use a salt, ideally a random salt for each user? Sure, it's definitely a good practice, and at the very least it lets you disambiguate two users who have the same password. But these days, salts alone can no longer save you from a person willing to spend a few thousand dollars on video card hardware, and if you think they can, you're in trouble.

Error when trying vagrant up

There appears to be something wrong with the embedded curl program in Vagrant. Following the advice above I just renamed it (just in case I wanted it back) and vagrant up began to work as expected.

On my mac:

? .vagrant.d sudo mv /opt/vagrant/embedded/bin/curl /opt/vagrant/embedded/bin/curlOLD Password:

Adding values to Arraylist

Actually, a third is preferred:

ArrayList<Object> array = new ArrayList<Object>();
array.add(Integer.valueOf(3));
array.add("ss");

This avoids autoboxing (Integer.valueOf(3) versus 3) and doesn't create an unnecessary String object.

Eclipse complains when you don't use type arguments with a generic type like ArrayList, because you are using something called a raw type, which is discouraged. If a class is generic (that is, it has type parameters), then you should always use type arguments with that class.

Autoboxing, on the other hand, is a personal preference. Some people are okay with it, and some not. I don't like it, and I turn on the warning for autoboxing/autounboxing.

CSS text-overflow in a table cell?

It is worked for me

table {
    width: 100%;
    table-layout: fixed;
}

td {
   text-overflow: ellipsis;
   white-space: nowrap;
}

What is callback in Android?

CallBack Interface are used for Fragment to Fragment communication in android.

Refer here for your understanding.

JSON library for C#

Try the Vici Project, Vici Parser. It includes a JSON parser / tokeniser. It works great, we use it together with the MVC framework.

More info at: http://viciproject.com/wiki/projects/parser/home

I forgot to say that it is open source so you can always take a look at the code if you like.

finding the type of an element using jQuery

The following will return true if the element is an input:

$("#elementId").is("input") 

or you can use the following to get the name of the tag:

$("#elementId").get(0).tagName

Vim: insert the same characters across multiple lines

I wanted to comment out a lot of lines in some config file on a server that only had vi (no nano), so visual method was cumbersome as well Here's how i did that.

  1. Open file vi file
  2. Display line numbers :set number! or :set number
  3. Then use the line numbers to replace start-of-line with "#", how?

:35,77s/^/#/

Note: the numbers are inclusive, lines from 35 to 77, both included will be modified.

To uncomment/undo that, simply use :35,77s/^#//

If you want to add a text word as a comment after every line of code, you can also use:

:35,77s/$/#test/ (for languages like Python)

:35,77s/;$/;\/\/test/ (for languages like Java)

credits/references:

  1. https://unix.stackexchange.com/questions/84929/uncommenting-multiple-lines-of-code-specified-by-line-numbers-using-vi-or-vim

  2. https://unix.stackexchange.com/questions/120615/how-to-comment-multiple-lines-at-once

Saving the PuTTY session logging

I always have to check my cheatsheet :-)

Step 1: right-click on the top of putty window and select 'Change settings'.

Step 2: type the name of the session and save.

That's it!. Enjoy!

How do I determine whether my calculation of pi is accurate?

The Taylor series is one way to approximate pi. As noted it converges slowly.

The partial sums of the Taylor series can be shown to be within some multiplier of the next term away from the true value of pi.

Other means of approximating pi have similar ways to calculate the max error.

We know this because we can prove it mathematically.

Named tuple and default values for optional keyword arguments

Here's a short, simple generic answer with a nice syntax for a named tuple with default arguments:

import collections

def dnamedtuple(typename, field_names, **defaults):
    fields = sorted(field_names.split(), key=lambda x: x in defaults)
    T = collections.namedtuple(typename, ' '.join(fields))
    T.__new__.__defaults__ = tuple(defaults[field] for field in fields[-len(defaults):])
    return T

Usage:

Test = dnamedtuple('Test', 'one two three', two=2)
Test(1, 3)  # Test(one=1, three=3, two=2)

Minified:

def dnamedtuple(tp, fs, **df):
    fs = sorted(fs.split(), key=df.__contains__)
    T = collections.namedtuple(tp, ' '.join(fs))
    T.__new__.__defaults__ = tuple(df[i] for i in fs[-len(df):])
    return T

How to make Apache serve index.php instead of index.html?

As of today (2015, Aug., 1st), Apache2 in Debian Jessie, you need to edit:

root@host:/etc/apache2/mods-enabled$ vi dir.conf 

And change the order of that line, bringing index.php to the first position:

DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm

Recommendations of Python REST (web services) framework?

I don't see any reason to use Django just to expose a REST api, there are lighter and more flexible solutions. Django carries a lot of other things to the table, that are not always needed. For sure not needed if you only want to expose some code as a REST service.

My personal experience, fwiw, is that once you have a one-size-fits-all framework, you'll start to use its ORM, its plugins, etc. just because it's easy, and in no time you end up having a dependency that is very hard to get rid of.

Choosing a web framework is a tough decision, and I would avoid picking a full stack solution just to expose a REST api.

Now, if you really need/want to use Django, then Piston is a nice REST framework for django apps.

That being said, CherryPy looks really nice too, but seems more RPC than REST.

Looking at the samples (I never used it), probably web.py is the best and cleanest if you only need REST.

Remove Identity from a column in a table

Just for someone who have the same problem I did. If you just want to make some insert just once you can do something like this.

Lets suppose you have a table with two columns

ID Identity (1,1) | Name Varchar

and want to insert a row with the ID = 4. So you Reseed it to 3 so the next one is 4

DBCC CHECKIDENT([YourTable], RESEED, 3)

Make the Insert

INSERT  INTO [YourTable]
        ( Name )
VALUES  ( 'Client' )

And get your seed back to the highest ID, lets suppose is 15

DBCC CHECKIDENT([YourTable], RESEED, 15)

Done!

Finding Android SDK on Mac and adding to PATH

Find the Android SDK location

Android Studio 
  > Preferences
  > Appearance & Behaviour
  > System Settings 
  > Android SDK
  > Android SDK Location

Create a .bash_profile file for your environment variables

  • Open the Terminal app
  • Go to your home directory via cd ~
  • Create the file with touch .bash_profile

Add the PATH variable to your .bash_profile

  • Open the file via open .bash_profile
  • Add export PATH=$PATH: [your SDK location] /platform-tools to the file and hit ?s to save it. By default it's:

    export PATH=$PATH:/Users/yourUserName/Library/Android/sdk/platform-tools

  • Go back to your Terminal App and load the variable with source ~/.bash_profile

AttributeError: 'module' object has no attribute 'urlretrieve'

Suppose you have following lines of code

MyUrl = "www.google.com" #Your url goes here
urllib.urlretrieve(MyUrl)

If you are receiving following error message

AttributeError: module 'urllib' has no attribute 'urlretrieve'

Then you should try following code to fix the issue:

import urllib.request
MyUrl = "www.google.com" #Your url goes here
urllib.request.urlretrieve(MyUrl)

Pythonic way to check if a file exists?

Instead of os.path.isfile, suggested by others, I suggest using os.path.exists, which checks for anything with that name, not just whether it is a regular file.

Thus:

if not os.path.exists(filename):
    file(filename, 'w').close()

Alternatively:

file(filename, 'w+').close()

The latter will create the file if it exists, but not otherwise. It will, however, fail if the file exists, but you don't have permission to write to it. That's why I prefer the first solution.

(13: Permission denied) while connecting to upstream:[nginx]

  1. Check the user in /etc/nginx/nginx.conf
  2. Change ownership to user.
sudo chown -R nginx:nginx /var/lib/nginx

Now see the magic.

How to drop a unique constraint from table column?

To drop a UNIQUE constraint, you don’t need the name of the constraint, just the list of columns that are included in the constraint.

The syntax would be:

ALTER TABLE table_name DROP UNIQUE (column1, column2, . . . )

Where do I find the bashrc file on Mac?

~/.bashrc is already a path to .bashrc.

If you do echo ~ you'll see that it's a path to your home directory.

Homebrew directory is /usr/local/bin. Homebrew is installed inside it and everything installed by homebrew will be installed there.

For example, if you do brew install python Homebrew will put Python binary in /usr/local/bin.

Finally, to add Homebrew directory to your path you can run echo "export PATH=/usr/local/lib:$PATH" >> ~/.bashrc. It will create .bashrc file if it doesn't exist and then append the needed line to the end.

You can check the result by running tail ~/.bashrc.

How to print a number with commas as thousands separators in JavaScript

if you are dealing with currency values and formatting a lot then it might be worth to add tiny accounting.js which handles lot of edge cases and localization:

// Default usage:
accounting.formatMoney(12345678); // $12,345,678.00

// European formatting (custom symbol and separators), could also use options object as second param:
accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99

// Negative values are formatted nicely, too:
accounting.formatMoney(-500000, "£ ", 0); // £ -500,000

// Simple `format` string allows control of symbol position [%v = value, %s = symbol]:
accounting.formatMoney(5318008, { symbol: "GBP",  format: "%v %s" }); // 5,318,008.00 GBP

Spool Command: Do not output SQL statement to file

set echo off
spool c:\test.csv 
select /*csv*/ username, user_id, created from all_users;
spool off;

Remove last 3 characters of string or number in javascript

Here is an approach using str.slice(0, -n). Where n is the number of characters you want to truncate.

_x000D_
_x000D_
var str = 1437203995000;_x000D_
str = str.toString();_x000D_
console.log("Original data: ",str);_x000D_
str = str.slice(0, -3);_x000D_
str = parseInt(str);_x000D_
console.log("After truncate: ",str);
_x000D_
_x000D_
_x000D_

Get drop down value

<select onchange = "selectChanged(this.value)">
  <item value = "1">one</item>
  <item value = "2">two</item>
</select>

and then the javascript...

function selectChanged(newvalue) {
  alert("you chose: " + newvalue);
}

Deserialize JSON into C# dynamic object?

Simple "string JSON data" to object without any third-party DLL file:

WebClient client = new WebClient();
string getString = client.DownloadString("https://graph.facebook.com/zuck");

JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic item = serializer.Deserialize<object>(getString);
string name = item["name"];

//note: JavaScriptSerializer in this namespaces
//System.Web.Script.Serialization.JavaScriptSerializer

Note: You can also using your custom object.

Personel item = serializer.Deserialize<Personel>(getString);

Can't operator == be applied to generic types in C#?

In general, EqualityComparer<T>.Default.Equals should do the job with anything that implements IEquatable<T>, or that has a sensible Equals implementation.

If, however, == and Equals are implemented differently for some reason, then my work on generic operators should be useful; it supports the operator versions of (among others):

  • Equal(T value1, T value2)
  • NotEqual(T value1, T value2)
  • GreaterThan(T value1, T value2)
  • LessThan(T value1, T value2)
  • GreaterThanOrEqual(T value1, T value2)
  • LessThanOrEqual(T value1, T value2)

Convert Go map to json

Since this question was asked/last answered, support for non string key types for maps for json Marshal/UnMarshal has been added through the use of TextMarshaler and TextUnmarshaler interfaces here. You could just implement these interfaces for your key types and then json.Marshal would work as expected.

package main

import (
    "encoding/json"
    "fmt"
    "strconv"
)

// Num wraps the int value so that we can implement the TextMarshaler and TextUnmarshaler 
type Num int

func (n *Num) UnmarshalText(text []byte) error {
    i, err := strconv.Atoi(string(text))
    if err != nil {
        return err
    }
    *n = Num(i)
    return nil
}

func (n Num) MarshalText() (text []byte, err error) {
    return []byte(strconv.Itoa(int(n))), nil
}

type Foo struct {
    Number Num    `json:"number"`
    Title  string `json:"title"`
}

func main() {
    datas := make(map[Num]Foo)

    for i := 0; i < 10; i++ {
        datas[Num(i)] = Foo{Number: 1, Title: "test"}
    }

    jsonString, err := json.Marshal(datas)
    if err != nil {
        panic(err)
    }

    fmt.Println(datas)
    fmt.Println(jsonString)

    m := make(map[Num]Foo)
    err = json.Unmarshal(jsonString, &m)
    if err != nil {
        panic(err)
    }

    fmt.Println(m)
}

Output:

map[1:{1 test} 2:{1 test} 4:{1 test} 7:{1 test} 8:{1 test} 9:{1 test} 0:{1 test} 3:{1 test} 5:{1 test} 6:{1 test}]
[123 34 48 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 49 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 50 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 51 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 52 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 53 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 54 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 55 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 56 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 57 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 125]
map[4:{1 test} 5:{1 test} 6:{1 test} 7:{1 test} 0:{1 test} 2:{1 test} 3:{1 test} 1:{1 test} 8:{1 test} 9:{1 test}]

How to delete empty folders using windows command prompt?

from the command line: for /R /D %1 in (*) do rd "%1"

in a batch file for /R /D %%1 in (*) do rd "%%1"

I don't know if it's documented as such, but it works in W2K, XP, and Win 7. And I don't know if it will always work, but it won't ever delete files by accident.

Why is <deny users="?" /> included in the following example?

Example 1 is for asp.net applications using forms authenication. This is common practice for internet applications because user is unauthenticated until it is authentcation against some security module.

Example 2 is for asp.net application using windows authenication. Windows Authentication uses Active Directory to authenticate users. The will prevent access to your application. I use this feature on intranet applications.

Delete all rows in a table based on another table

This is old I know, but just a pointer to anyone using this ass a reference. I have just tried this and if you are using Oracle, JOIN does not work in DELETE statements. You get a the following message:

ORA-00933: SQL command not properly ended.

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

Try to change this: <csrf /> to this : <csrf disabled="true"/>. It should disable csfr.

How to sort by column in descending order in Spark SQL?

import org.apache.spark.sql.functions.desc

df.orderBy(desc("columnname1"),desc("columnname2"),asc("columnname3"))

How to add /usr/local/bin in $PATH on Mac

To make the edited value of path persists in the next sessions

cd ~/
touch .bash_profile
open .bash_profile

That will open the .bash_profile in editor, write inside the following after adding what you want to the path separating each value by column.

export PATH=$PATH:/usr/local/git/bin:/usr/local/bin:

Save, exit, restart your terminal and enjoy

How to prevent long words from breaking my div?

Two fixes:

  1. overflow:scroll -- this makes sure your content can be seen at the cost of design (scrollbars are ugly)
  2. overflow:hidden -- just cuts off any overflow. It means people can't read the content though.

If (in the SO example) you want to stop it overlapping the padding, you'd probably have to create another div, inside the padding, to hold your content.

Edit: As the other answers state, there are a variety of methods for truncating the words, be that working out the render width on the client side (never attempt to do this server-side as it will never work reliably, cross platform) through JS and inserting break-characters, or using non-standard and/or wildly incompatible CSS tags (word-wrap: break-word doesn't appear to work in Firefox).

You will always need an overflow descriptor though. If your div contains another too-wide block-type piece of content (image, table, etc), you'll need overflow to make it not destroy the layout/design.

So by all means use another method (or a combination of them) but remember to add overflow too so you cover all browsers.

Edit 2 (to address your comment below):

Start off using the CSS overflow property isn't perfect but it stops designs breaking. Apply overflow:hidden first. Remember that overflow might not break on padding so either nest divs or use a border (whatever works best for you).

This will hide overflowing content and therefore you might lose meaning. You could use a scrollbar (using overflow:auto or overflow:scroll instead of overflow:hidden) but depending on the dimensions of the div, and your design, this might not look or work great.

To fix it, we can use JS to pull things back and do some form of automated truncation. I was half-way through writing out some pseudo code for you but it gets seriously complicated about half-way through. If you need to show as much as possible, give hyphenator a look in (as mentioned below).

Just be aware that this comes at the cost of user's CPUs. It could result in pages taking a long time to load and/or resize.

Java string split with "." (dot)

The dot "." is a special character in java regex engine, so you have to use "\\." to escape this character:

final String extensionRemoved = filename.split("\\.")[0];

I hope this helps

Mocking static methods with Mockito

To mock static method you should use a Powermock look at: https://github.com/powermock/powermock/wiki/MockStatic. Mockito doesn't provide this functionality.

You can read nice a article about mockito: http://refcardz.dzone.com/refcardz/mockito

How to Verify if file exist with VB script

There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :

Option Explicit
DIM fso    
Set fso = CreateObject("Scripting.FileSystemObject")

If (fso.FileExists("C:\Program Files\conf")) Then
  WScript.Echo("File exists!")
  WScript.Quit()
Else
  WScript.Echo("File does not exist!")
End If

WScript.Quit()

How to get TimeZone from android mobile?

On my device TimeZone.getDefault() is always returning UTC time zone.

I need to do this to get user configured time zone :

TimeZone.setDefault(null)
val tz = TimeZone.getDefault()

It will return user selected timezone.

How to make Java Set?

Like this:

import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);

Or adding from an Array/ or multiple literals; wrap to a list, first.

Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b));         // from an array variable
b.addAll( Arrays.asList( 8, 9, 10));  // from literals

To get the intersection:

// copies all from A;  then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print;   r.toString() implied.
System.out.println("A intersect B="+r);

Hope this answer helps. Vote for it!

Getting first and last day of the current month

Try this code it is already built in c#

int lastDay = DateTime.DaysInMonth (2014, 2);

and the first day is always 1.

Good Luck!

Using git commit -a with vim

  1. In vim, you save a file with :wEnter while in the normal mode (you get to the normal mode by pressing Esc).
  2. You close your file with :q while in the normal mode.

You can combine both these actions and do Esc:wqEnter to save the commit and quit vim.

As an alternate to the above, you can also press ZZ while in the normal mode, which will save the file and exit vim. This is also easier for some people as it's the same key pressed twice.

Angular JS POST request not sending JSON data

try to use absolute url. if it not works, check if service's response has headers:

Access-Control-Allow-Origin and Access-Control-Allow-Headers

for example:

"Access-Control-Allow-Origin": "*"
"Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept"

Best practices for circular shift (rotate) operations in C++

In details you can apply the following logic.

If Bit Pattern is 33602 in Integer

1000 0011 0100 0010

and you need to Roll over with 2 right shifs then: first make a copy of bit pattern and then left shift it: Length - RightShift i.e. length is 16 right shift value is 2 16 - 2 = 14

After 14 times left shifting you get.

1000 0000 0000 0000

Now right shift the value 33602, 2 times as required. You get

0010 0000 1101 0000

Now take an OR between 14 time left shifted value and 2 times right shifted value.

1000 0000 0000 0000
0010 0000 1101 0000
===================
1010 0000 1101 0000
===================

And you get your shifted rollover value. Remember bit wise operations are faster and this don't even required any loop.

Redirect with CodeIgniter

If your directory structure is like this,

site
  application
         controller
                folder_1
                   first_controller.php
                   second_controller.php
                folder_2
                   first_controller.php
                   second_controller.php

And when you are going to redirect it in same controller in which you are working then just write the following code.

 $this->load->helper('url');
    if ($some_value === FALSE/TRUE) //You may give 0/1 as well,its up to your logic
    {
         redirect('same_controller/method', 'refresh');
    }

And if you want to redirect to another control then use the following code.

$this->load->helper('url');
if ($some_value === FALSE/TRUE) //You may give 0/1 as well,its up to your logic
{
     redirect('folder_name/any_controller_name/method', 'refresh');
}

Synchronous request in Node.js

Using deferreds like Futures.

var sequence = Futures.sequence();

sequence
  .then(function(next) {
     http.get({}, next);
  })
  .then(function(next, res) {
     res.on("data", next);
  })
  .then(function(next, d) {
     http.get({}, next);
  })
  .then(function(next, res) {
    ...
  })

If you need to pass scope along then just do something like this

  .then(function(next, d) {
    http.get({}, function(res) {
      next(res, d);
    });
  })
  .then(function(next, res, d) { })
    ...
  })

SQL query to find third highest salary in company

You can get the third highest salary by using limit , by using TOP keyword and sub-query

  1. TOP keyword

    SELECT TOP 1 salary 
    FROM 
        (SELECT TOP 3 salary 
         FROM Table_Name 
         ORDER BY salary DESC) AS Comp 
    ORDER BY salary ASC
    
  2. limit

    SELECT salary 
    FROM Table_Name 
    ORDER BY salary DESC 
    LIMIT 2, 1
    
  3. by subquery

    SELECT salary  
    FROM 
        (SELECT salary 
         FROM Table_Name 
         ORDER BY salary DESC 
         LIMIT 3) AS Comp 
    ORDER BY salary 
    LIMIT 1;
    

I think anyone of these help you.

How do I add a linker or compile flag in a CMake file?

You can also add linker flags to a specific target using the LINK_FLAGS property:

set_property(TARGET ${target} APPEND_STRING PROPERTY LINK_FLAGS " ${flag}")

If you want to propagate this change to other targets, you can create a dummy target to link to.

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

Add this to your gemfile:

gem 'cliver', :git => 'git://github.com/yaauie/cliver', :ref => '5617ce'

How to enable production mode?

This worked for me, using the latest release of Angular 2 (2.0.0-rc.1):

main.ts

import {enableProdMode} from '@angular/core';

enableProdMode();
bootstrap(....);

Here is the function reference from their docs: https://angular.io/api/core/enableProdMode

How do I check if an object has a specific property in JavaScript?

With Underscore.js or (even better) Lodash:

_.has(x, 'key');

Which calls Object.prototype.hasOwnProperty, but (a) is shorter to type, and (b) uses "a safe reference to hasOwnProperty" (i.e. it works even if hasOwnProperty is overwritten).

In particular, Lodash defines _.has as:

   function has(object, key) {
      return object ? hasOwnProperty.call(object, key) : false;
   }
   // hasOwnProperty = Object.prototype.hasOwnProperty

Using "like" wildcard in prepared statement

Code it like this:

PreparedStatement pstmt = con.prepareStatement(
    "SELECT * FROM analysis WHERE notes like ?");
pstmt.setString(1, notes + "%");`

Make sure that you DO NOT include the quotes ' ' like below as they will cause an exception.

pstmt.setString(1,"'%"+ notes + "%'");

How to create a directory in Java?

Neat and clean:

import java.io.File;

public class RevCreateDirectory {

    public void revCreateDirectory() {
        //To create single directory/folder
        File file = new File("D:\\Directory1");
        if (!file.exists()) {
            if (file.mkdir()) {
                System.out.println("Directory is created!");
            } else {
                System.out.println("Failed to create directory!");
            }
        }
        //To create multiple directories/folders
        File files = new File("D:\\Directory2\\Sub2\\Sub-Sub2");
        if (!files.exists()) {
            if (files.mkdirs()) {
                System.out.println("Multiple directories are created!");
            } else {
                System.out.println("Failed to create multiple directories!");
            }
        }

    }
}

Convert tuple to list and back

Both the answers are good, but a little advice:

Tuples are immutable, which implies that they cannot be changed. So if you need to manipulate data, it is better to store data in a list, it will reduce unnecessary overhead.

In your case extract the data to a list, as shown by eumiro, and after modifying create a similar tuple of similar structure as answer given by Schoolboy.

Also as suggested using numpy array is a better option

Check object empty

If your Object contains Objects then check if they are null, if it have primitives check for their default values.

for Instance:

Person Object 
name Property with getter and setter

to check if name is not initialized. 

Person p = new Person();
if(p.getName()!=null)

How to return a value from __init__ in Python?

init() return none value solved perfectly

class Solve:
def __init__(self,w,d):
    self.value=w
    self.unit=d
def __str__(self):
    return str("my speed is "+str(self.value)+" "+str(self.unit))
ob=Solve(21,'kmh')
print (ob)

output: my speed is 21 kmh

How to Convert date into MM/DD/YY format in C#

 DateTime.Today.ToString("MM/dd/yy")

Look at the docs for custom date and time format strings for more info.

(Oh, and I hope this app isn't destined for other cultures. That format could really confuse a lot of people... I've never understood the whole month/day/year thing, to be honest. It just seems weird to go "middle/low/high" in terms of scale like that.)

Javascript receipt printing using POS Printer

If you are talking about a browser based POS app then it basically can't be done out of the box. There are a number of alternatives.

  1. Use an applet like Scott Selby says
  2. Print from the server. If this is a cloud server, ie not connectable to the receipt printer then what you can do is
    • From the server generate it as a pdf which can be made to popup a print dialog in the browser
    • Use something like Google Cloud Print which will allow connecting printers to a cloud service

How to resolve "must be an instance of string, string given" prior to PHP 7?

(originally posted by leepowers in his question)

The error message is confusing for one big reason:

Primitive type names are not reserved in PHP

The following are all valid class declarations:

class string { }
class int { }
class float { }
class double { }

My mistake was in thinking that the error message was referring solely to the string primitive type - the word 'instance' should have given me pause. An example to illustrate further:

class string { }
$n = 1234;
$s1 = (string)$n;
$s2 = new string();
$a = array('no', 'yes');
printf("\$s1 - primitive string? %s - string instance? %s\n",
        $a[is_string($s1)], $a[is_a($s1, 'string')]);
printf("\$s2 - primitive string? %s - string instance? %s\n",
        $a[is_string($s2)], $a[is_a($s2, 'string')]);

Output:

$s1 - primitive string? yes - string instance? no

$s2 - primitive string? no - string instance? yes

In PHP it's possible for a string to be a string except when it's actually a string. As with any language that uses implicit type conversion, context is everything.

Index was out of range. Must be non-negative and less than the size of the collection parameter name:index

what this means ? is there any problem in my code

It means that you are accessing a location or index which is not present in collection.

To find this, Make sure your Gridview has 5 columns as you are using it's 5th column by this line

dataGridView1.Columns[4].Name = "Amount";

Here is the image which shows the elements of an array. So if your gridview has less column then the (index + 1) by which you are accessing it, then this exception arises.

enter image description here

Subtracting 1 day from a timestamp date

Use the INTERVAL type to it. E.g:

--yesterday
SELECT NOW() - INTERVAL '1 DAY';

--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;

Then you can do the following on your query:

SELECT 
    org_id,
    count(accounts) AS COUNT,
    ((date_at) - INTERVAL '1 DAY') AS dateat
FROM 
    sourcetable
WHERE 
    date_at <= now() - INTERVAL '130 DAYS'
GROUP BY 
    org_id,
    dateat;


TIPS

Tip 1

You can append multiple operands. E.g.: how to get last day of current month?

SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';

Tip 2

You can also create an interval using make_interval function, useful when you need to create it at runtime (not using literals):

SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);


More info:

Date/Time Functions and Operators

datatype-datetime (Especial values).

What does yield mean in PHP?

simple example

<?php
echo '#start main# ';
function a(){
    echo '{start[';
    for($i=1; $i<=9; $i++)
        yield $i;
    echo ']end} ';
}
foreach(a() as $v)
    echo $v.',';
echo '#end main#';
?>

output

#start main# {start[1,2,3,4,5,6,7,8,9,]end} #end main#

advanced example

<?php
echo '#start main# ';
function a(){
    echo '{start[';
    for($i=1; $i<=9; $i++)
        yield $i;
    echo ']end} ';
}
foreach(a() as $k => $v){
    if($k === 5)
        break;
    echo $k.'=>'.$v.',';
}
echo '#end main#';
?>

output

#start main# {start[0=>1,1=>2,2=>3,3=>4,4=>5,#end main#

Change bar plot colour in geom_bar with ggplot2 in r

If you want all the bars to get the same color (fill), you can easily add it inside geom_bar.

ggplot(data=df, aes(x=c1+c2/2, y=c3)) + 
geom_bar(stat="identity", width=c2, fill = "#FF6666")

enter image description here

Add fill = the_name_of_your_var inside aes to change the colors depending of the variable :

c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2)

enter image description here

Use scale_fill_manual() if you want to manually the change of colors.

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2) + 
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))

enter image description here

Java get last element of a collection

There isn't a last() or first() method in a Collection interface. For getting the last method, you can either do get(size() - 1) on a List or reverse the List and do get(0). I don't see a need to have last() method in any Collection API unless you are dealing with Stacks or Queues

Is it good practice to use the xor operator for boolean checks?

I recently used an xor in a JavaScript project at work and ended up adding 7 lines of comments to explain what was going on. The justification for using xor in that context was that one of the terms (term1 in the example below) could take on not two but three values: undefined, true or false while the other (term2) could be true or false. I would have had to add an additional check for the undefined cases but with xor, the following was sufficient since the xor forces the first term to be first evaluated as a Boolean, letting undefined get treated as false:

if (term1 ^ term2) { ...

It was, in the end, a bit of an overkill, but I wanted to keep it in there anyway, as sort of an easter egg.

How to use null in switch

Some libraries attempt to offer alternatives to the builtin java switch statement. Vavr is one of them, they generalize it to pattern matching.

Here is an example from their documentation:

String s = Match(i).of(
    Case($(1), "one"),
    Case($(2), "two"),
    Case($(), "?")
);

You can use any predicate, but they offer many of them out of the box, and $(null) is perfectly legal. I find this a more elegant solution than the alternatives, but this requires java8 and a dependency on the vavr library...

How to create multidimensional array

Quote taken from Data Structures and Algorithms with JavaScript

The Good Parts (O’Reilly, p. 64). Crockford extends the JavaScript array object with a function that sets the number of rows and columns and sets each value to a value passed to the function. Here is his definition:

Array.matrix = function(numrows, numcols, initial) {
    var arr = [];
    for (var i = 0; i < numrows; ++i) {
        var columns = [];
        for (var j = 0; j < numcols; ++j) {
            columns[j] = initial;
        }
        arr[i] = columns;
    }
    return arr;
}

Here is some code to test the definition:

var nums = Array.matrix(5,5,0);
print(nums[1][1]); // displays 0
var names = Array.matrix(3,3,"");
names[1][2] = "Joe";
print(names[1][2]); // display "Joe"

We can also create a two-dimensional array and initialize it to a set of values in one line:

var grades = [[89, 77, 78],[76, 82, 81],[91, 94, 89]];
print(grades[2][2]); // displays 89

Making sure at least one checkbox is checked

This should work:

function valthisform()
{
    var checkboxs=document.getElementsByName("c1");
    var okay=false;
    for(var i=0,l=checkboxs.length;i<l;i++)
    {
        if(checkboxs[i].checked)
        {
            okay=true;
            break;
        }
    }
    if(okay)alert("Thank you for checking a checkbox");
    else alert("Please check a checkbox");
}

If you have a question about the code, just comment.


I use l=checkboxs.length to improve the performance. See http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/

How to disable back swipe gesture in UINavigationController on iOS 7

swift 5, swift 4.2 can use the code in the below.

// disable
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
// enable
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true

An Iframe I need to refresh every 30 seconds (but not the whole page)

You can put a meta refresh Tag in the irc_online.php

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

OR you can use Javascript with setInterval to refresh the src of the Source...

<script>
window.setInterval("reloadIFrame();", 30000);

function reloadIFrame() {
 document.frames["frameNameHere"].location.reload();
}
</script>

Capture key press (or keydown) event on DIV element

tabindex HTML attribute indicates if its element can be focused, and if/where it participates in sequential keyboard navigation (usually with the Tab key). Read MDN Web Docs for full reference.

Using Jquery

_x000D_
_x000D_
$( "#division" ).keydown(function(evt) {
    evt = evt || window.event;
    console.log("keydown: " + evt.keyCode);
});
_x000D_
#division {
  width: 90px;
  height: 30px;
  background: lightgrey;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="division" tabindex="0"></div>
_x000D_
_x000D_
_x000D_

Using JavaScript

_x000D_
_x000D_
var el = document.getElementById("division");

el.onkeydown = function(evt) {
    evt = evt || window.event;
    console.log("keydown: " + evt.keyCode);
};
_x000D_
#division {
  width: 90px;
  height: 30px;
  background: lightgrey;
}
_x000D_
<div id="division" tabindex="0"></div>
_x000D_
_x000D_
_x000D_

How do I add FTP support to Eclipse?

have you checked RSE (Remote System Explorer) ? I think it's pretty close to what you want to achieve.

a blog post about it, with screenshots

Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)

You should set your RecyclerView LayoutManager to Gridlayout mode. Just change your code when you want to set your RecyclerView LayoutManager:

recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), numberOfColumns));

Psexec "run as (remote) admin"

Use psexec -s

The s switch will cause it to run under system account which is the same as running an elevated admin prompt. just used it to enable WinRM remotely.

How to get value by class name in JavaScript or jquery?

Try this:

$(document).ready(function(){
    var yourArray = [];
    $("span.HOEnZb").find("div").each(function(){
        if(($.trim($(this).text()).length>0)){
         yourArray.push($(this).text());
        }
    });
});

DEMO

How to get the top 10 values in postgresql?

Seems you are looking for ORDER BY in DESCending order with LIMIT clause:

SELECT
 *
FROM
  scores
ORDER BY score DESC
LIMIT 10

Of course SELECT * could seriously affect performance, so use it with caution.

How do I check if a string contains another string in Swift?

Just an addendum to the answers here.

You can also do a local case insensitive test using:

 - (BOOL)localizedCaseInsensitiveContainsString:(NSString *)aString

Example:

    import Foundation

    var string: NSString  =  "hello Swift"
   if string.localizedCaseInsensitiveContainsString("Hello") {
    println("TRUE")
}

UPDATE

This is part of the Foundation Framework for iOS & Mac OS X 10.10.x and was part of 10.10 at Time of my original Posting.

Document Generated: 2014-06-05 12:26:27 -0700 OS X Release Notes Copyright © 2014 Apple Inc. All Rights Reserved.

OS X 10.10 Release Notes Cocoa Foundation Framework

NSString now has the following two convenience methods:

- (BOOL)containsString:(NSString *)str;

- (BOOL)localizedCaseInsensitiveContainsString:(NSString *)str;

How do I download a binary file over HTTP?

Here is my Ruby http to file using open(name, *rest, &block).

require "open-uri"
require "fileutils"

def download(url, path)
  case io = open(url)
  when StringIO then File.open(path, 'w') { |f| f.write(io.read) }
  when Tempfile then io.close; FileUtils.mv(io.path, path)
  end
end

The main advantage here it is concise and simple, because open does much of the heavy lifting. And it does not read the whole response in memory.

The open method will stream responses > 1kb to a Tempfile. We can exploit this knowledge to implement this lean download to file method. See the OpenURI::Buffer implementation here.

Please be careful with user provided input! open(name, *rest, &block) is unsafe if name is coming from user input!

What is a "static" function in C?

There is a big difference between static functions in C and static member functions in C++. In C, a static function is not visible outside of its translation unit, which is the object file it is compiled into. In other words, making a function static limits its scope. You can think of a static function as being "private" to its *.c file (although that is not strictly correct).

In C++, "static" can also apply to member functions and data members of classes. A static data member is also called a "class variable", while a non-static data member is an "instance variable". This is Smalltalk terminology. This means that there is only one copy of a static data member shared by all objects of a class, while each object has its own copy of a non-static data member. So a static data member is essentially a global variable, that is a member of a class.

Non-static member functions can access all data members of the class: static and non-static. Static member functions can only operate on the static data members.

One way to think about this is that in C++ static data members and static member functions do not belong to any object, but to the entire class.

How do I log errors and warnings into a file?

See

  • error_log — Send an error message somewhere

Example

error_log("You messed up!", 3, "/var/tmp/my-errors.log");

You can customize error handling with your own error handlers to call this function for you whenever an error or warning or whatever you need to log occurs. For additional information, please refer to the Chapter Error Handling in the PHP Manual

multiple packages in context:component-scan, spring config

If x.y.z is the common package then you can use:

<context:component-scan base-package="x.y.z.*">

it will include all the package that is start with x.y.z like: x.y.z.controller,x.y.z.service etc.

Unable to connect with remote debugger

Try adding this

package.json

devDependencies: {
//...    
    "@react-native-community/cli-debugger-ui": "4.7.0"
}

Terminate everything.

  • npm install
  • npx react-native start
  • npx react-native run-android

Reference: https://github.com/react-native-community/cli/issues/1081#issuecomment-614223917

PHP: How to check if image file exists?

You can use the file_get_contents function to access remote files. See http://php.net/manual/en/function.file-get-contents.php for details.

Is there a good JSP editor for Eclipse?

I followed the advice of Simon Gibbs in this answer and found it worked out fine - if you're in a hurry, the "Web Page Editor (optional)" package from the Eclipse update site does the trick.

For the Eclipse-challenged (me) Help > Install New Software > Work with > Expand Web, XML, and Java EE Development > Select "Web Page Editor (optional)" and "next-through" to completion.

Can I install the "app store" in an IOS simulator?

No, according to Apple here:

Note: You cannot install apps from the App Store in simulation environments.

"Expected BEGIN_OBJECT but was STRING at line 1 column 1"

In my case, I am Returning JSON Object as

{"data":"","message":"Attendance Saved Successfully..!!!","status":"success"}

Resolved by changing it as

{"data":{},"message":"Attendance Saved Successfully..!!!","status":"success"}

Here data is a sub JsonObject and it should starts from { not ""

Convert 4 bytes to int

Converting a 4-byte array into integer:

//Explictly declaring anInt=-4, byte-by-byte
byte[] anInt = {(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xfc}; // Equals -4
//And now you have a 4-byte array with an integer equaling -4...
//Converting back to integer from 4-bytes...
result = (int) ( anInt[0]<<24 | ( (anInt[1]<<24)>>>8 ) | ( (anInt[2]<<24)>>>16) | ( (anInt[3]<<24)>>>24) );

How to set IntelliJ IDEA Project SDK

For IntelliJ IDEA 2017.2 I did the following to fix this issue: Go to your project structure enter image description here Now go to SDKs under platform settings and click the green add button. Add your JDK path. In my case it was this path C:\Program Files\Java\jdk1.8.0_144 enter image description here Now Just go Project under Project settings and select the project SDK. enter image description here

Passing a variable from node.js to html

I figured it out I was able to pass a variable like this

<script>var name = "<%= name %>";</script>
console.log(name);

Node.js – events js 72 throw er unhandled 'error' event

Well, your script throws an error and you just need to catch it (and/or prevent it from happening). I had the same error, for me it was an already used port (EADDRINUSE).

How to wait for a process to terminate to execute another process in batch file

This works and is even simpler. If you remove ECHO-s, it will be even smaller:

REM
REM DEMO - how to launch several processes in parallel, and wait until all of them finish.
REM

@ECHO OFF
start "!The Title!" Echo Close me manually!
start "!The Title!" Echo Close me manually!
:waittofinish
echo At least one process is still running...
timeout /T 2 /nobreak >nul
tasklist.exe /fi "WINDOWTITLE eq !The Title!" | find ":" >nul
if errorlevel 1 goto waittofinish
echo Finished!
PAUSE

Resolving LNK4098: defaultlib 'MSVCRT' conflicts with

IMO this link from Yochai Timmer was very good and relevant but painful to read. I wrote a summary.

Yochai, if you ever read this, please see the note at the end.


For the original post read : warning LNK4098: defaultlib "LIBCD" conflicts with use of other libs

Error

LINK : warning LNK4098: defaultlib "LIBCD" conflicts with use of other libs; use /NODEFAULTLIB:library

Meaning

one part of the system was compiled to use a single threaded standard (libc) library with debug information (libcd) which is statically linked

while another part of the system was compiled to use a multi-threaded standard library without debug information which resides in a DLL and uses dynamic linking

How to resolve

  • Ignore the warning, after all it is only a warning. However, your program now contains multiple instances of the same functions.

  • Use the linker option /NODEFAULTLIB:lib. This is not a complete solution, even if you can get your program to link this way you are ignoring a warning sign: the code has been compiled for different environments, some of your code may be compiled for a single threaded model while other code is multi-threaded.

  • [...] trawl through all your libraries and ensure they have the correct link settings

In the latter, as it in mentioned in the original post, two common problems can arise :

  • You have a third party library which is linked differently to your application.

  • You have other directives embedded in your code: normally this is the MFC. If any modules in your system link against MFC all your modules must nominally link against the same version of MFC.

For those cases, ensure you understand the problem and decide among the solutions.


Note : I wanted to include that summary of Yochai Timmer's link into his own answer but since some people have trouble to review edits properly I had to write it in a separate answer. Sorry

Copy table from one database to another

SELECT ... INTO :

select * into <destination table> from <source table>

How to hash a string into 8 digits?

Yes, you can use the built-in hashlib module or the built-in hash function. Then, chop-off the last eight digits using modulo operations or string slicing operations on the integer form of the hash:

>>> s = 'she sells sea shells by the sea shore'

>>> # Use hashlib
>>> import hashlib
>>> int(hashlib.sha1(s.encode("utf-8")).hexdigest(), 16) % (10 ** 8)
58097614L

>>> # Use hash()
>>> abs(hash(s)) % (10 ** 8)
82148974

Render partial from different folder (not shared)

The VirtualPathProviderViewEngine, on which the WebFormsViewEngine is based, is supposed to support the "~" and "/" characters at the front of the path so your examples above should work.

I noticed your examples use the path "~/Account/myPartial.ascx", but you mentioned that your user control is in the Views/Account folder. Have you tried

<%Html.RenderPartial("~/Views/Account/myPartial.ascx");%>

or is that just a typo in your question?

Simple jQuery, PHP and JSONP example?

First of all you can't make a POST request using JSONP.

What basically is happening is that dynamically a script tag is inserted to load your data. Therefore only GET requests are possible.

Furthermore your data has to be wrapped in a callback function which is called after the request is finished to load the data in a variable.

This whole process is automated by jQuery for you. Just using $.getJSON on an external domain doesn't always work though. I can tell out of personal experience.

The best thing to do is adding &callback=? to you url.

At the server side you've got to make sure that your data is wrapped in this callback function.

ie.

echo $_GET['callback'] . '(' . $data . ')';

EDIT:

Don't have enough rep yet to comment on Liam's answer so therefore the solution over here.

Replace Liam's line

 echo "{'fullname' : 'Jeff Hansen'}";

with

 echo $_GET['callback'] . '(' . "{'fullname' : 'Jeff Hansen'}" . ')';

How to create a link to another PHP page

Easiest:

<a href="page2.php">Link</a>

And if you need to pass a value:

<a href="page2.php?val=1">Link that pass the value 1</a>

To retrive the value put in page2.php this code:

<?php
$val = $_GET["val"];
?>

Now the variable $val has the value 1.

Why do I get a warning icon when I add a reference to an MEF plugin project?

For both of (or all of) the projects that you want to use together:

Right click on the project > Properties > Application > Target .NET framework

Make sure that both of (or all of) your projects are using the same .NET framework version.

Property [title] does not exist on this collection instance

You Should Used Collection keyword in Controller. Like Here..

public function ApiView(){
    return User::collection(Profile::all());
}

Here, User is Resource Name and Profile is Model Name. Thank You.

Drop multiple tables in one shot in MySQL

Example:

Let's say table A has two children B and C. Then we can use the following syntax to drop all tables.

DROP TABLE IF EXISTS B,C,A;

This can be placed in the beginning of the script instead of individually dropping each table.

How can I change the image of an ImageView?

If you created imageview using xml file then follow the steps.

Solution 1:

Step 1: Create an XML file

<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:background="#cc8181"
  >

  <ImageView
      android:id="@+id/image"
      android:layout_width="50dip"
      android:layout_height="fill_parent" 
      android:src="@drawable/icon"
      android:layout_marginLeft="3dip"
      android:scaleType="center"/>

</LinearLayout>

Step 2: create an Activity

ImageView img= (ImageView) findViewById(R.id.image);
img.setImageResource(R.drawable.my_image);

Solution 2:

If you created imageview from Java Class

ImageView img = new ImageView(this);
img.setImageResource(R.drawable.my_image);

Redirect from an HTML page

You don't need any JavaScript code for this. Write this in the <head> section of the HTML page:

<meta http-equiv="refresh" content="0; url=example.com" />

As soon as the page loads at 0 seconds, you can go to your page.

Remove quotes from String in Python

if string.startswith('"'):
    string = string[1:]

if string.endswith('"'):
    string = string[:-1]

What .NET collection provides the fastest search

If you're using .Net 3.5, you can make cleaner code using:

foreach (Record item in LookupCollection.Intersect(LargeCollection))
{
  //dostuff
}

I don't have .Net 3.5 here and so this is untested. It relies on an extension method. Not that LookupCollection.Intersect(LargeCollection) is probably not the same as LargeCollection.Intersect(LookupCollection) ... the latter is probably much slower.

This assumes LookupCollection is a HashSet

Access: Move to next record until EOF

If (Not IsNull(Me.id.Value)) Then
DoCmd.GoToRecord , , acNext
End If

Hi, you need to put this in form activate, and have an id field named id...

this way it passes until it reaches the one without id (AKA new one)...

Solving SharePoint Server 2010 - 503. The service is unavailable, After installation

It can also happen if your password policy or something else have changed your password in case your appPools are using the the user with changed password.

So, you should update the user password from the advanced settings of your appPool throught "Identity" property.

The reference is here

How to append a date in batch files

There is a tech recipe available here that shows how to format it to MMDDYYYY, you should be able to adapt it for your needs.

echo on
@REM Seamonkey’s quick date batch (MMDDYYYY format)
@REM Setups %date variable
@REM First parses month, day, and year into mm , dd, yyyy formats and then combines to be MMDDYYYY
FOR /F "TOKENS=1* DELIMS= " %%A IN ('DATE/T') DO SET CDATE=%%B
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2 DELIMS=/ eol=/" %%A IN ('echo %CDATE%') DO SET dd=%%B
FOR /F "TOKENS=2,3 DELIMS=/ " %%A IN ('echo %CDATE%') DO SET yyyy=%%B
SET date=%mm%%dd%%yyyy%

echo %date%

EDIT: The reason did not work before was because of 'smartquotes' in the original text. I fixed them and the batch file will work if cut & pasted from this page.

Multiple GitHub Accounts & SSH Config

A possibly simpler alternative to editing the ssh config file (as suggested in all other answers), is to configure an individual repository to use a different (e.g. non-default) ssh key.

Inside the repository for which you want to use a different key, run:

git config core.sshCommand 'ssh -i ~/.ssh/id_rsa_anotheraccount'

If your key is passhprase-protected and you don't want to type your password every time, you have to add it to the ssh-agent. Here's how to do it for ubuntu and here for macOS.

It should also be possible to scale this approach to multiple repositories using global git config and conditional includes (see example).

How to create a laravel hashed password

use Illuminate\Support\Facades\Hash;
if(Hash::check($plain-text,$hashed-text))
    {
       return true;
    }
    else
    {
        return false;
    }

eg- $plain-text = 'text'; $hashed-text=Hash::make('text');

Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab

I will soon released a new version of my app to support to galaxy ace.

You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree

In order to solve your problem you should do this:

this._camera = Camera.open();     
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});

Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);

params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);

don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true

to turn off the led just release the camera

Download history stock prices automatically from yahoo finance in python

Short answer: Yes. Use Python's urllib to pull the historical data pages for the stocks you want. Go with Yahoo! Finance; Google is both less reliable, has less data coverage, and is more restrictive in how you can use it once you have it. Also, I believe Google specifically prohibits you from scraping the data in their ToS.

Longer answer: This is the script I use to pull all the historical data on a particular company. It pulls the historical data page for a particular ticker symbol, then saves it to a csv file named by that symbol. You'll have to provide your own list of ticker symbols that you want to pull.

import urllib

base_url = "http://ichart.finance.yahoo.com/table.csv?s="
def make_url(ticker_symbol):
    return base_url + ticker_symbol

output_path = "C:/path/to/output/directory"
def make_filename(ticker_symbol, directory="S&P"):
    return output_path + "/" + directory + "/" + ticker_symbol + ".csv"

def pull_historical_data(ticker_symbol, directory="S&P"):
    try:
        urllib.urlretrieve(make_url(ticker_symbol), make_filename(ticker_symbol, directory))
    except urllib.ContentTooShortError as e:
        outfile = open(make_filename(ticker_symbol, directory), "w")
        outfile.write(e.content)
        outfile.close()

How to connect to a remote MySQL database with Java?

Close all the connection which is open & connected to the server listen port, whatever it is from application or client side tool (navicat) or on running server (apache or weblogic). First close all connection then restart all tools MySQL,apache etc.

How to identify all stored procedures referring a particular table

SELECT DISTINCT OBJECT_NAME(OBJECT_ID),
object_definition(OBJECT_ID)
FROM sys.Procedures
WHERE object_definition(OBJECT_ID) LIKE '%' + 'table_name' + '%'

GO

This will work if you have to mention the table name.