Programs & Examples On #Ejb

Enterprise JavaBeans (EJB) is a managed, server-side component architecture for modular construction of enterprise applications. The EJB specification is one of several [Java] APIs in the [Java EE] specification.

Cannot instantiate the type List<Product>

Interfaces can not be directly instantiated, you should instantiate classes that implements such Interfaces.

Try this:

NameValuePair[] params = new BasicNameValuePair[] {
        new BasicNameValuePair("param1", param1),
        new BasicNameValuePair("param2", param2),
};

Should I use @EJB or @Inject

Update: This answer may be incorrect or out of date. Please see comments for details.

I switched from @Inject to @EJB because @EJB allows circular injection whereas @Inject pukes on it.

Details: I needed @PostConstruct to call an @Asynchronous method but it would do so synchronously. The only way to make the asynchronous call was to have the original call a method of another bean and have it call back the method of the original bean. To do this each bean needed a reference to the other -- thus circular. @Inject failed for this task whereas @EJB worked.

Android Min SDK Version vs. Target SDK Version

android:minSdkVersion and android:targetSdkVersion both are Integer value we need to declare in android manifest file but both are having different properties.

android:minSdkVersion: This is minimum required API level to run an android app. If we will install the same app on lower API version the parser error will be appear, and application not support problem will appear.

android:targetSdkVersion: Target sdk version is to set the Target API level of app. if this attribute not declared in manifest, minSdk version will be your TargetSdk Version. This is always true that "app support installation on all higher version of API we declared as TargetSdk Version". To make app limited target we need to declare maxSdkVersion in our manifest file...

How do you write multiline strings in Go?

From String literals:

  • raw string literal supports multiline (but escaped characters aren't interpreted)
  • interpreted string literal interpret escaped characters, like '\n'.

But, if your multi-line string has to include a backquote (`), then you will have to use an interpreted string literal:

`line one
  line two ` +
"`" + `line three
line four`

You cannot directly put a backquote (`) in a raw string literal (``xx\).
You have to use (as explained in "how to put a backquote in a backquoted string?"):

 + "`" + ...

swift How to remove optional String Character

import UIKit

let characters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]

var a: String = characters.randomElement()!
var b: String = characters.randomElement()!
var c: String = characters.randomElement()!
var d: String = characters.randomElement()!
var e: String = characters.randomElement()!
var f: String = characters.randomElement()!
var password = ("\(a)" + "\(b)" + "\(c)" + "\(d)" + "\(e)" + "\(f)")

    print ( password)

Select from one table matching criteria in another?

I have a similar problem (at least I think it is similar). In one of the replies here the solution is as follows:

select
    A.*
from
    table_A A
inner join table_B B
    on A.id = B.id
where
    B.tag = 'chair'

That WHERE clause I would like to be:

WHERE B.tag = A.<col_name>

or, in my specific case:

WHERE B.val BETWEEN A.val1 AND A.val2

More detailed:

Table A carries status information of a fleet of equipment. Each status record carries with it a start and stop time of that status. Table B carries regularly recorded, timestamped data about the equipment, which I want to extract for the duration of the period indicated in table A.

Nginx not running with no error message

You should probably check for errors in /var/log/nginx/error.log.

In my case I did no add the port for ipv6. You should also do this (in case you are running nginx on a port other than 80): listen [::]:8000 default_server ipv6only=on;

How to install latest version of openssl Mac OS X El Capitan

You can run brew link openssl to link it into /usr/local, if you don't mind the potential problem highlighted in the warning message. Otherwise, you can add the openssl bin directory to your path:

export PATH=$(brew --prefix openssl)/bin:$PATH

Android : Check whether the phone is dual SIM

Update 23 March'15 :

Official multiple SIM API is available now from Android 5.1 onwards

Other possible option :

You can use Java reflection to get both IMEI numbers.

Using these IMEI numbers you can check whether the phone is a DUAL SIM or not.

Try following activity :

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TelephonyInfo telephonyInfo = TelephonyInfo.getInstance(this);

        String imeiSIM1 = telephonyInfo.getImsiSIM1();
        String imeiSIM2 = telephonyInfo.getImsiSIM2();

        boolean isSIM1Ready = telephonyInfo.isSIM1Ready();
        boolean isSIM2Ready = telephonyInfo.isSIM2Ready();

        boolean isDualSIM = telephonyInfo.isDualSIM();

        TextView tv = (TextView) findViewById(R.id.tv);
        tv.setText(" IME1 : " + imeiSIM1 + "\n" +
                " IME2 : " + imeiSIM2 + "\n" +
                " IS DUAL SIM : " + isDualSIM + "\n" +
                " IS SIM1 READY : " + isSIM1Ready + "\n" +
                " IS SIM2 READY : " + isSIM2Ready + "\n");
    }
}

And here is TelephonyInfo.java :

import java.lang.reflect.Method;

import android.content.Context;
import android.telephony.TelephonyManager;

public final class TelephonyInfo {

    private static TelephonyInfo telephonyInfo;
    private String imeiSIM1;
    private String imeiSIM2;
    private boolean isSIM1Ready;
    private boolean isSIM2Ready;

    public String getImsiSIM1() {
        return imeiSIM1;
    }

    /*public static void setImsiSIM1(String imeiSIM1) {
        TelephonyInfo.imeiSIM1 = imeiSIM1;
    }*/

    public String getImsiSIM2() {
        return imeiSIM2;
    }

    /*public static void setImsiSIM2(String imeiSIM2) {
        TelephonyInfo.imeiSIM2 = imeiSIM2;
    }*/

    public boolean isSIM1Ready() {
        return isSIM1Ready;
    }

    /*public static void setSIM1Ready(boolean isSIM1Ready) {
        TelephonyInfo.isSIM1Ready = isSIM1Ready;
    }*/

    public boolean isSIM2Ready() {
        return isSIM2Ready;
    }

    /*public static void setSIM2Ready(boolean isSIM2Ready) {
        TelephonyInfo.isSIM2Ready = isSIM2Ready;
    }*/

    public boolean isDualSIM() {
        return imeiSIM2 != null;
    }

    private TelephonyInfo() {
    }

    public static TelephonyInfo getInstance(Context context){

        if(telephonyInfo == null) {

            telephonyInfo = new TelephonyInfo();

            TelephonyManager telephonyManager = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE));

            telephonyInfo.imeiSIM1 = telephonyManager.getDeviceId();;
            telephonyInfo.imeiSIM2 = null;

            try {
                telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getDeviceIdGemini", 0);
                telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getDeviceIdGemini", 1);
            } catch (GeminiMethodNotFoundException e) {
                e.printStackTrace();

                try {
                    telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getDeviceId", 0);
                    telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getDeviceId", 1);
                } catch (GeminiMethodNotFoundException e1) {
                    //Call here for next manufacturer's predicted method name if you wish
                    e1.printStackTrace();
                }
            }

            telephonyInfo.isSIM1Ready = telephonyManager.getSimState() == TelephonyManager.SIM_STATE_READY;
            telephonyInfo.isSIM2Ready = false;

            try {
                telephonyInfo.isSIM1Ready = getSIMStateBySlot(context, "getSimStateGemini", 0);
                telephonyInfo.isSIM2Ready = getSIMStateBySlot(context, "getSimStateGemini", 1);
            } catch (GeminiMethodNotFoundException e) {

                e.printStackTrace();

                try {
                    telephonyInfo.isSIM1Ready = getSIMStateBySlot(context, "getSimState", 0);
                    telephonyInfo.isSIM2Ready = getSIMStateBySlot(context, "getSimState", 1);
                } catch (GeminiMethodNotFoundException e1) {
                    //Call here for next manufacturer's predicted method name if you wish
                    e1.printStackTrace();
                }
            }
        }

        return telephonyInfo;
    }

    private static String getDeviceIdBySlot(Context context, String predictedMethodName, int slotID) throws GeminiMethodNotFoundException {

        String imei = null;

        TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

        try{

            Class<?> telephonyClass = Class.forName(telephony.getClass().getName());

            Class<?>[] parameter = new Class[1];
            parameter[0] = int.class;
            Method getSimID = telephonyClass.getMethod(predictedMethodName, parameter);

            Object[] obParameter = new Object[1];
            obParameter[0] = slotID;
            Object ob_phone = getSimID.invoke(telephony, obParameter);

            if(ob_phone != null){
                imei = ob_phone.toString();

            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new GeminiMethodNotFoundException(predictedMethodName);
        }

        return imei;
    }

    private static  boolean getSIMStateBySlot(Context context, String predictedMethodName, int slotID) throws GeminiMethodNotFoundException {

        boolean isReady = false;

        TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

        try{

            Class<?> telephonyClass = Class.forName(telephony.getClass().getName());

            Class<?>[] parameter = new Class[1];
            parameter[0] = int.class;
            Method getSimStateGemini = telephonyClass.getMethod(predictedMethodName, parameter);

            Object[] obParameter = new Object[1];
            obParameter[0] = slotID;
            Object ob_phone = getSimStateGemini.invoke(telephony, obParameter);

            if(ob_phone != null){
                int simState = Integer.parseInt(ob_phone.toString());
                if(simState == TelephonyManager.SIM_STATE_READY){
                    isReady = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new GeminiMethodNotFoundException(predictedMethodName);
        }

        return isReady;
    }


    private static class GeminiMethodNotFoundException extends Exception {

        private static final long serialVersionUID = -996812356902545308L;

        public GeminiMethodNotFoundException(String info) {
            super(info);
        }
    }
}

Edit :

Getting access of methods like "getDeviceIdGemini" for other SIM slot's detail has prediction that method exist.

If that method's name doesn't match with one given by device manufacturer than it will not work. You have to find corresponding method name for those devices.

Finding method names for other manufacturers can be done using Java reflection as follows :

public static void printTelephonyManagerMethodNamesForThisDevice(Context context) {

    TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    Class<?> telephonyClass;
    try {
        telephonyClass = Class.forName(telephony.getClass().getName());
        Method[] methods = telephonyClass.getMethods();
        for (int idx = 0; idx < methods.length; idx++) {

            System.out.println("\n" + methods[idx] + " declared by " + methods[idx].getDeclaringClass());
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
} 

EDIT :

As Seetha pointed out in her comment :

telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getDeviceIdDs", 0);
telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getDeviceIdDs", 1); 

It is working for her. She was successful in getting two IMEI numbers for both the SIM in Samsung Duos device.

Add <uses-permission android:name="android.permission.READ_PHONE_STATE" />

EDIT 2 :

The method used for retrieving data is for Lenovo A319 and other phones by that manufacture (Credit Maher Abuthraa):

telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getSimSerialNumberGemini", 0); 
telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getSimSerialNumberGemini", 1); 

get the titles of all open windows

Based on the previous answer that give me some errors, finaly I use this code with GetOpenedWindows function:

public class InfoWindow
{
            public IntPtr Handle = IntPtr.Zero;
            public FileInfo File = new FileInfo( Application.ExecutablePath );
            public string Title = Application.ProductName;
            public override string ToString() {
                return  File.Name + "\t>\t" + Title;
            }
 }//CLASS

/// <summary>Contains functionality to get info on the open windows.</summary>
public static class RuningWindows
{   
            internal static event EventHandler WindowActivatedChanged;    
            internal static Timer TimerWatcher = new Timer();    
            internal static InfoWindow WindowActive = new InfoWindow();       
            internal static void DoStartWatcher() {
                TimerWatcher.Interval = 500;
                TimerWatcher.Tick += TimerWatcher_Tick;
                TimerWatcher.Start();    
            }                    

            /// <summary>Returns a dictionary that contains the handle and title of all the open windows.</summary>
            /// <returns>A dictionary that contains the handle and title of all the open windows.</returns>
            public static IDictionary<IntPtr , InfoWindow> GetOpenedWindows()
            {
                IntPtr shellWindow = GetShellWindow();
                Dictionary<IntPtr , InfoWindow> windows = new Dictionary<IntPtr , InfoWindow>();

                EnumWindows( new EnumWindowsProc( delegate( IntPtr hWnd , int lParam ) {
                    if ( hWnd == shellWindow ) return true;
                    if ( !IsWindowVisible( hWnd ) ) return true;    
                    int length = GetWindowTextLength( hWnd );
                    if ( length == 0 ) return true;    
                    StringBuilder builder = new StringBuilder( length );
                    GetWindowText( hWnd , builder , length + 1 );    
                    var info = new InfoWindow();
                    info.Handle = hWnd;
                    info.File = new FileInfo( GetProcessPath( hWnd ) );
                    info.Title = builder.ToString();    
                    windows[hWnd] = info;
                    return true;    
                } ) , 0 );    
                return windows;
            }

            private delegate bool EnumWindowsProc( IntPtr hWnd , int lParam );  

            public static string GetProcessPath( IntPtr hwnd )
            {
                uint pid = 0;
                GetWindowThreadProcessId( hwnd , out pid );
                if ( hwnd != IntPtr.Zero ) {
                    if ( pid != 0 ) {
                        var process = Process.GetProcessById( (int) pid );
                        if ( process != null ) {
                            return process.MainModule.FileName.ToString();
                        }
                    }
                }
                return "";
            }    

            [DllImport( "USER32.DLL" )]
            private static extern bool EnumWindows( EnumWindowsProc enumFunc , int lParam );

            [DllImport( "USER32.DLL" )]
            private static extern int GetWindowText( IntPtr hWnd , StringBuilder lpString , int nMaxCount );

            [DllImport( "USER32.DLL" )]
            private static extern int GetWindowTextLength( IntPtr hWnd );

            [DllImport( "USER32.DLL" )]
            private static extern bool IsWindowVisible( IntPtr hWnd );

            [DllImport( "USER32.DLL" )]
            private static extern IntPtr GetShellWindow();

            [DllImport( "user32.dll" )]
            private static extern IntPtr GetForegroundWindow();

            //WARN: Only for "Any CPU":
            [DllImport( "user32.dll" , CharSet = CharSet.Auto , SetLastError = true )]
            private static extern int GetWindowThreadProcessId( IntPtr handle , out uint processId );    


            static void TimerWatcher_Tick( object sender , EventArgs e )
            {
                var windowActive = new InfoWindow();
                windowActive.Handle = GetForegroundWindow();
                string path = GetProcessPath( windowActive.Handle );
                if ( string.IsNullOrEmpty( path ) ) return;
                windowActive.File = new FileInfo( path );
                int length = GetWindowTextLength( windowActive.Handle );
                if ( length == 0 ) return;
                StringBuilder builder = new StringBuilder( length );
                GetWindowText( windowActive.Handle , builder , length + 1 );
                windowActive.Title = builder.ToString();
                if ( windowActive.ToString() != WindowActive.ToString() ) {
                    //fire:
                    WindowActive = windowActive;
                    if ( WindowActivatedChanged != null ) WindowActivatedChanged( sender , e );
                    Console.WriteLine( "Window: " + WindowActive.ToString() );
                }
            }

}//CLASS

Warning: You can only compil/debug under "Any CPU" to access to 32bits Apps...

All inclusive Charset to avoid "java.nio.charset.MalformedInputException: Input length = 1"?

ISO_8859_1 Worked for me! I was reading text file with comma separated values

How to resolve the error on 'react-native start'

I just got a similar error for the first time today. It appears in \node_modules\metro-config\src\defaults\blacklist.js, there is an invalid regular expression that needed changed. I changed the first expression under sharedBlacklist from:

var sharedBlacklist = [
  /node_modules[/\\]react[/\\]dist[/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

to:

var sharedBlacklist = [
  /node_modules[\/\\]react[\/\\]dist[\/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

Explode string by one or more spaces or tabs

I think you want preg_split:

$input = "A  B C   D";
$words = preg_split('/\s+/', $input);
var_dump($words);

Operand type clash: int is incompatible with date + The INSERT statement conflicted with the FOREIGN KEY constraint

I had the same problem. I tried 'yyyy-mm-dd' format i.e. '2013-26-11' and got rid of this problem...

Getting the name of the currently executing method

Thread.currentThread().getStackTrace() will usually contain the method you’re calling it from but there are pitfalls (see Javadoc):

Some virtual machines may, under some circumstances, omit one or more stack frames from the stack trace. In the extreme case, a virtual machine that has no stack trace information concerning this thread is permitted to return a zero-length array from this method.

Resource u'tokenizers/punkt/english.pickle' not found

Just make sure you are using Jupyter Notebook and in a notebook, do the following:

import nltk

nltk.download()

Then one popup window will appear (showing info https://raw.githubusercontent.com/nltk/nltk_data/gh-pages/index.xml) From that you have to download everything.

Then rerun your code.

How to make code wait while calling asynchronous calls like Ajax

Use callbacks. Something like this should work based on your sample code.

function someFunc() {

callAjaxfunc(function() {
    console.log('Pass2');
});

}

function callAjaxfunc(callback) {
    //All ajax calls called here
    onAjaxSuccess: function() {
        callback();
    };
    console.log('Pass1');    
}

This will print Pass1 immediately (assuming ajax request takes atleast a few microseconds), then print Pass2 when the onAjaxSuccess is executed.

sql server #region

(I am developer of SSMSBoost add-in for SSMS)

We have recently added support for this syntax into our SSMSBoost add-in.

--#region [Optional Name]
--#endregion

It has also an option to automatically "recognize" regions when opening scripts.

What's the best practice to round a float to 2 decimals?

I've tried to support the -ve values for @Ivan Stin excellent 2nd method. (Major credit goes to @Ivan Stin for his method)

public static float round(float value, int scale) {
    int pow = 10;
    for (int i = 1; i < scale; i++) {
        pow *= 10;
    }
    float tmp = value * pow;
    float tmpSub = tmp - (int) tmp;

    return ( (float) ( (int) (
            value >= 0
            ? (tmpSub >= 0.5f ? tmp + 1 : tmp)
            : (tmpSub >= -0.5f ? tmp : tmp - 1)
            ) ) ) / pow;

    // Below will only handles +ve values
    // return ( (float) ( (int) ((tmp - (int) tmp) >= 0.5f ? tmp + 1 : tmp) ) ) / pow;
}

Below are the tests cases I've tried. Please let me know if this is not addressing any other cases.

@Test
public void testFloatRound() {
    // +ve values
    Assert.assertEquals(0F, NumberUtils.round(0F), 0);
    Assert.assertEquals(1F, NumberUtils.round(1F), 0);
    Assert.assertEquals(23.46F, NumberUtils.round(23.4567F), 0);
    Assert.assertEquals(23.45F, NumberUtils.round(23.4547F), 0D);
    Assert.assertEquals(1.00F, NumberUtils.round(0.49999999999999994F + 0.5F), 0);
    Assert.assertEquals(123.12F, NumberUtils.round(123.123F), 0);
    Assert.assertEquals(0.12F, NumberUtils.round(0.123F), 0);
    Assert.assertEquals(0.55F, NumberUtils.round(0.55F), 0);
    Assert.assertEquals(0.55F, NumberUtils.round(0.554F), 0);
    Assert.assertEquals(0.56F, NumberUtils.round(0.556F), 0);
    Assert.assertEquals(123.13F, NumberUtils.round(123.126F), 0);
    Assert.assertEquals(123.15F, NumberUtils.round(123.15F), 0);
    Assert.assertEquals(123.17F, NumberUtils.round(123.1666F), 0);
    Assert.assertEquals(123.46F, NumberUtils.round(123.4567F), 0);
    Assert.assertEquals(123.87F, NumberUtils.round(123.8711F), 0);
    Assert.assertEquals(123.15F, NumberUtils.round(123.15123F), 0);
    Assert.assertEquals(123.89F, NumberUtils.round(123.8909F), 0);
    Assert.assertEquals(124.00F, NumberUtils.round(123.9999F), 0);
    Assert.assertEquals(123.70F, NumberUtils.round(123.7F), 0);
    Assert.assertEquals(123.56F, NumberUtils.round(123.555F), 0);
    Assert.assertEquals(123.00F, NumberUtils.round(123.00F), 0);
    Assert.assertEquals(123.50F, NumberUtils.round(123.50F), 0);
    Assert.assertEquals(123.93F, NumberUtils.round(123.93F), 0);
    Assert.assertEquals(123.93F, NumberUtils.round(123.9312F), 0);
    Assert.assertEquals(123.94F, NumberUtils.round(123.9351F), 0);
    Assert.assertEquals(123.94F, NumberUtils.round(123.9350F), 0);
    Assert.assertEquals(123.94F, NumberUtils.round(123.93501F), 0);
    Assert.assertEquals(99.99F, NumberUtils.round(99.99F), 0);
    Assert.assertEquals(100.00F, NumberUtils.round(99.999F), 0);
    Assert.assertEquals(100.00F, NumberUtils.round(99.9999F), 0);

    // -ve values
    Assert.assertEquals(-123.94F, NumberUtils.round(-123.93501F), 0);
    Assert.assertEquals(-123.00F, NumberUtils.round(-123.001F), 0);
    Assert.assertEquals(-0.94F, NumberUtils.round(-0.93501F), 0);
    Assert.assertEquals(-1F, NumberUtils.round(-1F), 0);
    Assert.assertEquals(-0.50F, NumberUtils.round(-0.50F), 0);
    Assert.assertEquals(-0.55F, NumberUtils.round(-0.55F), 0);
    Assert.assertEquals(-0.55F, NumberUtils.round(-0.554F), 0);
    Assert.assertEquals(-0.56F, NumberUtils.round(-0.556F), 0);
    Assert.assertEquals(-0.12F, NumberUtils.round(-0.1234F), 0);
    Assert.assertEquals(-0.12F, NumberUtils.round(-0.123456789F), 0);
    Assert.assertEquals(-0.13F, NumberUtils.round(-0.129F), 0);
    Assert.assertEquals(-99.99F, NumberUtils.round(-99.99F), 0);
    Assert.assertEquals(-100.00F, NumberUtils.round(-99.999F), 0);
    Assert.assertEquals(-100.00F, NumberUtils.round(-99.9999F), 0);
}

Can I delete a git commit but keep the changes?

Using git 2.9 (precisely 2.9.2.windows.1) git reset HEAD^ prompts for more; not sure what is expected input here. Please refer below screenshot

enter image description here

Found other solution git reset HEAD~#numberOfCommits using which we can choose to select number of local commits you want to reset by keeping your changes intact. Hence, we get an opportunity to throw away all local commits as well as limited number of local commits.

Refer below screenshots showing git reset HEAD~1 in action: enter image description here

enter image description here

Difference between Method and Function?

Both are the same, both are a term which means to encapsulate some code into a unit of work which can be called from elsewhere.

Historically, there may have been a subtle difference with a "method" being something which does not return a value, and a "function" one which does. in C# that would translate as:

public void DoSomething() {} // method
public int DoSomethingAndReturnMeANumber(){} // function

But really, I re-iterate that there is really no difference in the 2 concepts.

how to loop through rows columns in excel VBA Macro

Try this:

Create A Macro with the following thing inside:

Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(-1, 1).Select
Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(0, -1).Select

That particular macro will copy the current cell (place your cursor in the VOL cell you wish to copy) down one row and then copy the CAP cell also.

This is only a single loop so you can automate copying VOL and CAP of where your current active cell (where your cursor is) to down 1 row.

Just put it inside a For loop statement to do it x number of times. like:

For i = 1 to 100 'Do this 100 times
    Selection.Copy
    ActiveCell.Offset(1, 0).Select
    ActiveSheet.Paste
    ActiveCell.Offset(-1, 1).Select
    Selection.Copy
    ActiveCell.Offset(1, 0).Select
    ActiveSheet.Paste
    ActiveCell.Offset(0, -1).Select
Next i

Cleanest way to reset forms

For just to reset the form use reset() method. It resets the form but you could get issue such as validation errors - ex: Name is required

To solve this use resetForm() method. It resets the form and also resets the submit status solving your issue.

The resetForm() method is actually calling reset() method and additionally it is resetting the submit status.

How to get the last day of the month?

>>> import datetime
>>> import calendar
>>> date  = datetime.datetime.now()

>>> print date
2015-03-06 01:25:14.939574

>>> print date.replace(day = 1)
2015-03-01 01:25:14.939574

>>> print date.replace(day = calendar.monthrange(date.year, date.month)[1])
2015-03-31 01:25:14.939574

Get top n records for each group of grouped results

In other databases you can do this using ROW_NUMBER. MySQL doesn't support ROW_NUMBER but you can use variables to emulate it:

SELECT
    person,
    groupname,
    age
FROM
(
    SELECT
        person,
        groupname,
        age,
        @rn := IF(@prev = groupname, @rn + 1, 1) AS rn,
        @prev := groupname
    FROM mytable
    JOIN (SELECT @prev := NULL, @rn := 0) AS vars
    ORDER BY groupname, age DESC, person
) AS T1
WHERE rn <= 2

See it working online: sqlfiddle


Edit I just noticed that bluefeet posted a very similar answer: +1 to him. However this answer has two small advantages:

  1. It it is a single query. The variables are initialized inside the SELECT statement.
  2. It handles ties as described in the question (alphabetical order by name).

So I'll leave it here in case it can help someone.

Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'"

It is always preferred to use a virtual environment ,Create your virtual environment using :

python -m venv <name_of_virtualenv>

go to your environment directory and activate your environment using below command on windows:

env_name\Scripts\activate.bat

then simply use

pip install package_name

Passing an array to a query using a WHERE clause

We should take care of SQL injection vulnerabilities and an empty condition. I am going to handle both as below.

For a pure numeric array, use the appropriate type conversion viz intval or floatval or doubleval over each element. For string types mysqli_real_escape_string() which may also be applied to numeric values if you wish. MySQL allows numbers as well as date variants as string.

To appropriately escape the values before passing to the query, create a function similar to:

function escape($string)
{
    // Assuming $db is a link identifier returned by mysqli_connect() or mysqli_init()
    return mysqli_real_escape_string($db, $string);
}

Such a function would most likely be already available to you in your application, or maybe you've already created one.

Sanitize the string array like:

$values = array_map('escape', $gallaries);

A numeric array can be sanitized using intval or floatval or doubleval instead as suitable:

$values = array_map('intval', $gallaries);

Then finally build the query condition

$where  = count($values) ? "`id` = '" . implode("' OR `id` = '", $values) . "'" : 0;

or

$where  = count($values) ? "`id` IN ('" . implode("', '", $values) . "')" : 0;

Since the array can also be empty sometimes, like $galleries = array(); we should therefore note that IN () does not allow for an empty list. One can also use OR instead, but the problem remains. So the above check, count($values), is to ensure the same.

And add it to the final query:

$query  = 'SELECT * FROM `galleries` WHERE ' . $where;

TIP: If you want to show all records (no filtering) in case of an empty array instead of hiding all rows, simply replace 0 with 1 in the ternary's false part.

I can’t find the Android keytool

No need to use the command line.

If you FILE-> "Export Android Application" in the ADK then it will allow you to create a key and then produce your .apk file.

Is it possible to make input fields read-only through CSS?

Not really what you need, but it can help and answser the question here depending of what you want to achieve.

You can prevent all pointer events to be sent to the input by using the CSS property : pointer-events:none It will kind of add a layer on top of the element that will prevent you to click in it ... You can also add a cursor:text to the parent element to give back the text cursor style to the input ...

Usefull, for example, when you can't modify the JS/HTML of a module.. and you can just customize it by css.

JSFIDDLE

How to pass the values from one jsp page to another jsp without submit button?

I dont exactly know what you want to do.But you cant send data of one form using a submit button of another form.

You could do one thing either use sessions or use hidden fields that has the submit button. You could use javascript/jquery to pass the values from the first form to the hidden fields of the second form.Then you could submit the form.

Or else the easiest you could do is use sessions.

<form>
<input type="text" class="input-text " value="" size="32" name="user_data[firstname]" id="elm_6">
<input type="text" class="input-text " value="" size="32" name="user_data[lastname]" id="elm_7">
</form>

<form action="#">
<input type="text" class="input-text " value="" size="32" name="user_data[b_firstname]" id="elm_14">
<input type="text" class="input-text " value="" size="32" name="user_data[s_firstname]" id="elm_16">

<input type="submit" value="Continue" name="dispatch[checkout.update_steps]">
</form>


$('input[type=submit]').click(function(){
$('#elm_14').val($('#elm_6').val());
$('#elm_16').val($('#elm_7').val());
});

This is the jsfiddle for it http://jsfiddle.net/FPsdy/102/

Generate random 5 characters string

You can try it simply like this:

$length = 5;

$randomletter = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, $length);

more details: http://forum.arnlweb.com/viewtopic.php?f=7&t=25

Unicode, UTF, ASCII, ANSI format differences

Some reading to get you started on character encodings: Joel on Software: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

By the way - ASP.NET has nothing to do with it. Encodings are universal.

Delete files older than 3 months old in a directory using .NET

Here's a snippet of how to get the creation time of files in the directory and find those which have been created 3 months ago (90 days ago to be exact):

    DirectoryInfo source = new DirectoryInfo(sourceDirectoryPath);

    // Get info of each file into the directory
    foreach (FileInfo fi in source.GetFiles())
    {
        var creationTime = fi.CreationTime;

        if(creationTime < (DateTime.Now- new TimeSpan(90, 0, 0, 0)))
        {
            fi.Delete();
        }
    }

Programmatically center TextView text

if your text size is small, you should make the width of your text view to be "fill_parent". After that, you can set your TextView Gravity to center :

TextView textView = new TextView(this);
textView.setText(message);
textView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
textView.setGravity(Gravity.CENTER);

setOnItemClickListener on custom ListView

Sorry for coding with Kotlin. But I faced the same problem. I solved with the code below.

list.setOnItemClickListener{ _, view, _, _ ->
        val text1 = view.find<TextView>(R.id.~~).text

        }

You can put an id which shows a TextView that you want in "~~".

Hope it'll help someone!

Implement division with bit-wise operator

int remainder =0;

int division(int dividend, int divisor)
{
    int quotient = 1;

    int neg = 1;
    if ((dividend>0 &&divisor<0)||(dividend<0 && divisor>0))
        neg = -1;

    // Convert to positive
    unsigned int tempdividend = (dividend < 0) ? -dividend : dividend;
    unsigned int tempdivisor = (divisor < 0) ? -divisor : divisor;

    if (tempdivisor == tempdividend) {
        remainder = 0;
        return 1*neg;
    }
    else if (tempdividend < tempdivisor) {
        if (dividend < 0)
            remainder = tempdividend*neg;
        else
            remainder = tempdividend;
        return 0;
    }
    while (tempdivisor<<1 <= tempdividend)
    {
        tempdivisor = tempdivisor << 1;
        quotient = quotient << 1;
    }

    // Call division recursively
    if(dividend < 0)
        quotient = quotient*neg + division(-(tempdividend-tempdivisor), divisor);
    else
        quotient = quotient*neg + division(tempdividend-tempdivisor, divisor);
     return quotient;
 }


void main()
{
    int dividend,divisor;
    char ch = 's';
    while(ch != 'x')
    {
        printf ("\nEnter the Dividend: ");
        scanf("%d", &dividend);
        printf("\nEnter the Divisor: ");
        scanf("%d", &divisor);

        printf("\n%d / %d: quotient = %d", dividend, divisor, division(dividend, divisor));
        printf("\n%d / %d: remainder = %d", dividend, divisor, remainder);

        _getch();
    }
}

Iterating over and deleting from Hashtable in Java

You need to use an explicit java.util.Iterator to iterate over the Map's entry set rather than being able to use the enhanced For-loop syntax available in Java 6. The following example iterates over a Map of Integer, String pairs, removing any entry whose Integer key is null or equals 0.

Map<Integer, String> map = ...

Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();

while (it.hasNext()) {
  Map.Entry<Integer, String> entry = it.next();

  // Remove entry if key is null or equals 0.
  if (entry.getKey() == null || entry.getKey() == 0) {
    it.remove();
  }
}

Rails: Why "sudo" command is not recognized?

Sudo is a Unix specific command designed to allow a user to carry out administrative tasks with the appropriate permissions.

Windows does not have (need?) this.

Run the command with the sudo removed from the start.

Counting number of words in a file

Hack solution

You can read the text file into a String var. Then split the String into an array using a single whitespace as the delimiter StringVar.Split(" ").

The Array count would equal the number of "Words" in the file. Of course this wouldnt give you a count of line numbers.

How do I change the number of open files limit in Linux?

1) Add the following line to /etc/security/limits.conf

webuser hard nofile 64000

then login as webuser

su - webuser

2) Edit following two files for webuser

append .bashrc and .bash_profile file by running

echo "ulimit -n 64000" >> .bashrc ; echo "ulimit -n 64000" >> .bash_profile

3) Log out, then log back in and verify that the changes have been made correctly:

$ ulimit -a | grep open
open files                      (-n) 64000

Thats it and them boom, boom boom.

Link to a section of a webpage

Simple:

Use <section>.

and use <a href="page.html#tips">Visit the Useful Tips Section</a>

w3school.com/html_links

Where does Internet Explorer store saved passwords?

Short answer: in the Vault. Since Windows 7, a Vault was created for storing any sensitive data among it the credentials of Internet Explorer. The Vault is in fact a LocalSystem service - vaultsvc.dll.

Long answer: Internet Explorer allows two methods of credentials storage: web sites credentials (for example: your Facebook user and password) and autocomplete data. Since version 10, instead of using the Registry a new term was introduced: Windows Vault. Windows Vault is the default storage vault for the credential manager information.

You need to check which OS is running. If its Windows 8 or greater, you call VaultGetItemW8. If its isn't, you call VaultGetItemW7.

To use the "Vault", you load a DLL named "vaultcli.dll" and access its functions as needed.

A typical C++ code will be:

hVaultLib = LoadLibrary(L"vaultcli.dll");

if (hVaultLib != NULL) 
{
    pVaultEnumerateItems = (VaultEnumerateItems)GetProcAddress(hVaultLib, "VaultEnumerateItems");
    pVaultEnumerateVaults = (VaultEnumerateVaults)GetProcAddress(hVaultLib, "VaultEnumerateVaults");
    pVaultFree = (VaultFree)GetProcAddress(hVaultLib, "VaultFree");
    pVaultGetItemW7 = (VaultGetItemW7)GetProcAddress(hVaultLib, "VaultGetItem");
    pVaultGetItemW8 = (VaultGetItemW8)GetProcAddress(hVaultLib, "VaultGetItem");
    pVaultOpenVault = (VaultOpenVault)GetProcAddress(hVaultLib, "VaultOpenVault");
    pVaultCloseVault = (VaultCloseVault)GetProcAddress(hVaultLib, "VaultCloseVault");

    bStatus = (pVaultEnumerateVaults != NULL)
        && (pVaultFree != NULL)
        && (pVaultGetItemW7 != NULL)
        && (pVaultGetItemW8 != NULL)
        && (pVaultOpenVault != NULL)
        && (pVaultCloseVault != NULL)
        && (pVaultEnumerateItems != NULL);
}

Then you enumerate all stored credentials by calling

VaultEnumerateVaults

Then you go over the results.

Why do we have to normalize the input for an artificial neural network?

The reason normalization is needed is because if you look at how an adaptive step proceeds in one place in the domain of the function, and you just simply transport the problem to the equivalent of the same step translated by some large value in some direction in the domain, then you get different results. It boils down to the question of adapting a linear piece to a data point. How much should the piece move without turning and how much should it turn in response to that one training point? It makes no sense to have a changed adaptation procedure in different parts of the domain! So normalization is required to reduce the difference in the training result. I haven't got this written up, but you can just look at the math for a simple linear function and how it is trained by one training point in two different places. This problem may have been corrected in some places, but I am not familiar with them. In ALNs, the problem has been corrected and I can send you a paper if you write to wwarmstrong AT shaw.ca

Haversine Formula in Python (Bearing and Distance between two GPS points)

Refer to this link :https://gis.stackexchange.com/questions/84885/whats-the-difference-between-vincenty-and-great-circle-distance-calculations

this actually gives two ways of getting distance. They are Haversine and Vincentys. From my research I came to know that Vincentys is relatively accurate. Also use import statement to make the implementation.

Pandas timeseries plot setting x-axis major and minor ticks and labels

Both pandas and matplotlib.dates use matplotlib.units for locating the ticks.

But while matplotlib.dates has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).

So for the moment it seems more reasonable to use matplotlib.dates (as mentioned by @BrenBarn in his comment).

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt 
import matplotlib.dates as dates

idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)

fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
                                                interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()

pandas_like_date_fomatting

(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])

Finish all activities at a time

I was struggling with the same problem. Opening the about page and calling finish(); from there wasn't closing the app instead was going to previous activity and I wanted to close the app from the about page itself.

This is the code which worked for me:

Intent startMain = new Intent(Intent.ACTION_MAIN); 
startMain.addCategory(Intent.CATEGORY_HOME); 
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
startActivity(startMain); 
finish();

Hope this helps.

How can you print multiple variables inside a string using printf?

Change the line where you print the output to:

printf("\nmaximum of %d and %d is = %d",a,b,c);

See the docs here

How to add an image in Tkinter?

Following code works on my machine

  1. you probably have something missing in your code.
  2. please also check the code files's encoding.
  3. make sure you have PIL package installed

    import Tkinter as tk
    from PIL import ImageTk, Image
    
    path = 'C:/xxxx/xxxx.jpg'
    
    root = tk.Tk()
    img = ImageTk.PhotoImage(Image.open(path))
    panel = tk.Label(root, image = img)
    panel.pack(side = "bottom", fill = "both", expand = "yes")
    root.mainloop()
    

What does -> mean in C++?

It's to access a member function or member variable of an object through a pointer, as opposed to a regular variable or reference.

For example: with a regular variable or reference, you use the . operator to access member functions or member variables.

std::string s = "abc";
std::cout << s.length() << std::endl;

But if you're working with a pointer, you need to use the -> operator:

std::string* s = new std::string("abc");
std::cout << s->length() << std::endl;

It can also be overloaded to perform a specific function for a certain object type. Smart pointers like shared_ptr and unique_ptr, as well as STL container iterators, overload this operator to mimic native pointer semantics.

For example:

std::map<int, int>::iterator it = mymap.begin(), end = mymap.end();
for (; it != end; ++it)
    std::cout << it->first << std::endl;

Transactions in .net

You could also wrap the transaction up into it's own stored procedure and handle it that way instead of doing transactions in C# itself.

TypeError: Object of type 'bytes' is not JSON serializable

I guess the answer you need is referenced here Python sets are not json serializable

Not all datatypes can be json serialized . I guess pickle module will serve your purpose.

How do I call paint event?

Maybe this is an old question and that´s the reason why these answers didn't work for me ... using Visual Studio 2019, after some investigating, this is the solution I've found:

this.InvokePaint(this, new PaintEventArgs(this.CreateGraphics(), this.DisplayRectangle));

Changing Placeholder Text Color with Swift

Just write below code into Appdelegate's didFinishLaunchingWithOptions method use this if you want to change in the whole app written in Swift 4.2

UILabel.appearance(whenContainedInInstancesOf: [UITextField.self]).textColor = UIColor.white

Using switch statement with a range of value in each case?

It is supported as of Java 12. Check out JEP 354. No "range" possibilities here, but can be useful either.

switch (day) {
    case MONDAY, FRIDAY, SUNDAY -> System.out.println(6);//number of letters
    case TUESDAY                -> System.out.println(7);
    case THURSDAY, SATURDAY     -> System.out.println(8);
    case WEDNESDAY              -> System.out.println(9);
}

You should be able to implement that on ints too. Note through that your switch statement have to be exhaustive (using default keyword, or using all possible values in case statements).

Reading all files in a directory, store them in objects, and send the object

This is a modern Promise version of the previous one, using a Promise.all approach to resolve all promises when all files have been read:

/**
 * Promise all
 * @author Loreto Parisi (loretoparisi at gmail dot com)
 */
function promiseAllP(items, block) {
    var promises = [];
    items.forEach(function(item,index) {
        promises.push( function(item,i) {
            return new Promise(function(resolve, reject) {
                return block.apply(this,[item,index,resolve,reject]);
            });
        }(item,index))
    });
    return Promise.all(promises);
} //promiseAll

/**
 * read files
 * @param dirname string
 * @return Promise
 * @author Loreto Parisi (loretoparisi at gmail dot com)
 * @see http://stackoverflow.com/questions/10049557/reading-all-files-in-a-directory-store-them-in-objects-and-send-the-object
 */
function readFiles(dirname) {
    return new Promise((resolve, reject) => {
        fs.readdir(dirname, function(err, filenames) {
            if (err) return reject(err);
            promiseAllP(filenames,
            (filename,index,resolve,reject) =>  {
                fs.readFile(path.resolve(dirname, filename), 'utf-8', function(err, content) {
                    if (err) return reject(err);
                    return resolve({filename: filename, contents: content});
                });
            })
            .then(results => {
                return resolve(results);
            })
            .catch(error => {
                return reject(error);
            });
        });
  });
}

How to Use It:

Just as simple as doing:

readFiles( EMAIL_ROOT + '/' + folder)
.then(files => {
    console.log( "loaded ", files.length );
    files.forEach( (item, index) => {
        console.log( "item",index, "size ", item.contents.length);
    });
})
.catch( error => {
    console.log( error );
});

Supposed that you have another list of folders you can as well iterate over this list, since the internal promise.all will resolve each of then asynchronously:

var folders=['spam','ham'];
folders.forEach( folder => {
    readFiles( EMAIL_ROOT + '/' + folder)
    .then(files => {
        console.log( "loaded ", files.length );
        files.forEach( (item, index) => {
            console.log( "item",index, "size ", item.contents.length);
        });
    })
    .catch( error => {
        console.log( error );
    });
});

How it Works

The promiseAll does the magic. It takes a function block of signature function(item,index,resolve,reject), where item is the current item in the array, index its position in the array, and resolve and reject the Promise callback functions. Each promise will be pushed in a array at the current index and with the current item as arguments through a anonymous function call:

promises.push( function(item,i) {
        return new Promise(function(resolve, reject) {
            return block.apply(this,[item,index,resolve,reject]);
        });
    }(item,index))

Then all promises will be resolved:

return Promise.all(promises);

Maximum number of threads in a .NET app?

There is no inherent limit. The maximum number of threads is determined by the amount of physical resources available. See this article by Raymond Chen for specifics.

If you need to ask what the maximum number of threads is, you are probably doing something wrong.

[Update: Just out of interest: .NET Thread Pool default numbers of threads:

  • 1023 in Framework 4.0 (32-bit environment)
  • 32767 in Framework 4.0 (64-bit environment)
  • 250 per core in Framework 3.5
  • 25 per core in Framework 2.0

(These numbers may vary depending upon the hardware and OS)]

JavaScript/jQuery: replace part of string?

It should be like this

$(this).text($(this).text().replace('N/A, ', ''))

Store output of subprocess.Popen call in a string

import subprocess
output = str(subprocess.Popen("ntpq -p",shell = True,stdout = subprocess.PIPE, 
stderr = subprocess.STDOUT).communicate()[0])

This is one line solution

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 23: ordinal not in range(128)

When you get a UnicodeEncodeError, it means that somewhere in your code you convert directly a byte string to a unicode one. By default in Python 2 it uses ascii encoding, and utf8 encoding in Python3 (both may fail because not every byte is valid in either encoding)

To avoid that, you must use explicit decoding.

If you may have 2 different encoding in your input file, one of them accepts any byte (say UTF8 and Latin1), you can try to first convert a string with first and use the second one if a UnicodeDecodeError occurs.

def robust_decode(bs):
    '''Takes a byte string as param and convert it into a unicode one.
First tries UTF8, and fallback to Latin1 if it fails'''
    cr = None
    try:
        cr = bs.decode('utf8')
    except UnicodeDecodeError:
        cr = bs.decode('latin1')
    return cr

If you do not know original encoding and do not care for non ascii character, you can set the optional errors parameter of the decode method to replace. Any offending byte will be replaced (from the standard library documentation):

Replace with a suitable replacement character; Python will use the official U+FFFD REPLACEMENT CHARACTER for the built-in Unicode codecs on decoding and ‘?’ on encoding.

bs.decode(errors='replace')

How to see log files in MySQL?

You have to activate the query logging in mysql.

  1. edit /etc/my.cnf

    [mysqld]
    log=/tmp/mysql.log
    
  2. restart the computer or the mysqld service

    service mysqld restart
    
  3. open phpmyadmin/any application that uses mysql/mysql console and run a query

  4. cat /tmp/mysql.log ( you should see the query )

Adding css class through aspx code behind

controlName.CssClass="CSS Class Name";

working example follows below

txtBank.CssClass = "csError";

<strong> vs. font-weight:bold & <em> vs. font-style:italic

HTML represents meaning; CSS represents appearance. How you mark up text in a document is not determined by how that text appears on screen, but simply what it means. As another example, some other HTML elements, like headings, are styled font-weight: bold by default, but they are marked up using <h1><h6>, not <strong> or <b>.

In HTML5, you use <strong> to indicate important parts of a sentence, for example:

<p><strong>Do not touch.</strong> Contains <strong>hazardous</strong> materials.

And you use <em> to indicate linguistic stress, for example:

<p>A Gentleman: I suppose he does. But there's no point in asking.
<p>A Lady: Why not?
<p>A Gentleman: Because he doesn't row.
<p>A Lady: He doesn't <em>row</em>?
<p>A Gentleman: No. He <em>doesn't</em> row.
<p>A Lady: Ah. I see what you mean.

These elements are semantic elements that just happen to have bold and italic representations by default, but you can style them however you like. For example, in the <em> sample above, you could represent stress emphasis in uppercase instead of italics, but the functional purpose of the <em> element remains the same — to change the context of a sentence by emphasizing specific words or phrases over others:

em {
    font-style: normal;
    text-transform: uppercase;
}

Note that the original answer (below) applied to HTML standards prior to HTML5, in which <strong> and <em> had somewhat different meanings, <b> and <i> were purely presentational and had no semantic meaning whatsoever. Like <strong> and <em> respectively, they have similar presentational defaults but may be styled differently.


You use <strong> and <em> to indicate intense emphasis and normal emphasis respectively.

Or think of it this way: font-weight: bold is closer to <b> than <strong>, and font-style: italic is closer to <i> than <em>. These visual styles are purely visual: tools like screen readers aren't going to understand what bold and italic mean, but some screen readers are able to read <strong> and <em> text in a more emphasized tone.

How to replace all special character into a string using C#

Yes, you can use regular expressions in C#.

Using regular expressions with C#:

using System.Text.RegularExpressions;

string your_String = "Hello@Hello&Hello(Hello)";
string my_String =  Regex.Replace(your_String, @"[^0-9a-zA-Z]+", ",");

How to leave/exit/deactivate a Python virtualenv

Usually, activating a virtualenv gives you a shell function named:

$ deactivate

which puts things back to normal.

I have just looked specifically again at the code for virtualenvwrapper, and, yes, it too supports deactivate as the way to escape from all virtualenvs.

If you are trying to leave an Anaconda environment, the command depends upon your version of conda. Recent versions (like 4.6) install a conda function directly in your shell, in which case you run:

conda deactivate

Older conda versions instead implement deactivation using a stand-alone script:

source deactivate

How do I find the mime-type of a file with php?

mime_content_type() appears to be the way to go, notwithstanding the above comments saying it is deprecated. It is not -- or at least this incarnation of mime_content_type() is not deprecated, according to http://php.net/manual/en/function.mime-content-type.php. It is part of the FileInfo extension, but the PHP documentation now tells us it is enabled by default as of PHP 5.3.0.

SQL Server: how to create a stored procedure

T-SQL

/* 
Stored Procedure GetstudentnameInOutputVariable is modified to collect the
email address of the student with the help of the Alert Keyword
*/



CREATE  PROCEDURE GetstudentnameInOutputVariable
(

@studentid INT,                   --Input parameter ,  Studentid of the student
@studentname VARCHAR (200) OUT,    -- Output parameter to collect the student name
@StudentEmail VARCHAR (200)OUT     -- Output Parameter to collect the student email
)
AS
BEGIN
SELECT @studentname= Firstname+' '+Lastname, 
    @StudentEmail=email FROM tbl_Students WHERE studentid=@studentid
END

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

here's a regex one for ya.

update table
set col1=null
where col1 not like '%[a-z,0-9]%'

essentially finds any columns that dont have letters or numbers in them and sets it to null. might have to update if you have columns with just special characters.

How to change package name of an Android Application

Changing package name is a pain in the ass. It looks like different methods work for different people. My solution is quick and error free. Looks like no cleaning or resetting eclipse is needed.

  1. Right click on the package name then Refractor > Rename.
  2. Right click on the project name Android tools > Rename Application Package.
  3. Manually set the package names in the Manifest that have not been changed by the previous steps.

Is there a way to use shell_exec without waiting for the command to complete?

Use PHP's popen command, e.g.:

pclose(popen("start c:\wamp\bin\php.exe c:\wamp\www\script.php","r"));

This will create a child process and the script will excute in the background without waiting for output.

What is the iPhone 4 user-agent?

iOS 4.3.2's User Agent, which came out this week, is:

Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5

How to find the sum of an array of numbers

Just use this function:

function sum(pArray)
{
  pArray = pArray.reduce(function (a, b) {
      return a + b;
  }, 0);

  return pArray;
}

_x000D_
_x000D_
function sum(pArray)_x000D_
{_x000D_
  pArray = pArray.reduce(function (a, b) {_x000D_
      return a + b;_x000D_
  }, 0);_x000D_
_x000D_
  return pArray;_x000D_
}_x000D_
_x000D_
var arr = [1, 4, 5];_x000D_
_x000D_
console.log(sum(arr));
_x000D_
_x000D_
_x000D_

Replace Default Null Values Returned From Left Outer Join

That's as easy as

IsNull(FieldName, 0)

Or more completely:

SELECT iar.Description, 
  ISNULL(iai.Quantity,0) as Quantity, 
  ISNULL(iai.Quantity * rpl.RegularPrice,0) as 'Retail', 
  iar.Compliance 
FROM InventoryAdjustmentReason iar
LEFT OUTER JOIN InventoryAdjustmentItem iai  on (iar.Id = iai.InventoryAdjustmentReasonId)
LEFT OUTER JOIN Item i on (i.Id = iai.ItemId)
LEFT OUTER JOIN ReportPriceLookup rpl on (rpl.SkuNumber = i.SkuNo)
WHERE iar.StoreUse = 'yes'

How to scanf only integer and repeat reading if the user enters non-numeric characters?

char check1[10], check2[10];
int foo;

do{
  printf(">> ");
  scanf(" %s", check1);
  foo = strtol(check1, NULL, 10); // convert the string to decimal number
  sprintf(check2, "%d", foo); // re-convert "foo" to string for comparison
} while (!(strcmp(check1, check2) == 0 && 0 < foo && foo < 24)); // repeat if the input is not number

If the input is number, you can use foo as your input.

How to Change color of Button in Android when Clicked?

Try This

    final Button button = (Button) findViewById(R.id.button_id);
    button.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            if(event.getAction() == MotionEvent.ACTION_UP) {
                button.setBackgroundColor(Color.RED);
            } else if(event.getAction() == MotionEvent.ACTION_DOWN) {
                button.setBackgroundColor(Color.BLUE);
            }
            return false;
        }

    });

What Java FTP client library should I use?

Apache commons-nets get updates more frequently recently, while Enterprise DT library seems to update even more frequently.

How do I download/extract font from chrome developers tools?

Open chrome

Right click => inspect => navigate to application tab

In Frames section, all the statically available assets(resources) such as css, JavaScript, fonts are listed.

Importing xsd into wsdl

import vs. include

The primary purpose of an import is to import a namespace. A more common use of the XSD import statement is to import a namespace which appears in another file. You might be gathering the namespace information from the file, but don't forget that it's the namespace that you're importing, not the file (don't confuse an import statement with an include statement).

Another area of confusion is how to specify the location or path of the included .xsd file: An XSD import statement has an optional attribute named schemaLocation but it is not necessary if the namespace of the import statement is at the same location (in the same file) as the import statement itself.

When you do chose to use an external .xsd file for your WSDL, the schemaLocation attribute becomes necessary. Be very sure that the namespace you use in the import statement is the same as the targetNamespace of the schema you are importing. That is, all 3 occurrences must be identical:

WSDL:

xs:import namespace="urn:listing3" schemaLocation="listing3.xsd"/>

XSD:

<xsd:schema targetNamespace="urn:listing3"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 

Another approach to letting know the WSDL about the XSD is through Maven's pom.xml:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>xmlbeans-maven-plugin</artifactId>
  <executions>
    <execution>
      <id>generate-sources-xmlbeans</id>
      <phase>generate-sources</phase>
      <goals>
    <goal>xmlbeans</goal>
      </goals>
    </execution>
  </executions>
  <version>2.3.3</version>
  <inherited>true</inherited>
  <configuration>
    <schemaDirectory>${basedir}/src/main/xsd</schemaDirectory>
  </configuration>
</plugin>

You can read more on this in this great IBM article. It has typos such as xsd:import instead of xs:import but otherwise it's fine.

How does Google reCAPTCHA v2 work behind the scenes?

My Bots are running well against ReCaptcha.

Here my Solution.

Let your Bot do this Steps:

First write a Human Mouse Move Function to move your Mouse like a B-Spline (Ask me for Source Code). This is the most important Point.

Also use for better results a VPN like https://www.purevpn.com

For every Recpatcha do these Steps:

  1. If you use VPN switch IP first

  2. Clear all Browser Cookies

  3. Clear all Browser Cache

  4. Set one of these Useragents by Random:

    a. Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)

    b. Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0

5 Move your Mouse with the Human Mouse Move Funktion from a RandomPoint into the I am not a Robot Image every time with different 10x10 Randomrange

  1. Then Click ever with random delay between

    WM_LBUTTONDOWN

    and

    WM_LBUTTONUP

  2. Take Screenshot from Image Captcha

  3. Send Screenshot to

    http://www.deathbycaptcha.com

    or

    https://2captcha.com

and let they solve.

  1. After receiving click cooridinates from captcha solver use your Human Mouse move Funktion to move and Click Recaptcha Images

  2. Use your Human Mouse Move Funktion to move and Click to the Recaptcha Verify Button

In 75% all trys Recaptcha will solved

Chears Google

Tom

Beginner Python Practice?

I always find it easier to learn a language in a specific problem domain. You might try looking at Django and doing the tutorial. This will give you a very light-weight intro to both Python and to a web framework (a very well-documented one) that is 100% Python.

Then do something in your field(s) of expertise -- graph generation, or whatever -- and tie that into a working framework to see if you got it right. My universe tends to be computational linguistics and there are a number of Python-based toolkits to help get you started. E.g. Natural Language Toolkit.

Just a thought.

How can I create a blank/hardcoded column in a sql query?

SELECT
    hat,
    shoe,
    boat,
    0 as placeholder -- for column having 0 value    
FROM
    objects


--OR '' as Placeholder -- for blank column    
--OR NULL as Placeholder -- for column having null value

How to check if keras tensorflow backend is GPU or CPU version?

According to the documentation.

If you are running on the TensorFlow or CNTK backends, your code will automatically run on GPU if any available GPU is detected.

You can check what all devices are used by tensorflow by -

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

Also as suggested in this answer

import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

This will print whether your tensorflow is using a CPU or a GPU backend. If you are running this command in jupyter notebook, check out the console from where you have launched the notebook.

If you are sceptic whether you have installed the tensorflow gpu version or not. You can install the gpu version via pip.

pip install tensorflow-gpu

Setting background images in JFrame

There is no built-in method, but there are several ways to do it. The most straightforward way that I can think of at the moment is:

  1. Create a subclass of JComponent.
  2. Override the paintComponent(Graphics g) method to paint the image that you want to display.
  3. Set the content pane of the JFrame to be this subclass.

Some sample code:

class ImagePanel extends JComponent {
    private Image image;
    public ImagePanel(Image image) {
        this.image = image;
    }
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, this);
    }
}

// elsewhere
BufferedImage myImage = ImageIO.read(...);
JFrame myJFrame = new JFrame("Image pane");
myJFrame.setContentPane(new ImagePanel(myImage));

Note that this code does not handle resizing the image to fit the JFrame, if that's what you wanted.

How to check empty object in angular 2 template using *ngIf

This worked for me:

Check the length property and use ? to avoid undefined errors.

So your example would be:

<div class="comeBack_up" *ngIf="previous_info?.length">

UPDATE

The length property only exists on arrays. Since the question was about objects, use Object.getOwnPropertyNames(obj) to get an array of properties from the object. The example becomes:

<div class="comeBack_up" *ngIf="previous_info  && Object.getOwnPropertyNames(previous_info).length > 0">

The previous_info && is added to check if the object exists. If it evaluates to true the next statement checks if the object has at least on proporty. It does not check whether the property has a value.

Getting Database connection in pure JPA setup

As per the hibernate docs here,

Connection connection()

Deprecated. (scheduled for removal in 4.x). Replacement depends on need; for doing direct JDBC stuff use doWork(org.hibernate.jdbc.Work) ...

Use Hibernate Work API instead:

Session session = entityManager.unwrap(Session.class);
session.doWork(new Work() {

    @Override
    public void execute(Connection connection) throws SQLException {
        // do whatever you need to do with the connection
    }
});

How to use http.client in Node.js if there is basic authorization

var http = require("http");
var url = "http://api.example.com/api/v1/?param1=1&param2=2";

var options = {
    host: "http://api.example.com",
    port: 80,
    method: "GET",
    path: url,//I don't know for some reason i have to use full url as a path
    auth: username + ':' + password
};

http.get(options, function(rs) {
    var result = "";
    rs.on('data', function(data) {
        result += data;
    });
    rs.on('end', function() {
        console.log(result);
    });
});

Access Controller method from another controller in Laravel 5

You can access the controller by instantiating it and calling doAction: (put use Illuminate\Support\Facades\App; before the controller class declaration)

$controller = App::make('\App\Http\Controllers\YouControllerName');
$data = $controller->callAction('controller_method', $parameters);

Also note that by doing this you will not execute any of the middlewares declared on that controller.

Does Python have a toString() equivalent, and can I convert a db.Model element to String?

You should define the __unicode__ method on your model, and the template will call it automatically when you reference the instance.

graphing an equation with matplotlib

To plot an equation that is not solved for a specific variable (like circle or hyperbola):

import numpy as np  
import matplotlib.pyplot as plt  
plt.figure() # Create a new figure window
xlist = np.linspace(-2.0, 2.0, 100) # Create 1-D arrays for x,y dimensions
ylist = np.linspace(-2.0, 2.0, 100) 
X,Y = np.meshgrid(xlist, ylist) # Create 2-D grid xlist,ylist values
F = X**2 + Y**2 - 1  #  'Circle Equation
plt.contour(X, Y, F, [0], colors = 'k', linestyles = 'solid')
plt.show()

More about it: http://courses.csail.mit.edu/6.867/wiki/images/3/3f/Plot-python.pdf

Change values on matplotlib imshow() graph axis

I would try to avoid changing the xticklabels if possible, otherwise it can get very confusing if you for example overplot your histogram with additional data.

Defining the range of your grid is probably the best and with imshow it can be done by adding the extent keyword. This way the axes gets adjusted automatically. If you want to change the labels i would use set_xticks with perhaps some formatter. Altering the labels directly should be the last resort.

fig, ax = plt.subplots(figsize=(6,6))

ax.imshow(hist, cmap=plt.cm.Reds, interpolation='none', extent=[80,120,32,0])
ax.set_aspect(2) # you may also use am.imshow(..., aspect="auto") to restore the aspect ratio

enter image description here

Append TimeStamp to a File Name

you can use:

Stopwatch.GetTimestamp();

How to create an array from a CSV file using PHP and the fgetcsv function

I came up with this pretty basic code. I think it could be useful to anyone.

$link = "link to the CSV here"
$fp = fopen($link, 'r');

while(($line = fgetcsv($fp)) !== FALSE) {
    foreach($line as $key => $value) {
        echo $key . " - " . $value . "<br>";
    }
}


fclose($fp);

File path for project files?

Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"JukeboxV2.0\JukeboxV2.0\Datos\ich will.mp3")

base directory + your filename

c# regex matches example

It looks like most of post here described what you need here. However - something you might need more complex behavior - depending on what you're parsing. In your case it might be so that you won't need more complex parsing - but it depends what information you're extracting.

You can use regex groups as field name in class, after which could be written for example like this:

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

public class Info
{
    public String Identifier;
    public char nextChar;
};

class testRegex {

    const string input = "Lorem ipsum dolor sit %download%#456 amet, consectetur adipiscing %download%#3434 elit. " +
    "Duis non nunc nec mauris feugiat porttitor. Sed tincidunt blandit dui a viverra%download%#298. Aenean dapibus nisl %download%#893434 id nibh auctor vel tempor velit blandit.";

    static void Main(string[] args)
    {
        Regex regex = new Regex(@"%download%#(?<Identifier>[0-9]*)(?<nextChar>.)(?<thisCharIsNotNeeded>.)");
        List<Info> infos = new List<Info>();

        foreach (Match match in regex.Matches(input))
        {
            Info info = new Info();
            for( int i = 1; i < regex.GetGroupNames().Length; i++ )
            {
                String groupName = regex.GetGroupNames()[i];

                FieldInfo fi = info.GetType().GetField(regex.GetGroupNames()[i]);

                if( fi != null ) // Field is non-public or does not exists.
                    fi.SetValue( info, Convert.ChangeType( match.Groups[groupName].Value, fi.FieldType));
            }
            infos.Add(info);
        }

        foreach ( var info in infos )
        {
            Console.WriteLine(info.Identifier + " followed by '" + info.nextChar.ToString() + "'");
        }
    }

};

This mechanism uses C# reflection to set value to class. group name is matched against field name in class instance. Please note that Convert.ChangeType won't accept any kind of garbage.

If you want to add tracking of line / column - you can add extra Regex split for lines, but in order to keep for loop intact - all match patterns must have named groups. (Otherwise column index will be calculated incorrectly)

This will results in following output:

456 followed by ' '
3434 followed by ' '
298 followed by '.'
893434 followed by ' '

Calling a class function inside of __init__

You must declare parse_file like this; def parse_file(self). The "self" parameter is a hidden parameter in most languages, but not in python. You must add it to the definition of all that methods that belong to a class. Then you can call the function from any method inside the class using self.parse_file

your final program is going to look like this:

class MyClass():
  def __init__(self, filename):
      self.filename = filename 

      self.stat1 = None
      self.stat2 = None
      self.stat3 = None
      self.stat4 = None
      self.stat5 = None
      self.parse_file()

  def parse_file(self):
      #do some parsing
      self.stat1 = result_from_parse1
      self.stat2 = result_from_parse2
      self.stat3 = result_from_parse3
      self.stat4 = result_from_parse4
      self.stat5 = result_from_parse5

How do I convert a Swift Array to a String?

Try This:

let categories = dictData?.value(forKeyPath: "listing_subcategories_id") as! NSMutableArray
                        let tempArray = NSMutableArray()
                        for dc in categories
                        {
                            let dictD = dc as? NSMutableDictionary
                            tempArray.add(dictD?.object(forKey: "subcategories_name") as! String)
                        }
                        let joinedString = tempArray.componentsJoined(by: ",")

How to display items side-by-side without using tables?

Yes, divs and CSS are usually a better and easier way to place your HTML. There are many different ways to do this and it all depends on the context.

For instance, if you want to place an image to the right of your text, you could do it like so:

<p style="width: 500px;">
<img src="image.png" style="float: right;" />
This is some text
</p> 

And if you want to display multiple items side by side, float is also usually preferred.For example:

<div>
  <img src="image1.png" style="float: left;" />
  <img src="image2.png" style="float: left;" />
  <img src="image3.png" style="float: left;" />
</div>

Floating these images to the same side will have then laying next to each other for as long as you hava horizontal space.

REST, HTTP DELETE and parameters

It's an old question, but here are some comments...

  1. In SQL, the DELETE command accepts a parameter "CASCADE", which allows you to specify that dependent objects should also be deleted. This is an example of a DELETE parameter that makes sense, but 'man rm' could provide others. How would these cases possibly be implemented in REST/HTTP without a parameter?
  2. @Jan, it seems to be a well-established convention that the path part of the URL identifies a resource, whereas the querystring does not (at least not necessarily). Examples abound: getting the same resource but in a different format, getting specific fields of a resource, etc. If we consider the querystring as part of the resource identifier, it is impossible to have a concept of "different views of the same resource" without turning to non-RESTful mechanisms such as HTTP content negotiation (which can be undesirable for many reasons).

Can you get the column names from a SqlDataReader?

If you want the column names only, you can do:

List<string> columns = new List<string>();
using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly))
{
    DataTable dt = reader.GetSchemaTable();
    foreach (DataRow row in dt.Rows)
    {
        columns.Add(row.Field<String>("ColumnName"));
    }
}

But if you only need one row, I like my AdoHelper addition. This addition is great if you have a single line query and you don't want to deal with data table in you code. It's returning a case insensitive dictionary of column names and values.

public static Dictionary<string, string> ExecuteCaseInsensitiveDictionary(string query, string connectionString, Dictionary<string, string> queryParams = null)
{
    Dictionary<string, string> CaseInsensitiveDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
    try
    {
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.Connection = conn;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = query;

                // Add the parameters for the SelectCommand.
                if (queryParams != null)
                    foreach (var param in queryParams)
                        cmd.Parameters.AddWithValue(param.Key, param.Value);

                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    DataTable dt = new DataTable();
                    dt.Load(reader);
                    foreach (DataRow row in dt.Rows)
                    {
                        foreach (DataColumn column in dt.Columns)
                        {
                            CaseInsensitiveDictionary.Add(column.ColumnName, row[column].ToString());
                        }
                    }
                }
            }
            conn.Close();
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return CaseInsensitiveDictionary;
}

python JSON object must be str, bytes or bytearray, not 'dict

import json
data = json.load(open('/Users/laxmanjeergal/Desktop/json.json'))
jtopy=json.dumps(data) #json.dumps take a dictionary as input and returns a string as output.
dict_json=json.loads(jtopy) # json.loads take a string as input and returns a dictionary as output.
print(dict_json["shipments"])

error TS2339: Property 'x' does not exist on type 'Y'

The correct fix is to add the property in the type definition as explained by @Nitzan Tomer. But also you can just define property as any, if you want to write code almost as in JavaScript:

arr.filter((item:any) => {
    return item.isSelected == true;
}

How do I convert a list of ascii values to a string in python?

import array
def f7(list):
    return array.array('B', list).tostring()

from Python Patterns - An Optimization Anecdote

Should I write script in the body or the head of the html?

Head, or before closure of body tag. When DOM loads JS is then executed, that is exactly what jQuery document.ready does.

Set focus on <input> element

In Angular, within HTML itself, you can set focus to input on click of a button.

<button (click)="myInput.focus()">Click Me</button>

<input #myInput></input>

Increase max execution time for php

Add these lines of code in your htaccess file. I hope it will solve your problem.

<IfModule mod_php5.c>
php_value max_execution_time 259200
</IfModule>

Get property value from C# dynamic object by string (reflection?)

I don't know if there's a more elegant way with dynamically created objects, but using plain old reflection should work:

var nameOfProperty = "property1";
var propertyInfo = myObject.GetType().GetProperty(nameOfProperty);
var value = propertyInfo.GetValue(myObject, null);

GetProperty will return null if the type of myObject does not contain a public property with this name.


EDIT: If the object is not a "regular" object but something implementing IDynamicMetaObjectProvider, this approach will not work. Please have a look at this question instead:

Read data from a text file using Java

public class FilesStrings {

public static void main(String[] args) throws FileNotFoundException, IOException {
    FileInputStream fis = new FileInputStream("input.txt");
    InputStreamReader input = new InputStreamReader(fis);
    BufferedReader br = new BufferedReader(input);
    String data;
    String result = new String();

    while ((data = br.readLine()) != null) {
        result = result.concat(data + " ");
    }

    System.out.println(result);

MySQL - length() vs char_length()

varchar(10) will store 10 characters, which may be more than 10 bytes. In indexes, it will allocate the maximium length of the field - so if you are using UTF8-mb4, it will allocate 40 bytes for the 10 character field.

How to request Location Permission at runtime

Google has created a library for easy Permissions management. Its called EasyPermissions

Here is a simple example on requesting Location permission using this library.

public class MainActivity extends AppCompatActivity {

    private final int REQUEST_LOCATION_PERMISSION = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestLocationPermission();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @AfterPermissionGranted(REQUEST_LOCATION_PERMISSION)
    public void requestLocationPermission() {
        String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION};
        if(EasyPermissions.hasPermissions(this, perms)) {
            Toast.makeText(this, "Permission already granted", Toast.LENGTH_SHORT).show();
        }
        else {
            EasyPermissions.requestPermissions(this, "Please grant the location permission", REQUEST_LOCATION_PERMISSION, perms);
        }
    }
}

@AfterPermissionsGranted(REQUEST_CODE) is used to indicate the method that needs to be executed after a permission request with the request code REQUEST_CODE has been granted.

This above case, the method requestLocationPermission() method is called if the user grants the permission to access location services. So, that method acts as both a callback and a method to request the permissions.

You can implement separate callbacks for permission granted and permission denied as well. It is explained in the github page.

jQuery to retrieve and set selected option value of html select element

I know this is old but I just had a bear of a time with Razor, could not get it to work no matter how hard I tried. Kept coming back as "undefined" no matter if I used "text" or "html" for attribute. Finally I added "data-value" attribute to the option and it read that just fine.

 <option value="1" data-value="MyText">MyText</option>

 var DisplayText = $(this).find("option:selected").attr("data-value");

What is the MySQL VARCHAR max size?

From MySQL documentation:

The effective maximum length of a VARCHAR in MySQL 5.0.3 and later is subject to the maximum row size (65,535 bytes, which is shared among all columns) and the character set used. For example, utf8 characters can require up to three bytes per character, so a VARCHAR column that uses the utf8 character set can be declared to be a maximum of 21,844 characters.

Limits for the VARCHAR varies depending on charset used. Using ASCII would use 1 byte per character. Meaning you could store 65,535 characters. Using utf8 will use 3 bytes per character resulting in character limit of 21,844. BUT if you are using the modern multibyte charset utf8mb4 which you should use! It supports emojis and other special characters. It will be using 4 bytes per character. This will limit the number of characters per table to 16,383. Note that other fields such as INT will also be counted to these limits.

Conclusion:

utf8 maximum of 21,844 characters

utf8mb4 maximum of 16,383 characters

Dictionary returning a default value if the key does not exist

TryGetValue will already assign the default value for the type to the dictionary, so you can just use:

dictionary.TryGetValue(key, out value);

and just ignore the return value. However, that really will just return default(TValue), not some custom default value (nor, more usefully, the result of executing a delegate). There's nothing more powerful built into the framework. I would suggest two extension methods:

public static TValue GetValueOrDefault<TKey, TValue>
    (this IDictionary<TKey, TValue> dictionary, 
     TKey key,
     TValue defaultValue)
{
    TValue value;
    return dictionary.TryGetValue(key, out value) ? value : defaultValue;
}

public static TValue GetValueOrDefault<TKey, TValue>
    (this IDictionary<TKey, TValue> dictionary,
     TKey key,
     Func<TValue> defaultValueProvider)
{
    TValue value;
    return dictionary.TryGetValue(key, out value) ? value
         : defaultValueProvider();
}

(You may want to put argument checking in, of course :)

How to shutdown a Spring Boot Application in a correct way?

You can make the springboot application to write the PID into file and you can use the pid file to stop or restart or get the status using a bash script. To write the PID to a file, register a listener to SpringApplication using ApplicationPidFileWriter as shown below :

SpringApplication application = new SpringApplication(Application.class);
application.addListeners(new ApplicationPidFileWriter("./bin/app.pid"));
application.run();

Then write a bash script to run the spring boot application . Reference.

Now you can use the script to start,stop or restart.

How to create module-wide variables in Python?

Steveha's answer was helpful to me, but omits an important point (one that I think wisty was getting at). The global keyword is not necessary if you only access but do not assign the variable in the function.

If you assign the variable without the global keyword then Python creates a new local var -- the module variable's value will now be hidden inside the function. Use the global keyword to assign the module var inside a function.

Pylint 1.3.1 under Python 2.7 enforces NOT using global if you don't assign the var.

module_var = '/dev/hello'

def readonly_access():
    connect(module_var)

def readwrite_access():
    global module_var
    module_var = '/dev/hello2'
    connect(module_var)

Java serialization - java.io.InvalidClassException local class incompatible

For me, I forgot to add the default serial id.

private static final long serialVersionUID = 1L;

Overflow-x:hidden doesn't prevent content from overflowing in mobile browsers

Creating a site wrapper div inside the <body> and applying the overflow-x:hidden to the wrapper instead of the <body> or <html> fixed the issue.

It appears that browsers that parse the <meta name="viewport"> tag simply ignore overflow attributes on the html and body tags.

Note: You may also need to add position: relative to the wrapper div.

Adding click event listener to elements with the same class

The problem with using querySelectorAll and a for loop is that it creates a whole new event handler for each element in the array.

Sometimes that is exactly what you want. But if you have many elements, it may be more efficient to create a single event handler and attach it to a container element. You can then use event.target to refer to the specific element which triggered the event:

document.body.addEventListener("click", function (event) {
  if (event.target.classList.contains("delete")) {
    var title = event.target.getAttribute("title");

    if (!confirm("sure u want to delete " + title)) {
      event.preventDefault();
    }
  }
});

In this example we only create one event handler which is attached to the body element. Whenever an element inside the body is clicked, the click event bubbles up to our event handler.

How do you add an in-app purchase to an iOS application?

RMStore is a lightweight iOS library for In-App Purchases. It wraps StoreKit API and provides you with handy blocks for asynchronous requests. Purchasing a product is as easy as calling a single method.

For the advanced users, this library also provides receipt verification, content downloads and transaction persistence.

Javascript : Send JSON Object with Ajax?

Adding Json.stringfy around the json that fixed the issue

json_encode() escaping forward slashes

On the flip side, I was having an issue with PHPUNIT asserting urls was contained in or equal to a url that was json_encoded -

my expected:

http://localhost/api/v1/admin/logs/testLog.log

would be encoded to:

http:\/\/localhost\/api\/v1\/admin\/logs\/testLog.log

If you need to do a comparison, transforming the url using:

addcslashes($url, '/')

allowed for the proper output during my comparisons.

"An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP

Please confirm that your firewall is allowing outbound traffic and that you are not being blocked by antivirus software.

I received the same issue and the culprit was antivirus software.

Combining two lists and removing duplicates, without removing duplicates in original list

    first_list = [1, 2, 2, 5]
    second_list = [2, 5, 7, 9]

    newList=[]
    for i in first_list:
        newList.append(i)
    for z in second_list:
        if z not in newList:
            newList.append(z)
    newList.sort()
    print newList

[1, 2, 2, 5, 7, 9]

How can I check if string contains characters & whitespace, not just whitespace?

if (/^\s+$/.test(myString))
{
      //string contains only whitespace
}

this checks for 1 or more whitespace characters, if you it to also match an empty string then replace + with *.

Converting string to date in mongodb

Using MongoDB 4.0 and newer

The $toDate operator will convert the value to a date. If the value cannot be converted to a date, $toDate errors. If the value is null or missing, $toDate returns null:

You can use it within an aggregate pipeline as follows:

db.collection.aggregate([
    { "$addFields": {
        "created_at": {
            "$toDate": "$created_at"
        }
    } }
])

The above is equivalent to using the $convert operator as follows:

db.collection.aggregate([
    { "$addFields": {
        "created_at": { 
            "$convert": { 
                "input": "$created_at", 
                "to": "date" 
            } 
        }
    } }
])

Using MongoDB 3.6 and newer

You cab also use the $dateFromString operator which converts the date/time string to a date object and has options for specifying the date format as well as the timezone:

db.collection.aggregate([
    { "$addFields": {
        "created_at": { 
            "$dateFromString": { 
                "dateString": "$created_at",
                "format": "%m-%d-%Y" /* <-- option available only in version 4.0. and newer */
            } 
        }
    } }
])

Using MongoDB versions >= 2.6 and < 3.2

If MongoDB version does not have the native operators that do the conversion, you would need to manually iterate the cursor returned by the find() method by either using the forEach() method or the cursor method next() to access the documents. Withing the loop, convert the field to an ISODate object and then update the field using the $set operator, as in the following example where the field is called created_at and currently holds the date in string format:

var cursor = db.collection.find({"created_at": {"$exists": true, "$type": 2 }}); 
while (cursor.hasNext()) { 
    var doc = cursor.next(); 
    db.collection.update(
        {"_id" : doc._id}, 
        {"$set" : {"created_at" : new ISODate(doc.created_at)}}
    ) 
};

For improved performance especially when dealing with large collections, take advantage of using the Bulk API for bulk updates as you will be sending the operations to the server in batches of say 1000 which gives you a better performance as you are not sending every request to the server, just once in every 1000 requests.

The following demonstrates this approach, the first example uses the Bulk API available in MongoDB versions >= 2.6 and < 3.2. It updates all the documents in the collection by changing the created_at fields to date fields:

var bulk = db.collection.initializeUnorderedBulkOp(),
    counter = 0;

db.collection.find({"created_at": {"$exists": true, "$type": 2 }}).forEach(function (doc) {
    var newDate = new ISODate(doc.created_at);
    bulk.find({ "_id": doc._id }).updateOne({ 
        "$set": { "created_at": newDate}
    });

    counter++;
    if (counter % 1000 == 0) {
        bulk.execute(); // Execute per 1000 operations and re-initialize every 1000 update statements
        bulk = db.collection.initializeUnorderedBulkOp();
    }
})
// Clean up remaining operations in queue
if (counter % 1000 != 0) { bulk.execute(); }

Using MongoDB 3.2

The next example applies to the new MongoDB version 3.2 which has since deprecated the Bulk API and provided a newer set of apis using bulkWrite():

var bulkOps = [],
    cursor = db.collection.find({"created_at": {"$exists": true, "$type": 2 }});

cursor.forEach(function (doc) { 
    var newDate = new ISODate(doc.created_at);
    bulkOps.push(         
        { 
            "updateOne": { 
                "filter": { "_id": doc._id } ,              
                "update": { "$set": { "created_at": newDate } } 
            }         
        }           
    );

    if (bulkOps.length === 500) {
        db.collection.bulkWrite(bulkOps);
        bulkOps = [];
    }     
});

if (bulkOps.length > 0) db.collection.bulkWrite(bulkOps);

How to use OpenCV SimpleBlobDetector

You may store the parameters for the blob detector in a file, but this is not necessary. Example:

// set up the parameters (check the defaults in opencv's code in blobdetector.cpp)
cv::SimpleBlobDetector::Params params;
params.minDistBetweenBlobs = 50.0f;
params.filterByInertia = false;
params.filterByConvexity = false;
params.filterByColor = false;
params.filterByCircularity = false;
params.filterByArea = true;
params.minArea = 20.0f;
params.maxArea = 500.0f;
// ... any other params you don't want default value

// set up and create the detector using the parameters
cv::SimpleBlobDetector blob_detector(params);
// or cv::Ptr<cv::SimpleBlobDetector> detector = cv::SimpleBlobDetector::create(params)

// detect!
vector<cv::KeyPoint> keypoints;
blob_detector.detect(image, keypoints);

// extract the x y coordinates of the keypoints: 

for (int i=0; i<keypoints.size(); i++){
    float X = keypoints[i].pt.x; 
    float Y = keypoints[i].pt.y;
}

Checking if a string can be converted to float in Python

If you cared about performance (and I'm not suggesting you should), the try-based approach is the clear winner (compared with your partition-based approach or the regexp approach), as long as you don't expect a lot of invalid strings, in which case it's potentially slower (presumably due to the cost of exception handling).

Again, I'm not suggesting you care about performance, just giving you the data in case you're doing this 10 billion times a second, or something. Also, the partition-based code doesn't handle at least one valid string.

$ ./floatstr.py
F..
partition sad: 3.1102449894
partition happy: 2.09208488464
..
re sad: 7.76906108856
re happy: 7.09421992302
..
try sad: 12.1525540352
try happy: 1.44165301323
.
======================================================================
FAIL: test_partition (__main__.ConvertTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "./floatstr.py", line 48, in test_partition
    self.failUnless(is_float_partition("20e2"))
AssertionError

----------------------------------------------------------------------
Ran 8 tests in 33.670s

FAILED (failures=1)

Here's the code (Python 2.6, regexp taken from John Gietzen's answer):

def is_float_try(str):
    try:
        float(str)
        return True
    except ValueError:
        return False

import re
_float_regexp = re.compile(r"^[-+]?(?:\b[0-9]+(?:\.[0-9]*)?|\.[0-9]+\b)(?:[eE][-+]?[0-9]+\b)?$")
def is_float_re(str):
    return re.match(_float_regexp, str)


def is_float_partition(element):
    partition=element.partition('.')
    if (partition[0].isdigit() and partition[1]=='.' and partition[2].isdigit()) or (partition[0]=='' and partition[1]=='.' and pa\
rtition[2].isdigit()) or (partition[0].isdigit() and partition[1]=='.' and partition[2]==''):
        return True

if __name__ == '__main__':
    import unittest
    import timeit

    class ConvertTests(unittest.TestCase):
        def test_re(self):
            self.failUnless(is_float_re("20e2"))

        def test_try(self):
            self.failUnless(is_float_try("20e2"))

        def test_re_perf(self):
            print
            print 're sad:', timeit.Timer('floatstr.is_float_re("12.2x")', "import floatstr").timeit()
            print 're happy:', timeit.Timer('floatstr.is_float_re("12.2")', "import floatstr").timeit()

        def test_try_perf(self):
            print
            print 'try sad:', timeit.Timer('floatstr.is_float_try("12.2x")', "import floatstr").timeit()
            print 'try happy:', timeit.Timer('floatstr.is_float_try("12.2")', "import floatstr").timeit()

        def test_partition_perf(self):
            print
            print 'partition sad:', timeit.Timer('floatstr.is_float_partition("12.2x")', "import floatstr").timeit()
            print 'partition happy:', timeit.Timer('floatstr.is_float_partition("12.2")', "import floatstr").timeit()

        def test_partition(self):
            self.failUnless(is_float_partition("20e2"))

        def test_partition2(self):
            self.failUnless(is_float_partition(".2"))

        def test_partition3(self):
            self.failIf(is_float_partition("1234x.2"))

    unittest.main()

Why does Eclipse automatically add appcompat v7 library support whenever I create a new project?

If you are not targeting 2.x versions you can set your minimum sdk version of 4.x and then create project. Appcompat V7 lib wont be created.

JRE installation directory in Windows

Not as a command, but this information is in the registry:

  • Open the key HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
  • Read the CurrentVersion REG_SZ
  • Open the subkey under Java Runtime Environment named with the CurrentVersion value
  • Read the JavaHome REG_SZ to get the path

For example on my workstation i have

HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
  CurrentVersion = "1.6"
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.5
  JavaHome = "C:\Program Files\Java\jre1.5.0_20"
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.6
  JavaHome = "C:\Program Files\Java\jre6"

So my current JRE is in C:\Program Files\Java\jre6

Select specific row from mysql table

Your table will need to be created with a unique ID field that will ideally have the AUTO_INCREMENT attribute. example:

CREATE TABLE Persons
(
P_Id int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
PRIMARY KEY (P_Id)
)

Then you can access the 3rd record in this table with:

SELECT * FROM Persons WHERE P_Id = 3

How do I use Spring Boot to serve static content located in Dropbox folder?

For the current Spring-Boot Version 1.5.3 the parameter is

spring.resources.static-locations

Update I configured

`spring.resources.static-locations=file:/opt/x/y/z/static``

and expected to get my index.html living in this folder when calling

http://<host>/index.html

This did not work. I had to include the folder name in the URL:

http://<host>/static/index.html

Spring boot: Unable to start embedded Tomcat servlet container

You need to Tomcat Dependency and also extend your Application Class from extends SpringBootServletInitializer

@SpringBootApplication  
public class App extend SpringBootServletInitializer
{
    public static void main( String[] args )
    {
        SpringApplication.run(App.class, "hello");
    }
}

How to read a file into a variable in shell?

If you want to read the whole file into a variable:

#!/bin/bash
value=`cat sources.xml`
echo $value

If you want to read it line-by-line:

while read line; do    
    echo $line    
done < file.txt

Strip double quotes from a string in .NET

c#: "\"", thus s.Replace("\"", "")

vb/vbs/vb.net: "" thus s.Replace("""", "")

Delete many rows from a table using id in Mysql

Something like this might make it a bit easier, you could obviously use a script to generate this, or even excel

DELETE FROM tablename WHERE id IN (
1,
2,
3,
4,
5,
6
);

Oracle SQL query for Date format

you can use this command by getting your data. this will extract your data...

select * from employees where to_char(es_date,'dd/mon/yyyy')='17/jun/2003';

How do I change the font color in an html table?

Something like this, if want to go old-school.

<font color="blue">Sustaining : $60.00 USD - yearly</font>

Though a more modern approach would be to use a css style:

<td style="color:#0000ff">Sustaining : $60.00 USD - yearly</td>

There are of course even more general ways to do it.

Difference between maven scope compile and provided for JAR packaging

From the Maven Doc:

  • compile

    This is the default scope, used if none is specified. Compile dependencies are available in all classpaths of a project. Furthermore, those dependencies are propagated to dependent projects.

  • provided

    This is much like compile, but indicates you expect the JDK or a container to provide the dependency at runtime. For example, when building a web application for the Java Enterprise Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope provided because the web container provides those classes. This scope is only available on the compilation and test classpath, and is not transitive.

Recap:

  • dependencies are not transitive (as you mentioned)
  • provided scope is only available on the compilation and test classpath, whereas compile scope is available in all classpaths.
  • provided dependencies are not packaged

Serialize JavaScript object into JSON string

Well, the type of an element is not standardly serialized, so you should add it manually. For example

var myobject = new MyClass1("5678999", "text");
var toJSONobject = { objectType: myobject.constructor, objectProperties: myobject };
console.log(JSON.stringify(toJSONobject));

Good luck!

edit: changed typeof to the correct .constructor. See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/constructor for more information on the constructor property for Objects.

How to compare different branches in Visual Studio Code

It's now possible by using the githistory extension.

Here's a small trick though: You can compare the latest commits from each branch and that would be the same as comparing two branches side by side or creating a PR.

Here's how to do that using githistory extension:

  1. Open githistory
  2. Pick the latest commit from your current branch by clicking on "Git Commit Icon" → (Usually it should be latest commit it the list). From the opened dropdown menu click on "Select this commit".
  3. Pick the latest commit from the branch you want to compare to by clicking "Git Commit Icon".
  4. As a result, the dropdown should appear with a few options → Select the last option that says "Compare with SHA" and you'll see the diff.

Android Studio - Device is connected but 'offline'

Disabling and Enabling the Developer options and debug mode on the Android phone settings fixed the issue.

Function to close the window in Tkinter

class App():
    def __init__(self):
        self.root = Tkinter.Tk()
        button = Tkinter.Button(self.root, text = 'root quit', command=self.quit)
        button.pack()
        self.root.mainloop()

    def quit(self):
        self.root.destroy()

app = App()

var.replace is not a function

You should use toString() Method of java script for the convert into string before because replace method is a string function.

Load data from txt with pandas

you can use this

import pandas as pd
dataset=pd.read_csv("filepath.txt",delimiter="\t")

Android list view inside a scroll view

I had a similar problem to the issue posed by the Original Poster - how to make the listview scroll inside the scrollview - and this answer solved my problem. Disable scrolling of a ListView contained within a ScrollView

I didn't call new fragments into existing layouts or anything like that, like the OP was doing, so my code would look something like this :

<ScrollView
    android:id="@+id/scrollView1"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="2"
    android:fillViewport="true"
    android:gravity="top" >

 <LinearLayout
        android:id="@+id/foodItemActvity_linearLayout_fragments"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >


    <TextView
       android:id="@+id/fragment_dds_review_textView_label"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Reviews:"
       android:textAppearance="?android:attr/textAppearanceMedium" />

   <ListView
       android:id="@+id/my_listView"
       android:layout_width="match_parent"
       android:layout_height="wrap_content">
   </ListView>

</LinearLayout>

</ScrollView>

Basically what I am doing is checking the length of the listview before I call it and when I call it I make it into that length. In your java class use this function:

public static void justifyListViewHeightBasedOnChildren (ListView listView) {

    ListAdapter adapter = listView.getAdapter();

    if (adapter == null) {
        return;
    }
    ViewGroup vg = listView;
    int totalHeight = 0;
    for (int i = 0; i < adapter.getCount(); i++) {
        View listItem = adapter.getView(i, null, vg);
        listItem.measure(0, 0);
        totalHeight += listItem.getMeasuredHeight();
    }

    ViewGroup.LayoutParams par = listView.getLayoutParams();
    par.height = totalHeight + (listView.getDividerHeight() * (adapter.getCount() - 1));
    listView.setLayoutParams(par);
    listView.requestLayout();
}

And call the function like this:

justifyListViewHeightBasedOnChildren(listView);

The result is a listview with no scrollbar, the whole length of the listview being displayed, that scrolls with the scroll bar of the scrollview.

ie8 var w= window.open() - "Message: Invalid argument."

This is an old posting but maybe still useful for someone.

I had the same error message. In the end the problem was an invalid name for the second argument, i.e., I had a line like:

   window.open('/somefile.html', 'a window title', 'width=300');

The problem was 'a window title' as it is not valid. It worked fine with the following line:

   window.open('/somefile.html', '', 'width=300');

In fact, reading carefully I realized that Microsoft does not support a name as second argument. When you look at the official documentation page, you see that Microsoft only allows the following arguments, If using that argument at all:

  • _blank
  • _media
  • _parent
  • _search
  • _self
  • _top

How to serve up images in Angular2?

In angular only one page is requested from server, that is index.html. And index.html and assets folder are on same directory. while putting image in any component give src value like assets\image.png. This will work fine because browser will make request to server for that image and webpack will be able serve that image.

Finding the average of an array using JS

answer to your 1. question:

for ( var i = 0; i < grades.length; i ++){
    var avg = (grades[i] / grades.length) * grades.length
}

avg is declared in each loop. Thus, at the end of the loop, avg has the value of the last item in the array : 68 *5 / 5

How can I check out a GitHub pull request with git?

If you are using Github.com, go to "Pull requests", click on the relevant pull request, and then click on the "command line instructions" link: command line instructions at Github.com

Display a message in Visual Studio's output window when not debug mode?

For me this was the fact that debug.writeline shows in the Immediate window, not the Output. My installation of VS2013 by default doesn't even show an option to open the Immediate window, so you have to do the following:

Select Tools -> Customize 
Commands Tab
View | Other Windows menu bar dropdown
Add Command...
The Immediate option is in the Debug section.

Once you have Ok'd that, you can go to View -> Other Windows and select the Immediate Window and hey presto all of the debug output can be seen.

Unfortunately for me it also showed about 50 errors that I wasn't aware of in my project... maybe I'll just turn it off again :-)

send checkbox value in PHP form

If the checkbox is checked you will get a value for it in your $_POST array. If it isn't the element will be omitted from the array altogether.

The easiest way to test it is like this:

if (isset($_POST['myCheckbox'])) {
  $checkBoxValue = "yes";
} else {
  $checkBoxValue = "no";
}

For your code, add it immediately below the other preprocessing:

$name = $_POST['name']; 
$email_address = $_POST['email']; 
$message = $_POST['tel']; 

if (isset($_POST['newsletter'])) {
  $newsletter = "yes";
} else {
  $newsletter = "no";
}

You'll also need to change the HTML slightly. Change this line:

<input type="checkbox" name="newsletter[]" value="newsletter" checked>i want to sign up for newsletter<br>

to this:

<input type="checkbox" name="newsletter" value="newsletter" checked>i want to sign up   for newsletter<br>
                                      ^^^ remove square brackets here.

Convert hex string to int in Python

int(hexstring, 16) does the trick, and works with and without the 0x prefix:

>>> int("a", 16)
10
>>> int("0xa", 16)
10

How to use group by with union in t-sql

You need to alias the subquery. Thus, your statement should be:

Select Z.id
From    (
        Select id, time
        From dbo.tablea
        Union All
        Select id, time
        From dbo.tableb
        ) As Z
Group By Z.id

LoDash: Get an array of values from an array of object properties

With pure JS:

var userIds = users.map( function(obj) { return obj.id; } );

Draw horizontal rule in React Native

Maybe you should try using react-native-hr something like this:

<Hr lineColor='#b3b3b3'/>

documentation: https://www.npmjs.com/package/react-native-hr

How can I hide a TD tag using inline JavaScript or CSS?

If you have more than this in javascript consider some javascript library, e.g. jquery which takes away a little speed, but gives you more readable code.

Your question's code via jquery:

$("td").hide();

Of course there are other javascript libraries out there, as this comparison on wikipedia shows.

How to add a RequiredFieldValidator to DropDownList control?

Suppose your drop down list is:

<asp:DropDownList runat="server" id="ddl">
<asp:ListItem Value="0" text="Select a Value">
....
</asp:DropDownList>

There are two ways:

<asp:RequiredFieldValidator ID="re1" runat="Server" InitialValue="0" />

the 2nd way is to use a compare validator:

<asp:CompareValidator ID="re1" runat="Server" ValueToCompare="0" ControlToCompare="ddl" Operator="Equal" />

How to inherit constructors?

The problem is not that Bar and Bah have to copy 387 constructors, the problem is that Foo has 387 constructors. Foo clearly does too many things - refactor quick! Also, unless you have a really good reason to have values set in the constructor (which, if you provide a parameterless constructor, you probably don't), I'd recommend using property getting/setting.

Fit Image into PictureBox

You could try changing the: SizeMode property of the PictureBox.

You could also set your image as the BackGroundImage of the PictureBox and try changing the BackGroundImageLayout to the correct mode.

javac is not recognized as an internal or external command, operable program or batch file

You mistyped the set command – you missed the backslash after C:. It should be:

C:\>set path=C:\Program Files (x86)\Java\jdk1.7.0\bin

How to print star pattern in JavaScript in a very simple manner?

for(var a=1;a<8;a++){   
    var o="";  
    for(var b=1;b<=a;b++){  
        o +="#";    
    }   
    debug(o);   
}

Try above code.

Output:

--> #
--> ##
--> ###
--> ####
--> #####
--> ######

PHP multiline string with PHP

Use the show_source(); function of PHP. Check for more details in show_source. This is a better method I guess.

Spring Boot not serving static content

Given resources under src/main/resources/static, if you add this code, then all static content from src/main/resources/static will be available under "/":

@Configuration
public class StaticResourcesConfigurer implements WebMvcConfigurer {
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/static/");
    }
}

X-Frame-Options Allow-From multiple domains

Necromancing.
The provided answers are incomplete.

First, as already said, you cannot add multiple allow-from hosts, that's not supported.
Second, you need to dynamically extract that value from the HTTP referrer, which means that you can't add the value to Web.config, because it's not always the same value.

It will be necessary to do browser-detection to avoid adding allow-from when the browser is Chrome (it produces an error on the debug - console, which can quickly fill the console up, or make the application slow). That also means you need to modify the ASP.NET browser detection, as it wrongly identifies Edge as Chrome.

This can be done in ASP.NET by writing a HTTP-module which runs on every request, that appends a http-header for every response, depending on the request's referrer. For Chrome, it needs to add Content-Security-Policy.

// https://stackoverflow.com/questions/31870789/check-whether-browser-is-chrome-or-edge
public class BrowserInfo
{

    public System.Web.HttpBrowserCapabilities Browser { get; set; }
    public string Name { get; set; }
    public string Version { get; set; }
    public string Platform { get; set; }
    public bool IsMobileDevice { get; set; }
    public string MobileBrand { get; set; }
    public string MobileModel { get; set; }


    public BrowserInfo(System.Web.HttpRequest request)
    {
        if (request.Browser != null)
        {
            if (request.UserAgent.Contains("Edge")
                && request.Browser.Browser != "Edge")
            {
                this.Name = "Edge";
            }
            else
            {
                this.Name = request.Browser.Browser;
                this.Version = request.Browser.MajorVersion.ToString();
            }
            this.Browser = request.Browser;
            this.Platform = request.Browser.Platform;
            this.IsMobileDevice = request.Browser.IsMobileDevice;
            if (IsMobileDevice)
            {
                this.Name = request.Browser.Browser;
            }
        }
    }


}


void context_EndRequest(object sender, System.EventArgs e)
{
    if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Response != null)
    {
        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;

        try
        {
            // response.Headers["P3P"] = "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"":
            // response.Headers.Set("P3P", "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"");
            // response.AddHeader("P3P", "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"");
            response.AppendHeader("P3P", "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"");

            // response.AppendHeader("X-Frame-Options", "DENY");
            // response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
            // response.AppendHeader("X-Frame-Options", "AllowAll");

            if (System.Web.HttpContext.Current.Request.UrlReferrer != null)
            {
                // "X-Frame-Options": "ALLOW-FROM " Not recognized in Chrome 
                string host = System.Web.HttpContext.Current.Request.UrlReferrer.Scheme + System.Uri.SchemeDelimiter
                            + System.Web.HttpContext.Current.Request.UrlReferrer.Authority
                ;

                string selfAuth = System.Web.HttpContext.Current.Request.Url.Authority;
                string refAuth = System.Web.HttpContext.Current.Request.UrlReferrer.Authority;

                // SQL.Log(System.Web.HttpContext.Current.Request.RawUrl, System.Web.HttpContext.Current.Request.UrlReferrer.OriginalString, refAuth);

                if (IsHostAllowed(refAuth))
                {
                    BrowserInfo bi = new BrowserInfo(System.Web.HttpContext.Current.Request);

                    // bi.Name = Firefox
                    // bi.Name = InternetExplorer
                    // bi.Name = Chrome

                    // Chrome wants entire path... 
                    if (!System.StringComparer.OrdinalIgnoreCase.Equals(bi.Name, "Chrome"))
                        response.AppendHeader("X-Frame-Options", "ALLOW-FROM " + host);    

                    // unsafe-eval: invalid JSON https://github.com/keen/keen-js/issues/394
                    // unsafe-inline: styles
                    // data: url(data:image/png:...)

                    // https://www.owasp.org/index.php/Clickjacking_Defense_Cheat_Sheet
                    // https://www.ietf.org/rfc/rfc7034.txt
                    // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options
                    // https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP

                    // https://stackoverflow.com/questions/10205192/x-frame-options-allow-from-multiple-domains
                    // https://content-security-policy.com/
                    // http://rehansaeed.com/content-security-policy-for-asp-net-mvc/

                    // This is for Chrome:
                    // response.AppendHeader("Content-Security-Policy", "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: *.msecnd.net vortex.data.microsoft.com " + selfAuth + " " + refAuth);


                    System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>();
                    ls.Add("default-src");
                    ls.Add("'self'");
                    ls.Add("'unsafe-inline'");
                    ls.Add("'unsafe-eval'");
                    ls.Add("data:");

                    // http://az416426.vo.msecnd.net/scripts/a/ai.0.js

                    // ls.Add("*.msecnd.net");
                    // ls.Add("vortex.data.microsoft.com");

                    ls.Add(selfAuth);
                    ls.Add(refAuth);

                    string contentSecurityPolicy = string.Join(" ", ls.ToArray());
                    response.AppendHeader("Content-Security-Policy", contentSecurityPolicy);
                }
                else
                {
                    response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
                }

            }
            else
                response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
        }
        catch (System.Exception ex)
        {
            // WTF ? 
            System.Console.WriteLine(ex.Message); // Suppress warning
        }

    } // End if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Response != null)

} // End Using context_EndRequest


private static string[] s_allowedHosts = new string[] 
{
     "localhost:49533"
    ,"localhost:52257"
    ,"vmcompany1"
    ,"vmcompany2"
    ,"vmpostalservices"
    ,"example.com"
};


public static bool IsHostAllowed(string host)
{
    return Contains(s_allowedHosts, host);
} // End Function IsHostAllowed 


public static bool Contains(string[] allowed, string current)
{
    for (int i = 0; i < allowed.Length; ++i)
    {
        if (System.StringComparer.OrdinalIgnoreCase.Equals(allowed[i], current))
            return true;
    } // Next i 

    return false;
} // End Function Contains 

You need to register the context_EndRequest function in the HTTP-module Init function.

public class RequestLanguageChanger : System.Web.IHttpModule
{


    void System.Web.IHttpModule.Dispose()
    {
        // throw new NotImplementedException();
    }


    void System.Web.IHttpModule.Init(System.Web.HttpApplication context)
    {
        // https://stackoverflow.com/questions/441421/httpmodule-event-execution-order
        context.EndRequest += new System.EventHandler(context_EndRequest);
    }

    // context_EndRequest Code from above comes here


}

Next you need to add the module to your application. You can either do this programmatically in Global.asax by overriding the Init function of the HttpApplication, like this:

namespace ChangeRequestLanguage
{


    public class Global : System.Web.HttpApplication
    {

        System.Web.IHttpModule mod = new libRequestLanguageChanger.RequestLanguageChanger();

        public override void Init()
        {
            mod.Init(this);
            base.Init();
        }



        protected void Application_Start(object sender, System.EventArgs e)
        {

        }

        protected void Session_Start(object sender, System.EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, System.EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, System.EventArgs e)
        {

        }

        protected void Application_Error(object sender, System.EventArgs e)
        {

        }

        protected void Session_End(object sender, System.EventArgs e)
        {

        }

        protected void Application_End(object sender, System.EventArgs e)
        {

        }


    }


}

or you can add entries to Web.config if you don't own the application source-code:

      <httpModules>
        <add name="RequestLanguageChanger" type= "libRequestLanguageChanger.RequestLanguageChanger, libRequestLanguageChanger" />
      </httpModules>
    </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>

    <modules runAllManagedModulesForAllRequests="true">
      <add name="RequestLanguageChanger" type="libRequestLanguageChanger.RequestLanguageChanger, libRequestLanguageChanger" />
    </modules>
  </system.webServer>
</configuration>

The entry in system.webServer is for IIS7+, the other in system.web is for IIS 6.
Note that you need to set runAllManagedModulesForAllRequests to true, for that it works properly.

The string in type is in the format "Namespace.Class, Assembly". Note that if you write your assembly in VB.NET instead of C#, VB creates a default-Namespace for each project, so your string will look like

"[DefaultNameSpace.Namespace].Class, Assembly"

If you want to avoid this problem, write the DLL in C#.

Is there a minlength validation attribute in HTML5?

My solution for textarea using jQuery and combining HTML5 required validation to check the minimum length.

minlength.js

$(document).ready(function(){
  $('form textarea[minlength]').on('keyup', function(){
    e_len = $(this).val().trim().length
    e_min_len = Number($(this).attr('minlength'))
    message = e_min_len <= e_len ? '' : e_min_len + ' characters minimum'
    this.setCustomValidity(message)
  })
})

HTML

<form action="">
  <textarea name="test_min_length" id="" cols="30" rows="10" minlength="10"></textarea>
</form>

How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites

from now, unix timestamp param,

function timeSince(ts){
    now = new Date();
    ts = new Date(ts*1000);
    var delta = now.getTime() - ts.getTime();

    delta = delta/1000; //us to s

    var ps, pm, ph, pd, min, hou, sec, days;

    if(delta<=59){
        ps = (delta>1) ? "s": "";
        return delta+" second"+ps
    }

    if(delta>=60 && delta<=3599){
        min = Math.floor(delta/60);
        sec = delta-(min*60);
        pm = (min>1) ? "s": "";
        ps = (sec>1) ? "s": "";
        return min+" minute"+pm+" "+sec+" second"+ps;
    }

    if(delta>=3600 && delta<=86399){
        hou = Math.floor(delta/3600);
        min = Math.floor((delta-(hou*3600))/60);
        ph = (hou>1) ? "s": "";
        pm = (min>1) ? "s": "";
        return hou+" hour"+ph+" "+min+" minute"+pm;
    } 

    if(delta>=86400){
        days = Math.floor(delta/86400);
        hou =  Math.floor((delta-(days*86400))/60/60);
        pd = (days>1) ? "s": "";
        ph = (hou>1) ? "s": "";
        return days+" day"+pd+" "+hou+" hour"+ph;
    }

}

How to fix nginx throws 400 bad request headers on any header testing tools?

When nginx returns 400(bad request) it will log the reason into error log, at "info" level and take a look into error log when testing.

Java: Integer equals vs. ==

Besides these given great answers, What I have learned is that:

NEVER compare objects with == unless you intend to be comparing them by their references.

How do I ignore files in a directory in Git?

I'm maintaining a GUI and CLI based service that allows you to generate .gitignore templates very easily at https://www.gitignore.io.

You can either type the templates you want in the search field or install the command line alias and run

$ gi swift,osx

Why should we NOT use sys.setdefaultencoding("utf-8") in a py script?

  • The first danger lies in reload(sys).

    When you reload a module, you actually get two copies of the module in your runtime. The old module is a Python object like everything else, and stays alive as long as there are references to it. So, half of the objects will be pointing to the old module, and half to the new one. When you make some change, you will never see it coming when some random object doesn't see the change:

    (This is IPython shell)
    
    In [1]: import sys
    
    In [2]: sys.stdout
    Out[2]: <colorama.ansitowin32.StreamWrapper at 0x3a2aac8>
    
    In [3]: reload(sys)
    <module 'sys' (built-in)>
    
    In [4]: sys.stdout
    Out[4]: <open file '<stdout>', mode 'w' at 0x00000000022E20C0>
    
    In [11]: import IPython.terminal
    
    In [14]: IPython.terminal.interactiveshell.sys.stdout
    Out[14]: <colorama.ansitowin32.StreamWrapper at 0x3a9aac8>
    
  • Now, sys.setdefaultencoding() proper

    All that it affects is implicit conversion str<->unicode. Now, utf-8 is the sanest encoding on the planet (backward-compatible with ASCII and all), the conversion now "just works", what could possibly go wrong?

    Well, anything. And that is the danger.

    • There may be some code that relies on the UnicodeError being thrown for non-ASCII input, or does the transcoding with an error handler, which now produces an unexpected result. And since all code is tested with the default setting, you're strictly on "unsupported" territory here, and no-one gives you guarantees about how their code will behave.
    • The transcoding may produce unexpected or unusable results if not everything on the system uses UTF-8 because Python 2 actually has multiple independent "default string encodings". (Remember, a program must work for the customer, on the customer's equipment.)
      • Again, the worst thing is you will never know that because the conversion is implicit -- you don't really know when and where it happens. (Python Zen, koan 2 ahoy!) You will never know why (and if) your code works on one system and breaks on another. (Or better yet, works in IDE and breaks in console.)

conditional Updating a list using LINQ

Try Parallel for longer lists:

Parallel.ForEach(li.Where(f => f.name == "di"), l => l.age = 10);

OSX - How to auto Close Terminal window after the "exit" command executed.

Actually, you should set a config on your Terminal, when your Terminal is up press ?+, then you will see below screen:

enter image description here

Then press shell tab and you will see below screen:

enter image description here

Now select Close if the shell exited cleanly for When the shell exits.

By the above config each time with exit command the Terminal will close but won't quit.

Laravel Eloquent limit and offset

skip = OFFSET
$products = $art->products->skip(0)->take(10)->get(); //get first 10 rows
$products = $art->products->skip(10)->take(10)->get(); //get next 10 rows

From laravel doc 5.2 https://laravel.com/docs/5.2/queries#ordering-grouping-limit-and-offset

skip / take

To limit the number of results returned from the query, or to skip a given number of results in the query (OFFSET), you may use the skip and take methods:

$users = DB::table('users')->skip(10)->take(5)->get();

In laravel 5.3 you can write (https://laravel.com/docs/5.3/queries#ordering-grouping-limit-and-offset)

$products = $art->products->offset(0)->limit(10)->get(); 

Running Groovy script from the command line

#!/bin/sh
sed '1,2d' "$0"|$(which groovy) /dev/stdin; exit;

println("hello");

How do I define a method in Razor?

Razor is just a templating engine.

You should create a regular class.

If you want to make a method inside of a Razor page, put them in an @functions block.

Delete a database in phpMyAdmin

  1. Connect to your localhost.
  2. Open your favorite browser.
  3. Make sure your localhost is working.
  4. Type in url= localhost.
  5. Scroll down click on phpadmin once phpadmin is open.
  6. Click on database.
  7. Mark check the database you want remove.
  8. Click on drop.

If this don't work

  1. Click on database go to operation
  2. Click drop database

How to plot a function curve in R

You mean like this?

> eq = function(x){x*x}
> plot(eq(1:1000), type='l')

Plot of eq over range 1:1000

(Or whatever range of values is relevant to your function)

What is the role of the package-lock.json?

package-lock.json is automatically generated for any operations where npm modifies either the node_modules tree, or package.json. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.

It describes a single representation of a dependency tree such that teammates, deployments, and continuous integration are guaranteed to install exactly the same dependencies.It contains the following properties.

{
    "name": "mobileapp",
    "version": "1.0.0",
    "lockfileVersion": 1,
    "requires": true,
    "dependencies": {
    "@angular-devkit/architect": {
      "version": "0.11.4",
      "resolved": "https://registry.npmjs.org/@angular- devkit/architect/-/architect-0.11.4.tgz",
      "integrity": "sha512-2zi6S9tPlk52vyqNFg==",
      "dev": true,
      "requires": {
        "@angular-devkit/core": "7.1.4",
        "rxjs": "6.3.3"
      }
    },
}       

Superscript in Python plots

If you want to write unit per meter (m^-1), use $m^{-1}$), which means -1 inbetween {}

Example: plt.ylabel("Specific Storage Values ($m^{-1}$)", fontsize = 12 )

How to create websockets server in PHP

I was in the same boat as you recently, and here is what I did:

  1. I used the phpwebsockets code as a reference for how to structure the server-side code. (You seem to already be doing this, and as you noted, the code doesn't actually work for a variety of reasons.)

  2. I used PHP.net to read the details about every socket function used in the phpwebsockets code. By doing this, I was finally able to understand how the whole system works conceptually. This was a pretty big hurdle.

  3. I read the actual WebSocket draft. I had to read this thing a bunch of times before it finally started to sink in. You will likely have to go back to this document again and again throughout the process, as it is the one definitive resource with correct, up-to-date information about the WebSocket API.

  4. I coded the proper handshake procedure based on the instructions in the draft in #3. This wasn't too bad.

  5. I kept getting a bunch of garbled text sent from the clients to the server after the handshake and I couldn't figure out why until I realized that the data is encoded and must be unmasked. The following link helped me a lot here: (original link broken) Archived copy.

    Please note that the code available at this link has a number of problems and won't work properly without further modification.

  6. I then came across the following SO thread, which clearly explains how to properly encode and decode messages being sent back and forth: How can I send and receive WebSocket messages on the server side?

    This link was really helpful. I recommend consulting it while looking at the WebSocket draft. It'll help make more sense out of what the draft is saying.

  7. I was almost done at this point, but had some issues with a WebRTC app I was making using WebSocket, so I ended up asking my own question on SO, which I eventually solved: What is this data at the end of WebRTC candidate info?

  8. At this point, I pretty much had it all working. I just had to add some additional logic for handling the closing of connections, and I was done.

That process took me about two weeks total. The good news is that I understand WebSocket really well now and I was able to make my own client and server scripts from scratch that work great. Hopefully the culmination of all that information will give you enough guidance and information to code your own WebSocket PHP script.

Good luck!


Edit: This edit is a couple of years after my original answer, and while I do still have a working solution, it's not really ready for sharing. Luckily, someone else on GitHub has almost identical code to mine (but much cleaner), so I recommend using the following code for a working PHP WebSocket solution:
https://github.com/ghedipunk/PHP-Websockets/blob/master/websockets.php


Edit #2: While I still enjoy using PHP for a lot of server-side related things, I have to admit that I've really warmed up to Node.js a lot recently, and the main reason is because it's better designed from the ground up to handle WebSocket than PHP (or any other server-side language). As such, I've found recently that it's a lot easier to set up both Apache/PHP and Node.js on your server and use Node.js for running the WebSocket server and Apache/PHP for everything else. And in the case where you're on a shared hosting environment in which you can't install/use Node.js for WebSocket, you can use a free service like Heroku to set up a Node.js WebSocket server and make cross-domain requests to it from your server. Just make sure if you do that to set your WebSocket server up to be able to handle cross-origin requests.

What does it mean if a Python object is "subscriptable" or not?

A scriptable object is an object that records the operations done to it and it can store them as a "script" which can be replayed.

For example, see: Application Scripting Framework

Now, if Alistair didn't know what he asked and really meant "subscriptable" objects (as edited by others), then (as mipadi also answered) this is the correct one:

A subscriptable object is any object that implements the __getitem__ special method (think lists, dictionaries).

JavaScript associative array to JSON

I posted a fix for this here

You can use this function to modify JSON.stringify to encode arrays, just post it near the beginning of your script (check the link above for more detail):

// Upgrade for JSON.stringify, updated to allow arrays
(function(){
    // Convert array to object
    var convArrToObj = function(array){
        var thisEleObj = new Object();
        if(typeof array == "object"){
            for(var i in array){
                var thisEle = convArrToObj(array[i]);
                thisEleObj[i] = thisEle;
            }
        }else {
            thisEleObj = array;
        }
        return thisEleObj;
    };
    var oldJSONStringify = JSON.stringify;
    JSON.stringify = function(input){
        if(oldJSONStringify(input) == '[]')
            return oldJSONStringify(convArrToObj(input));
        else
            return oldJSONStringify(input);
    };
})();

Use PHP composer to clone git repo

If you want to use a composer.json from GitHub you would look at this example (under the VCS section).

The package section is for packages that do not have the composer.json. However, you didn't follow that example as well or it would also have worked. Do read what it says about package repositories:

Basically, you define the same information that is included in the composer repository's packages.json, but only for a single package. Again, the minimum required fields are name, version, and either of dist or source.

How can I change the color of my prompt in zsh (different from normal text)?

To get a prompt with the color depending on the last command’s exit status, you could use this:

PS1='%(?.%F{green}.%F{red})%n@%m:%~%# %f'

Just add this line to your ~/.zshrc.

The documentation lists possible placeholders.

Formula to convert date to number

The Excel number for a modern date is most easily calculated as the number of days since 12/30/1899 on the Gregorian calendar.

Excel treats the mythical date 01/00/1900 (i.e., 12/31/1899) as corresponding to 0, and incorrectly treats year 1900 as a leap year. So for dates before 03/01/1900, the Excel number is effectively the number of days after 12/31/1899.

However, Excel will not format any number below 0 (-1 gives you ##########) and so this only matters for "01/00/1900" to 02/28/1900, making it easier to just use the 12/30/1899 date as a base.

A complete function in DB2 SQL that accounts for the leap year 1900 error:

SELECT
   DAYS(INPUT_DATE)                 
   - DAYS(DATE('1899-12-30'))
   - CASE                       
        WHEN INPUT_DATE < DATE('1900-03-01')  
           THEN 1               
           ELSE 0               
     END

adding noise to a signal in python

In real life you wish to simulate a signal with white noise. You should add to your signal random points that have Normal Gaussian distribution. If we speak about a device that have sensitivity given in unit/SQRT(Hz) then you need to devise standard deviation of your points from it. Here I give function "white_noise" that does this for you, an the rest of a code is demonstration and check if it does what it should.

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal

"""
parameters: 
rhp - spectral noise density unit/SQRT(Hz)
sr  - sample rate
n   - no of points
mu  - mean value, optional

returns:
n points of noise signal with spectral noise density of rho
"""
def white_noise(rho, sr, n, mu=0):
    sigma = rho * np.sqrt(sr/2)
    noise = np.random.normal(mu, sigma, n)
    return noise

rho = 1 
sr = 1000
n = 1000
period = n/sr
time = np.linspace(0, period, n)
signal_pure = 100*np.sin(2*np.pi*13*time)
noise = white_noise(rho, sr, n)
signal_with_noise = signal_pure + noise

f, psd = signal.periodogram(signal_with_noise, sr)

print("Mean spectral noise density = ",np.sqrt(np.mean(psd[50:])), "arb.u/SQRT(Hz)")

plt.plot(time, signal_with_noise)
plt.plot(time, signal_pure)
plt.xlabel("time (s)")
plt.ylabel("signal (arb.u.)")
plt.show()

plt.semilogy(f[1:], np.sqrt(psd[1:]))
plt.xlabel("frequency (Hz)")
plt.ylabel("psd (arb.u./SQRT(Hz))")
#plt.axvline(13, ls="dashed", color="g")
plt.axhline(rho, ls="dashed", color="r")
plt.show()

Signal with noise

PSD

What's the difference between HTML 'hidden' and 'aria-hidden' attributes?

setting aria-hidden to false and toggling it on element.show() worked for me.

e.g

<span aria-hidden="true">aria text</span>

$(span).attr('aria-hidden', 'false');
$(span).show();

and when hiding back

$(span).attr('aria-hidden', 'true');
$(span).hide();

Hibernate: ids for this class must be manually assigned before calling save()

your id attribute is not set. this MAY be due to the fact that the DB field is not set to auto increment? what DB are you using? MySQL? is your field set to AUTO INCREMENT?

How to sort Map values by key in Java?

Assuming TreeMap is not good for you (and assuming you can't use generics):

List sortedKeys=new ArrayList(yourMap.keySet());
Collections.sort(sortedKeys);
// Do what you need with sortedKeys.

#pragma mark in Swift?

In Objective-C code Xcode detects comments like // MARK: - foo which is a bit more portable than #pragma. But these do not seem to be picked up, too (yet?).

Edit: Fixed in Xcode 6 beta 4.

PHP Redirect with POST data

Here there is another approach that works for me:

if you need to redirect to another web page (user.php) and includes a PHP variable ($user[0]):

header('Location:./user.php?u_id='.$user[0]);

or

header("Location:./user.php?u_id=$user[0]");

The operation couldn’t be completed. (com.facebook.sdk error 2.) ios6

Another potential cause for this error: Attempting to get permission for a Facebook app in sandbox mode when the Facebook user is not listed in the app's admins, developers or testers.

Prevent flicker on webkit-transition of webkit-transform

The rule:

-webkit-backface-visibility: hidden;

will not work for sprites or image backgrounds.

body {-webkit-transform:translate3d(0,0,0);}

screws up backgrounds that are tiled.

I prefer to make a class called no-flick and do this:

.no-flick{-webkit-transform:translate3d(0,0,0);}

How do I download a binary file over HTTP?

The simplest way is the platform-specific solution:

 #!/usr/bin/env ruby
`wget http://somedomain.net/flv/sample/sample.flv`

Probably you are searching for:

require 'net/http'
# Must be somedomain.net instead of somedomain.net/, otherwise, it will throw exception.
Net::HTTP.start("somedomain.net") do |http|
    resp = http.get("/flv/sample/sample.flv")
    open("sample.flv", "wb") do |file|
        file.write(resp.body)
    end
end
puts "Done."

Edit: Changed. Thank You.

Edit2: The solution which saves part of a file while downloading:

# instead of http.get
f = open('sample.flv')
begin
    http.request_get('/sample.flv') do |resp|
        resp.read_body do |segment|
            f.write(segment)
        end
    end
ensure
    f.close()
end

(grep) Regex to match non-ASCII characters?

You don't really need a regex.

printf "%s\n" *[!\ -~]*

This will show file names with control characters in their names, too, but I consider that a feature.

If you don't have any matching files, the glob will expand to just itself, unless you have nullglob set. (The expression does not match itself, so technically, this output is unambiguous.)

What's the simplest way to list conflicted files in Git?

git diff --name-only --diff-filter=U

Is it possible to import a whole directory in sass using @import?

This feature will never be part of Sass. One major reason is import order. In CSS, the files imported last can override the styles stated before. If you import a directory, how can you determine import order? There's no way that doesn't introduce some new level of complexity. By keeping a list of imports (as you did in your example), you're being explicit with import order. This is essential if you want to be able to confidently override styles that are defined in another file or write mixins in one file and use them in another.

For a more thorough discussion, view this closed feature request here:

How do I indent multiple lines at once in Notepad++?

If you're using QuickText and like pressing Tab for it, you can otherwise change the indentation key.

Go Settings > Shortcup Mapper > Scintilla Command. Look at the number 10.

  • I changed 10 to : CTRL + ALT + RIGHT and
  • 11 to : CTRL+ ALT+ LEFT.

Now I think it's even better than the TABL / SHIFT + TAB as default.