Programs & Examples On #Embedded flashplayer

Scheduled run of stored procedure on SQL server

If MS SQL Server Express Edition is being used then SQL Server Agent is not available. I found the following worked for all editions:

USE Master
GO

IF  EXISTS( SELECT *
            FROM sys.objects
            WHERE object_id = OBJECT_ID(N'[dbo].[MyBackgroundTask]')
            AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[MyBackgroundTask]
GO

CREATE PROCEDURE MyBackgroundTask
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- The interval between cleanup attempts
    declare @timeToRun nvarchar(50)
    set @timeToRun = '03:33:33'

    while 1 = 1
    begin
        waitfor time @timeToRun
        begin
            execute [MyDatabaseName].[dbo].[MyDatabaseStoredProcedure];
        end
    end
END
GO

-- Run the procedure when the master database starts.
sp_procoption    @ProcName = 'MyBackgroundTask',
                @OptionName = 'startup',
                @OptionValue = 'on'
GO

Some notes:

ESLint - "window" is not defined. How to allow global variables in package.json

Your .eslintrc.json should contain the text below.
This way ESLint knows about your global variables.

{
  "env": {
    "browser": true,
    "node": true
  }                                                                      
}

Adding value to input field with jQuery

$.each(obj, function(index, value) {
    $('#looking_for_job_titles').tagsinput('add', value);
    console.log(value);
});

How to use (install) dblink in PostgreSQL?

Installing modules usually requires you to run an sql script that is included with the database installation.

Assuming linux-like OS

find / -name dblink.sql

Verify the location and run it

Should I use PATCH or PUT in my REST API?

One possible option to implement such behavior is

PUT /groups/api/v1/groups/{group id}/status
{
    "Status":"Activated"
}

And obviously, if someone need to deactivate it, PUT will have Deactivated status in JSON.

In case of necessity of mass activation/deactivation, PATCH can step into the game (not for exact group, but for groups resource:

PATCH /groups/api/v1/groups
{
    { “op”: “replace”, “path”: “/group1/status”, “value”: “Activated” },
    { “op”: “replace”, “path”: “/group7/status”, “value”: “Activated” },
    { “op”: “replace”, “path”: “/group9/status”, “value”: “Deactivated” }
}

In general this is idea as @Andrew Dobrowolski suggesting, but with slight changes in exact realization.

Keras, How to get the output of each layer?

You can easily get the outputs of any layer by using: model.layers[index].output

For all layers use this:

from keras import backend as K

inp = model.input                                           # input placeholder
outputs = [layer.output for layer in model.layers]          # all layer outputs
functors = [K.function([inp, K.learning_phase()], [out]) for out in outputs]    # evaluation functions

# Testing
test = np.random.random(input_shape)[np.newaxis,...]
layer_outs = [func([test, 1.]) for func in functors]
print layer_outs

Note: To simulate Dropout use learning_phase as 1. in layer_outs otherwise use 0.

Edit: (based on comments)

K.function creates theano/tensorflow tensor functions which is later used to get the output from the symbolic graph given the input.

Now K.learning_phase() is required as an input as many Keras layers like Dropout/Batchnomalization depend on it to change behavior during training and test time.

So if you remove the dropout layer in your code you can simply use:

from keras import backend as K

inp = model.input                                           # input placeholder
outputs = [layer.output for layer in model.layers]          # all layer outputs
functors = [K.function([inp], [out]) for out in outputs]    # evaluation functions

# Testing
test = np.random.random(input_shape)[np.newaxis,...]
layer_outs = [func([test]) for func in functors]
print layer_outs

Edit 2: More optimized

I just realized that the previous answer is not that optimized as for each function evaluation the data will be transferred CPU->GPU memory and also the tensor calculations needs to be done for the lower layers over-n-over.

Instead this is a much better way as you don't need multiple functions but a single function giving you the list of all outputs:

from keras import backend as K

inp = model.input                                           # input placeholder
outputs = [layer.output for layer in model.layers]          # all layer outputs
functor = K.function([inp, K.learning_phase()], outputs )   # evaluation function

# Testing
test = np.random.random(input_shape)[np.newaxis,...]
layer_outs = functor([test, 1.])
print layer_outs

How to insert the current timestamp into MySQL database using a PHP insert query

Your usage of now() is correct. However, you need to use one type of quotes around the entire query and another around the values.

You can modify your query to use double quotes at the beginning and end, and single quotes around $somename:

$update_query = "UPDATE db.tablename SET insert_time=now() WHERE username='$somename'";

How to explain callbacks in plain english? How are they different from calling one function from another function?

Imagine you need a function that returns 10 squared so you write a function:

function tenSquared() {return 10*10;}

Later you need 9 squared so you write another function:

function nineSquared() {return 9*9;}

Eventually you will replace all of these with a generic function:

function square(x) {return x*x;}

The exact same thinking applies for callbacks. You have a function that does something and when done calls doA:

function computeA(){
    ...
    doA(result);
}

Later you want the exact same function to call doB instead you could duplicate the whole function:

function computeB(){
    ...
    doB(result);
}

Or you could pass a callback function as a variable and only have to have the function once:

function compute(callback){
    ...
    callback(result);
}

Then you just have to call compute(doA) and compute(doB).

Beyond simplifying code, it lets asynchronous code let you know it has completed by calling your arbitrary function on completion, similar to when you call someone on the phone and leave a callback number.

Super-simple example of C# observer/observable with delegates

    /**********************Simple Example ***********************/    

class Program
        {
            static void Main(string[] args)
            {
                Parent p = new Parent();
            }
        }

        ////////////////////////////////////////////

        public delegate void DelegateName(string data);

        class Child
        {
            public event DelegateName delegateName;

            public void call()
            {
                delegateName("Narottam");
            }
        }

        ///////////////////////////////////////////

        class Parent
        {
            public Parent()
            {
                Child c = new Child();
                c.delegateName += new DelegateName(print);
                //or like this
                //c.delegateName += print;
                c.call();
            }

            public void print(string name)
            {
                Console.WriteLine("yes we got the name : " + name);
            }
        }

Setting href attribute at runtime

To get or set an attribute of an HTML element, you can use the element.attr() function in jQuery.

To get the href attribute, use the following code:

var a_href = $('selector').attr('href');

To set the href attribute, use the following code:

$('selector').attr('href','http://example.com');

In both cases, please use the appropriate selector. If you have set the class for the anchor element, use '.class-name' and if you have set the id for the anchor element, use '#element-id'.

How to track down a "double free or corruption" error

If you're using glibc, you can set the MALLOC_CHECK_ environment variable to 2, this will cause glibc to use an error tolerant version of malloc, which will cause your program to abort at the point where the double free is done.

You can set this from gdb by using the set environment MALLOC_CHECK_ 2 command before running your program; the program should abort, with the free() call visible in the backtrace.

see the man page for malloc() for more information

Android ImageView Zoom-in and Zoom-Out

Please follow the below class, that is used for Zoom in and Zoom Out for ImageView.

import android.app.Activity;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;

public class ZoomInZoomOut extends Activity implements OnTouchListener 
{
    private static final String TAG = "Touch";
    @SuppressWarnings("unused")
    private static final float MIN_ZOOM = 1f,MAX_ZOOM = 1f;

    // These matrices will be used to scale points of the image
    Matrix matrix = new Matrix();
    Matrix savedMatrix = new Matrix();

    // The 3 states (events) which the user is trying to perform
    static final int NONE = 0;
    static final int DRAG = 1;
    static final int ZOOM = 2;
    int mode = NONE;

    // these PointF objects are used to record the point(s) the user is touching
    PointF start = new PointF();
    PointF mid = new PointF();
    float oldDist = 1f;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ImageView view = (ImageView) findViewById(R.id.imageView);
        view.setOnTouchListener(this);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) 
    {
        ImageView view = (ImageView) v;
        view.setScaleType(ImageView.ScaleType.MATRIX);
        float scale;

        dumpEvent(event);
        // Handle touch events here...

        switch (event.getAction() & MotionEvent.ACTION_MASK) 
        {
            case MotionEvent.ACTION_DOWN:   // first finger down only
                                                savedMatrix.set(matrix);
                                                start.set(event.getX(), event.getY());
                                                Log.d(TAG, "mode=DRAG"); // write to LogCat
                                                mode = DRAG;
                                                break;

            case MotionEvent.ACTION_UP: // first finger lifted

            case MotionEvent.ACTION_POINTER_UP: // second finger lifted

                                                mode = NONE;
                                                Log.d(TAG, "mode=NONE");
                                                break;

            case MotionEvent.ACTION_POINTER_DOWN: // first and second finger down

                                                oldDist = spacing(event);
                                                Log.d(TAG, "oldDist=" + oldDist);
                                                if (oldDist > 5f) {
                                                    savedMatrix.set(matrix);
                                                    midPoint(mid, event);
                                                    mode = ZOOM;
                                                    Log.d(TAG, "mode=ZOOM");
                                                }
                                                break;

            case MotionEvent.ACTION_MOVE:

                                                if (mode == DRAG) 
                                                { 
                                                    matrix.set(savedMatrix);
                                                    matrix.postTranslate(event.getX() - start.x, event.getY() - start.y); // create the transformation in the matrix  of points
                                                } 
                                                else if (mode == ZOOM) 
                                                { 
                                                    // pinch zooming
                                                    float newDist = spacing(event);
                                                    Log.d(TAG, "newDist=" + newDist);
                                                    if (newDist > 5f) 
                                                    {
                                                        matrix.set(savedMatrix);
                                                        scale = newDist / oldDist; // setting the scaling of the
                                                                                    // matrix...if scale > 1 means
                                                                                    // zoom in...if scale < 1 means
                                                                                    // zoom out
                                                        matrix.postScale(scale, scale, mid.x, mid.y);
                                                    }
                                                }
                                                break;
        }

        view.setImageMatrix(matrix); // display the transformation on screen

        return true; // indicate event was handled
    }

    /*
     * --------------------------------------------------------------------------
     * Method: spacing Parameters: MotionEvent Returns: float Description:
     * checks the spacing between the two fingers on touch
     * ----------------------------------------------------
     */

    private float spacing(MotionEvent event) 
    {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return (float) Math.sqrt(x * x + y * y);
    }

    /*
     * --------------------------------------------------------------------------
     * Method: midPoint Parameters: PointF object, MotionEvent Returns: void
     * Description: calculates the midpoint between the two fingers
     * ------------------------------------------------------------
     */

    private void midPoint(PointF point, MotionEvent event) 
    {
        float x = event.getX(0) + event.getX(1);
        float y = event.getY(0) + event.getY(1);
        point.set(x / 2, y / 2);
    }

    /** Show an event in the LogCat view, for debugging */
    private void dumpEvent(MotionEvent event) 
    {
        String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE","POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
        StringBuilder sb = new StringBuilder();
        int action = event.getAction();
        int actionCode = action & MotionEvent.ACTION_MASK;
        sb.append("event ACTION_").append(names[actionCode]);

        if (actionCode == MotionEvent.ACTION_POINTER_DOWN || actionCode == MotionEvent.ACTION_POINTER_UP) 
        {
            sb.append("(pid ").append(action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
            sb.append(")");
        }

        sb.append("[");
        for (int i = 0; i < event.getPointerCount(); i++) 
        {
            sb.append("#").append(i);
            sb.append("(pid ").append(event.getPointerId(i));
            sb.append(")=").append((int) event.getX(i));
            sb.append(",").append((int) event.getY(i));
            if (i + 1 < event.getPointerCount())
                sb.append(";");
        }

        sb.append("]");
        Log.d("Touch Events ---------", sb.toString());
    }
}

Circular dependency in Spring

If you generally use constructor-injection and don't want to switch to property-injection then Spring's lookup-method-injection will let one bean lazily lookup the other and hence workaround the cyclic dependency. See here: http://docs.spring.io/spring/docs/1.2.9/reference/beans.html#d0e1161

strdup() - what does it do in C?

The most valuable thing it does is give you another string identical to the first, without requiring you to allocate memory (location and size) yourself. But, as noted, you still need to free it (but which doesn't require a quantity calculation, either.)

If Radio Button is selected, perform validation on Checkboxes

You need to use == or === for comparison. = assigns a new value.

Besides that, using == is pointless when dealing with booleans only. Just use if(foo) instead of if(foo == true).

VBA procedure to import csv file into access

Your file seems quite small (297 lines) so you can read and write them quite quickly. You refer to Excel CSV, which does not exists, and you show space delimited data in your example. Furthermore, Access is limited to 255 columns, and a CSV is not, so there is no guarantee this will work

Sub StripHeaderAndFooter()
Dim fs As Object ''FileSystemObject
Dim tsIn As Object, tsOut As Object ''TextStream
Dim sFileIn As String, sFileOut As String
Dim aryFile As Variant

    sFileIn = "z:\docs\FileName.csv"
    sFileOut = "z:\docs\FileOut.csv"

    Set fs = CreateObject("Scripting.FileSystemObject")
    Set tsIn = fs.OpenTextFile(sFileIn, 1) ''ForReading

    sTmp = tsIn.ReadAll

    Set tsOut = fs.CreateTextFile(sFileOut, True) ''Overwrite
    aryFile = Split(sTmp, vbCrLf)

    ''Start at line 3 and end at last line -1
    For i = 3 To UBound(aryFile) - 1
        tsOut.WriteLine aryFile(i)
    Next

    tsOut.Close

    DoCmd.TransferText acImportDelim, , "NewCSV", sFileOut, False
End Sub

Edit re various comments

It is possible to import a text file manually into MS Access and this will allow you to choose you own cell delimiters and text delimiters. You need to choose External data from the menu, select your file and step through the wizard.

About importing and linking data and database objects -- Applies to: Microsoft Office Access 2003

Introduction to importing and exporting data -- Applies to: Microsoft Access 2010

Once you get the import working using the wizards, you can save an import specification and use it for you next DoCmd.TransferText as outlined by @Olivier Jacot-Descombes. This will allow you to have non-standard delimiters such as semi colon and single-quoted text.

Add padding on view programmatically

Using Kotlin and the android-ktx library, you can simply do

view.updatePadding(top = 42)

See docs here

Batch files : How to leave the console window open

put at the end it will reopen your console

start cmd 

Use of for_each on map elements

It's unfortunate that you don't have Boost however if your STL implementation has the extensions then you can compose mem_fun_ref and select2nd to create a single functor suitable for use with for_each. The code would look something like this:

#include <algorithm>
#include <map>
#include <ext/functional>   // GNU-specific extension for functor classes missing from standard STL

using namespace __gnu_cxx;  // for compose1 and select2nd

class MyClass
{
public:
    void Method() const;
};

std::map<int, MyClass> Map;

int main(void)
{
    std::for_each(Map.begin(), Map.end(), compose1(std::mem_fun_ref(&MyClass::Method), select2nd<std::map<int, MyClass>::value_type>()));
}

Note that if you don't have access to compose1 (or the unary_compose template) and select2nd, they are fairly easy to write.

Http Get using Android HttpURLConnection

A more contemporary way of doing it on a separate thread using Tasks and Kotlin

private val mExecutor: Executor = Executors.newSingleThreadExecutor()

private fun createHttpTask(u:String): Task<String> {
    return Tasks.call(mExecutor, Callable<String>{
        val url = URL(u)
        val conn: HttpURLConnection = url.openConnection() as HttpURLConnection
        conn.requestMethod = "GET"
        conn.connectTimeout = 3000
        conn.readTimeout = 3000
        val rc = conn.responseCode
        if ( rc != HttpURLConnection.HTTP_OK) {
            throw java.lang.Exception("Error: ${rc}")
        }
        val inp: InputStream = BufferedInputStream(conn.inputStream)
        val resp: String = inp.bufferedReader(UTF_8).use{ it.readText() }
        return@Callable resp
    })
}

and now you can use it like below in many places:

            createHttpTask("https://google.com")
                    .addOnSuccessListener {
                        Log.d("HTTP", "Response: ${it}") // 'it' is a response string here
                    }
                    .addOnFailureListener {
                        Log.d("HTTP", "Error: ${it.message}") // 'it' is an Exception object here
                    }

Download & Install Xcode version without Premium Developer Account

I am able to download it using apple's download website today. https://developer.apple.com/download/

I do not have a paid apple developer account. Before I was only able to see xcode 8.3.3 but somehow today xcode 9 beta also appeared.

Deleting an SVN branch

Command to delete a branch is as follows:

svn delete -m "<your message>" <branch url>

If you wish to not fetch/checkout the entire repo, execute the following command on your terminal:

1) get the absolute path of the directory that will contain your working copy
> pwd
2) Start svn code checkout
> svn checkout <branch url> <absolute path from point 1>

The above steps will get you the files inside the branch folder and not the entire folder.

TCP vs UDP on video stream

If the bandwidth is far higher than the bitrate, I would recommend TCP for unicast live video streaming.

Case 1: Consecutive packets are lost for a duration of several seconds. => live video will stop on the client side whatever the transport layer is (TCP or UDP). When the network recovers: - if TCP is used, client video player can choose to restart the stream at the first packet lost (timeshift) OR to drop all late packets and to restart the video stream with no timeshift. - if UDP is used, there is no choice on the client side, video restart live without any timeshift. => TCP equal or better.

Case 2: some packets are randomly and often lost on the network. - if TCP is used, these packets will be immediately retransmitted and with a correct jitter buffer, there will be no impact on the video stream quality/latency. - if UDP is used, video quality will be poor. => TCP much better

Using BigDecimal to work with currencies

I would recommend a little research on Money Pattern. Martin Fowler in his book Analysis pattern has covered this in more detail.

public class Money {

    private static final Currency USD = Currency.getInstance("USD");
    private static final RoundingMode DEFAULT_ROUNDING = RoundingMode.HALF_EVEN;

    private final BigDecimal amount;
    private final Currency currency;   

    public static Money dollars(BigDecimal amount) {
        return new Money(amount, USD);
    }

    Money(BigDecimal amount, Currency currency) {
        this(amount, currency, DEFAULT_ROUNDING);
    }

    Money(BigDecimal amount, Currency currency, RoundingMode rounding) {
        this.currency = currency;      
        this.amount = amount.setScale(currency.getDefaultFractionDigits(), rounding);
    }

    public BigDecimal getAmount() {
        return amount;
    }

    public Currency getCurrency() {
        return currency;
    }

    @Override
    public String toString() {
        return getCurrency().getSymbol() + " " + getAmount();
    }

    public String toString(Locale locale) {
        return getCurrency().getSymbol(locale) + " " + getAmount();
    }   
}

Coming to the usage:

You would represent all monies using Money object as opposed to BigDecimal. Representing money as big decimal will mean that you will have the to format the money every where you display it. Just imagine if the display standard changes. You will have to make the edits all over the place. Instead using the Money pattern you centralize the formatting of money to a single location.

Money price = Money.dollars(38.28);
System.out.println(price);

Find duplicate characters in a String and count the number of occurances using Java

 void Findrepeter(){
    String s="mmababctamantlslmag";
    int distinct = 0 ;

    for (int i = 0; i < s.length(); i++) {

        for (int j = 0; j < s.length(); j++) {

            if(s.charAt(i)==s.charAt(j))
            {
                distinct++;

            }
        }   
        System.out.println(s.charAt(i)+"--"+distinct);
        String d=String.valueOf(s.charAt(i)).trim();
        s=s.replaceAll(d,"");
        distinct = 0;

    }

}

gpg decryption fails with no secret key error

Following this procedure worked for me.

To create gpg key. gpg --gen-key --homedir /etc/salt/gpgkeys

export the public key, secret key, and secret subkey.

gpg --homedir /etc/salt/gpgkeys --export test-key > pub.key
gpg --homedir /etc/salt/gpgkeys --export-secret-keys test-key > sec.key
gpg --homedir /etc/salt/gpgkeys --export-secret-subkeys test-key > sub.key

Now import the keys using the following command.

gpg --import pub.key
gpg --import sec.key
gpg --import sub.key

Verify if the keys are imported.

gpg --list-keys
gpg --list-secret-keys

Create a sample file.

echo "hahaha" > a.txt

Encrypt the file using the imported key

gpg --encrypt --sign --armor -r test-key a.txt

To decrypt the file, use the following command.

gpg --decrypt a.txt.asc

Specifying content of an iframe instead of the src attribute to a page

In combination with what Guffa described, you could use the technique described in Explanation of <script type = "text/template"> ... </script> to store the HTML document in a special script element (see the link for an explanation on how this works). That's a lot easier than storing the HTML document in a string.

SQL query to make all data in a column UPPER CASE?

Permanent:

UPDATE
  MyTable
SET
  MyColumn = UPPER(MyColumn)

Temporary:

SELECT
  UPPER(MyColumn) AS MyColumn
FROM
  MyTable

Maven dependency update on commandline

Simple run your project online i.e mvn clean install . It fetches all the latest dependencies that you mention in your pom.xml and built the project

How to convert JSON string into List of Java object?

StudentList studentList = mapper.readValue(jsonString,StudentList.class);

Change this to this one

StudentList studentList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});

Selenium Finding elements by class name in python

Use nth-child, for example: http://www.w3schools.com/cssref/sel_nth-child.asp

driver.find_element(By.CSS_SELECTOR, 'p.content:nth-child(1)')

or http://www.w3schools.com/cssref/sel_firstchild.asp

driver.find_element(By.CSS_SELECTOR, 'p.content:first-child')

How to determine if a type implements an interface with C# reflection

Note that if you have a generic interface IMyInterface<T> then this will always return false:

  typeof(IMyInterface<>).IsAssignableFrom(typeof(MyType)) /* ALWAYS FALSE */

This doesn't work either:

  typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface<>))  /* ALWAYS FALSE */

However, if MyType implements IMyInterface<MyType> this works and returns true:

  typeof(IMyInterface<MyType>).IsAssignableFrom(typeof(MyType))

However, you likely will not know the type parameter T at runtime. A somewhat hacky solution is:

  typeof(MyType).GetInterfaces()
                .Any(x=>x.Name == typeof(IMyInterface<>).Name)

Jeff's solution is a bit less hacky:

  typeof(MyType).GetInterfaces()
         .Any(i => i.IsGenericType 
             && i.GetGenericTypeDefinition() == typeof(IMyInterface<>));

Here's a extension method on Type that works for any case:

public static class TypeExtensions
{
    public static bool IsImplementing(this Type type, Type someInterface)
    {
        return type.GetInterfaces()
             .Any(i => i == someInterface 
                 || i.IsGenericType 
                    && i.GetGenericTypeDefinition() == someInterface);
    }
}

(Note that the above uses linq, which is probably slower than a loop.)

You can then do:

   typeof(MyType).IsImplementing(IMyInterface<>)

Replace new lines with a comma delimiter with Notepad++?

For Notepad++ 5.9

  1. Press Ctrl+H
  2. Select Search mode Extended(\n, \r, \t, \o, \x...)
  3. Enter Find what: \r\n
  4. Enter Replace with: ,
  5. Replace_All should get the required result.

Select multiple images from android gallery

The EXTRA_ALLOW_MULTIPLE option is set on the intent through the Intent.putExtra() method:

intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);

Your code above should look like this:

Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), 1);

Note: the EXTRA_ALLOW_MULTIPLE option is only available in Android API 18 and higher.

How to time Java program execution speed

You can make use of System#nanoTime(). Get it before and after the execution and just do the math. It's preferred above System#currentTimeMillis() because it has a better precision. Depending on the hardware and the platform used, you may otherwise get an incorrect gap in elapsed time. Here with Core2Duo on Windows, between about 0 and ~15ms actually nothing can be calculated.

A more advanced tool is a profiler.

IntelliJ does not show 'Class' when we right click and select 'New'

The directory or one of the parent directories must be marked as Source Root (In this case, it appears in blue).

If this is not the case, right click your root source directory -> Mark As -> Source Root.

How to open the Google Play Store directly from my Android application?

Kotlin

fun openAppInPlayStore(appPackageName: String) {
    try {
        startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$appPackageName")))
    } catch (exception: android.content.ActivityNotFoundException) {
        startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=$appPackageName")))
    }
}

Generate preview image from Video file?

Two ways come to mind:

  • Using a command-line tool like the popular ffmpeg, however you will almost always need an own server (or a very nice server administrator / hosting company) to get that

  • Using the "screenshoot" plugin for the LongTail Video player that allows the creation of manual screenshots that are then sent to a server-side script.

PHP array: count or sizeof?

Please use count function, Here is a example how to count array in a element

$cars = array("Volvo","BMW","Toyota");
echo count($cars);

The count() function returns the number of elements in an array.

The sizeof() function returns the number of elements in an array.

The sizeof() function is an alias of the count() function.

Exception: "URI formats are not supported"

I solved the same error with the Path.Combine(MapPath()) to get the physical file path instead of the http:/// www one.

Java socket API: How to tell if a connection has been closed?

Here you are another general solution for any data type.

int offset = 0;
byte[] buffer = new byte[8192];

try {
    do {
        int b = inputStream.read();

        if (b == -1)
           break;

        buffer[offset++] = (byte) b;

        //check offset with buffer length and reallocate array if needed
    } while (inputStream.available() > 0);
} catch (SocketException e) {
    //connection was lost
}

//process buffer

jquery AJAX and json format

Currently you are sending the data as typical POST values, which look like this:

first_name=somename&last_name=somesurname

If you want to send data as json you need to create an object with data and stringify it.

data: JSON.stringify(someobject)

Converting String array to java.util.List

The Simplest approach:

String[] stringArray = {"Hey", "Hi", "Hello"};

List<String> list = Arrays.asList(stringArray);

How to delete the first row of a dataframe in R?

I am not expert, but this may work as well,

dat <- dat[2:nrow(dat), ]

How many spaces will Java String.trim() remove?

When in doubt, write a unit test:

@Test
public void trimRemoveAllBlanks(){
    assertThat("    content   ".trim(), is("content"));
}

NB: of course the test (for JUnit + Hamcrest) doesn't fail

Django: save() vs update() to update the database?

Using update directly is more efficient and could also prevent integrity problems.

From the official documentation https://docs.djangoproject.com/en/3.0/ref/models/querysets/#django.db.models.query.QuerySet.update

If you’re just updating a record and don’t need to do anything with the model object, the most efficient approach is to call update(), rather than loading the model object into memory. For example, instead of doing this:

e = Entry.objects.get(id=10)
e.comments_on = False
e.save()

…do this:

Entry.objects.filter(id=10).update(comments_on=False)

Using update() also prevents a race condition wherein something might change in your database in the short period of time between loading the object and calling save().

Set environment variables on Mac OS X Lion

First, one thing to recognize about OS X is that it is built on Unix. This is where the .bash_profile comes in. When you start the Terminal app in OS X you get a bash shell by default. The bash shell comes from Unix and when it loads it runs the .bash_profile script. You can modify this script for your user to change your settings. This file is located at:

~/.bash_profile

Update for Mavericks

OS X Mavericks does not use the environment.plist - at least not for OS X windows applications. You can use the launchd configuration for windowed applications. The .bash_profile is still supported since that is part of the bash shell used in Terminal.

Lion and Mountain Lion Only

OS X windowed applications receive environment variables from the your environment.plist file. This is likely what you mean by the ".plist" file. This file is located at:

~/.MacOSX/environment.plist

If you make a change to your environment.plist file then OS X windows applications, including the Terminal app, will have those environment variables set. Any environment variable you set in your .bash_profile will only affect your bash shells.

Generally I only set variables in my .bash_profile file and don't change the .plist file (or launchd file on Mavericks). Most OS X windowed applications don't need any custom environment. Only when an application actually needs a specific environment variable do I change the environment.plist (or launchd file on Mavericks).

It sounds like what you want is to change the environment.plist file, rather than the .bash_profile.

One last thing, if you look for those files, I think you will not find them. If I recall correctly, they were not on my initial install of Lion.

Edit: Here are some instructions for creating a plist file.

  1. Open Xcode
  2. Select File -> New -> New File...
  3. Under Mac OS X select Resources
  4. Choose a plist file
  5. Follow the rest of the prompts

To edit the file, you can Control-click to get a menu and select Add Row. You then can add a key value pair. For environment variables, the key is the environment variable name and the value is the actual value for that environment variable.

Once the plist file is created you can open it with Xcode to modify it anytime you wish.

Where should my npm modules be installed on Mac OS X?

/usr/local/lib/node_modules is the correct directory for globally installed node modules.

/usr/local/share/npm/lib/node_modules makes no sense to me. One issue here is that you're confused because there are two directories called node_modules:

/usr/local/lib/node_modules
/usr/local/lib/node_modules/npm/node_modules

The latter seems to be node modules that came with Node, e.g., lodash, when the former is Node modules that I installed using npm.

How can I Convert HTML to Text in C#?

I have used Detagger in the past. It does a pretty good job of formatting the HTML as text and is more than just a tag remover.

Class JavaLaunchHelper is implemented in both. One of the two will be used. Which one is undefined

From what I've found online, this is a bug introduced in JDK 1.7.0_45. It appears to also be present in JDK 1.7.0_60. A bug report on Oracle's website states that, while there was a fix, it was removed before the JDK was released. I do not know why the fix was removed, but it confirms what we've already suspected -- the JDK is still broken.

The bug report claims that the error is benign and should not cause any run-time problems, though one of the comments disagrees with that. In my own experience, I have been able to work without any problems using JDK 1.7.0_60 despite seeing the message.

If this issue is causing serious problems, here are a few things I would suggest:

  • Revert back to JDK 1.7.0_25 until a fix is added to the JDK.

  • Keep an eye on the bug report so that you are aware of any work being done on this issue. Maybe even add your own comment so Oracle is aware of the severity of the issue.

  • Try the JDK early releases as they come out. One of them might fix your problem.

Instructions for installing the JDK on Mac OS X are available at JDK 7 Installation for Mac OS X. It also contains instructions for removing the JDK.

How to build an android library with Android Studio and gradle?

Gradle Build Tools 2.2.0+ - Everything just works

This is the correct way to do it

In trying to avoid experimental and frankly fed up with the NDK and all its hackery I am happy that 2.2.x of the Gradle Build Tools came out and now it just works. The key is the externalNativeBuild and pointing ndkBuild path argument at an Android.mk or change ndkBuild to cmake and point the path argument at a CMakeLists.txt build script.

android {
    compileSdkVersion 19
    buildToolsVersion "25.0.2"

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 19

        ndk {
            abiFilters 'armeabi', 'armeabi-v7a', 'x86'
        }

        externalNativeBuild {
            cmake {
                cppFlags '-std=c++11'
                arguments '-DANDROID_TOOLCHAIN=clang',
                        '-DANDROID_PLATFORM=android-19',
                        '-DANDROID_STL=gnustl_static',
                        '-DANDROID_ARM_NEON=TRUE',
                        '-DANDROID_CPP_FEATURES=exceptions rtti'
            }
        }
    }

    externalNativeBuild {
        cmake {
             path 'src/main/jni/CMakeLists.txt'
        }
        //ndkBuild {
        //   path 'src/main/jni/Android.mk'
        //}
    }
}

For much more detail check Google's page on adding native code.

After this is setup correctly you can ./gradlew installDebug and off you go. You will also need to be aware that the NDK is moving to clang since gcc is now deprecated in the Android NDK.

in linux terminal, how do I show the folder's last modification date, taking its content into consideration?

If you have a version of find (such as GNU find) that supports -printf then there's no need to call stat repeatedly:

find /some/dir -printf "%T+\n" | sort -nr | head -n 1

or

find /some/dir -printf "%TY-%Tm-%Td %TT\n" | sort -nr | head -n 1

If you don't need recursion, though:

stat --printf="%y\n" *

How can you encode a string to Base64 in JavaScript?

You can use btoa (to base-64) and atob (from base-64).

For IE 9 and below, try the jquery-base64 plugin:

$.base64.encode("this is a test");
$.base64.decode("dGhpcyBpcyBhIHRlc3Q=");

How to use ADB Shell when Multiple Devices are connected? Fails with "error: more than one device and emulator"

The best way to run shell on any particular device is to use:

adb -s << emulator UDID >> shell

For Example:
adb -s emulator-5554 shell

How to convert a double to long without casting?

Simply put, casting is more efficient than creating a Double object.

How to upload a project to Github

git push --force origin master

if you have problems uploading!

JavaFX 2.1 TableView refresh items

?????????TableColumn?visable???????databinding???,???JavaFX?bug????????,?????Java8??????

??trace JavaFX ?source code?,?????bug???Listener????????????????JFace??PropertyChangeSupport????POJO?????????????DoubleProperty ??WritableObjectValue,???????

                                                           ???????

I had firmed use change Column Visable Property is not conform data binding automation purpose.

After I traced JavaFX TableView source code. I never discovered any problem code for Tableview binding issue. After 4 weeks ago, I changed POJO field's type from DoubleProperty to WritableObjectValue, problem was solved.

                                               resolve in Taiwan Taipei.

Sample code:

public class CostAnalytics{
protected WritableObjectValue<Double> subtotal=new SimpleObjectProperty<Double>();//??WritableObjectValue????????,???????Column??setVisable(false)?setVisable(true)
//...
public void setQuantity(double quantity) {
    this.pcs.firePropertyChange("quantity", this.quantity, quantity);
    this.quantity.set(quantity);
    this.calsSubtotal();
}
public WritableObjectValue<Double> getSubtotal() {//??WritableObjectValue????????,???????Column??setVisable(false)?setVisable(true)
    return subtotal;
}
///...
}


TableColumn<CostAnalytics, Double> subtotal = new TableColumn<CostAnalytics, Double>(
            "??");
subtotal.setCellValueFactory(new Callback<CellDataFeatures<CostAnalytics, Double>, ObservableValue<Double>>() {

        public ObservableValue<Double> call(
                CellDataFeatures<CostAnalytics, Double> p) {
            WritableObjectValue<Double> result = p.getValue().getSubtotal();// //??WritableObjectValue????????,???????Column??setVisable(false)?setVisable(true)
            // return (ObservableValue<Double>)
            // result;//??WritableObjectValue????????,???????Column??setVisable(false)?setVisable(true)
            // return new
            // ReadOnlyObjectWrapper<Double>(p.getValue().getSubtotal());//????????
            return (ObservableValue<Double>) p.getValue().getSubtotal();// ??WritableObjectValue????????,???????Column??setVisable(false)?setVisable(true)
        }

    });

How can I add an element after another element?

try

.insertAfter()

here

$(content).insertAfter('#bla');

Finding moving average from data points in Python

I think something like:

aves = [sum(data[i:i+6]) for i in range(0, len(data), 5)]

But I always have to double check the indices are doing what I expect. The range you want is (0, 5, 10, ...) and data[0:6] will give you data[0]...data[5]

ETA: oops, and you want ave rather than sum, of course. So actually using your code and the formula:

r = 5
x = data[:,0]
y1 = data[:,1]
y2 = [ave(y1[i-r:i+r]) for i in range(r, len(y1), 2*r)]
y = [y1, y2]

Adding the "Clear" Button to an iPhone UITextField

On Xcode 8 (8A218a):

Swift:

textField.clearButtonMode = UITextField.ViewMode.whileEditing;

The "W" went from capital to non-cap "w".

LDAP Authentication using Java

// this class will authenticate LDAP UserName or Email

// simply call LdapAuth.authenticateUserAndGetInfo (username,password);

//Note: Configure ldapURI ,requiredAttributes ,ADSearchPaths,accountSuffex 

import java.util.*;

import javax.naming.*;

import java.util.regex.*;

import javax.naming.directory.*;

import javax.naming.ldap.InitialLdapContext;

import javax.naming.ldap.LdapContext;

public class LdapAuth {


private final static String ldapURI = "ldap://20.200.200.200:389/DC=corp,DC=local";

private final static String contextFactory = "com.sun.jndi.ldap.LdapCtxFactory";

private  static String[] requiredAttributes = {"cn","givenName","sn","displayName","userPrincipalName","sAMAccountName","objectSid","userAccountControl"};


// see you active directory user OU's hirarchy 

private  static String[] ADSearchPaths = 

{ 

    "OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=In-House,OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=Torbram Users,OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=Migrated Users,OU=TES-Users"

};


private static String accountSuffex = "@corp.local"; // this will be used if user name is just provided


private static void authenticateUserAndGetInfo (String user, String password) throws Exception {

    try {


        Hashtable<String,String> env = new Hashtable <String,String>();

        env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);

        env.put(Context.PROVIDER_URL, ldapURI);     

        env.put(Context.SECURITY_AUTHENTICATION, "simple");

        env.put(Context.SECURITY_PRINCIPAL, user);

        env.put(Context.SECURITY_CREDENTIALS, password);

        DirContext ctx = new InitialDirContext(env);

        String filter = "(sAMAccountName="+user+")";  // default for search filter username

        if(user.contains("@"))  // if user name is a email then
        {
            //String parts[] = user.split("\\@");
            //use different filter for email
            filter = "(userPrincipalName="+user+")";
        }

        SearchControls ctrl = new SearchControls();
        ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ctrl.setReturningAttributes(requiredAttributes);

        NamingEnumeration userInfo = null;


        Integer i = 0;
        do
        {
            userInfo = ctx.search(ADSearchPaths[i], filter, ctrl);
            i++;

        } while(!userInfo.hasMore() && i < ADSearchPaths.length );

        if (userInfo.hasMore()) {

            SearchResult UserDetails = (SearchResult) userInfo.next();
            Attributes userAttr = UserDetails.getAttributes();System.out.println("adEmail = "+userAttr.get("userPrincipalName").get(0).toString());

            System.out.println("adFirstName = "+userAttr.get("givenName").get(0).toString());

            System.out.println("adLastName = "+userAttr.get("sn").get(0).toString());

            System.out.println("name = "+userAttr.get("cn").get(0).toString());

            System.out.println("AdFullName = "+userAttr.get("cn").get(0).toString());

        }

        userInfo.close();

    }
    catch (javax.naming.AuthenticationException e) {

    }
}   
}

Handling very large numbers in Python

You could do this for the fun of it, but other than that it's not a good idea. It would not speed up anything I can think of.

  • Getting the cards in a hand will be an integer factoring operation which is much more expensive than just accessing an array.

  • Adding cards would be multiplication, and removing cards division, both of large multi-word numbers, which are more expensive operations than adding or removing elements from lists.

  • The actual numeric value of a hand will tell you nothing. You will need to factor the primes and follow the Poker rules to compare two hands. h1 < h2 for such hands means nothing.

What is std::move(), and when should it be used?

Q: What is std::move?

A: std::move() is a function from the C++ Standard Library for casting to a rvalue reference.

Simplisticly std::move(t) is equivalent to:

static_cast<T&&>(t);

An rvalue is a temporary that does not persist beyond the expression that defines it, such as an intermediate function result which is never stored in a variable.

int a = 3; // 3 is a rvalue, does not exist after expression is evaluated
int b = a; // a is a lvalue, keeps existing after expression is evaluated

An implementation for std::move() is given in N2027: "A Brief Introduction to Rvalue References" as follows:

template <class T>
typename remove_reference<T>::type&&
std::move(T&& a)
{
    return a;
}

As you can see, std::move returns T&& no matter if called with a value (T), reference type (T&), or rvalue reference (T&&).

Q: What does it do?

A: As a cast, it does not do anything during runtime. It is only relevant at compile time to tell the compiler that you would like to continue considering the reference as an rvalue.

foo(3 * 5); // obviously, you are calling foo with a temporary (rvalue)

int a = 3 * 5;
foo(a);     // how to tell the compiler to treat `a` as an rvalue?
foo(std::move(a)); // will call `foo(int&& a)` rather than `foo(int a)` or `foo(int& a)`

What it does not do:

  • Make a copy of the argument
  • Call the copy constructor
  • Change the argument object

Q: When should it be used?

A: You should use std::move if you want to call functions that support move semantics with an argument which is not an rvalue (temporary expression).

This begs the following follow-up questions for me:

  • What is move semantics? Move semantics in contrast to copy semantics is a programming technique in which the members of an object are initialized by 'taking over' instead of copying another object's members. Such 'take over' makes only sense with pointers and resource handles, which can be cheaply transferred by copying the pointer or integer handle rather than the underlying data.

  • What kind of classes and objects support move semantics? It is up to you as a developer to implement move semantics in your own classes if these would benefit from transferring their members instead of copying them. Once you implement move semantics, you will directly benefit from work from many library programmers who have added support for handling classes with move semantics efficiently.

  • Why can't the compiler figure it out on its own? The compiler cannot just call another overload of a function unless you say so. You must help the compiler choose whether the regular or move version of the function should be called.

  • In which situations would I want to tell the compiler that it should treat a variable as an rvalue? This will most likely happen in template or library functions, where you know that an intermediate result could be salvaged.

Concatenating strings in C, which method is more efficient?

sprintf() is designed to handle far more than just strings, strcat() is specialist. But I suspect that you are sweating the small stuff. C strings are fundamentally inefficient in ways that make the differences between these two proposed methods insignificant. Read "Back to Basics" by Joel Spolsky for the gory details.

This is an instance where C++ generally performs better than C. For heavy weight string handling using std::string is likely to be more efficient and certainly safer.

[edit]

[2nd edit]Corrected code (too many iterations in C string implementation), timings, and conclusion change accordingly

I was surprised at Andrew Bainbridge's comment that std::string was slower, but he did not post complete code for this test case. I modified his (automating the timing) and added a std::string test. The test was on VC++ 2008 (native code) with default "Release" options (i.e. optimised), Athlon dual core, 2.6GHz. Results:

C string handling = 0.023000 seconds
sprintf           = 0.313000 seconds
std::string       = 0.500000 seconds

So here strcat() is faster by far (your milage may vary depending on compiler and options), despite the inherent inefficiency of the C string convention, and supports my original suggestion that sprintf() carries a lot of baggage not required for this purpose. It remains by far the least readable and safe however, so when performance is not critical, has little merit IMO.

I also tested a std::stringstream implementation, which was far slower again, but for complex string formatting still has merit.

Corrected code follows:

#include <ctime>
#include <cstdio>
#include <cstring>
#include <string>

void a(char *first, char *second, char *both)
{
    for (int i = 0; i != 1000000; i++)
    {
        strcpy(both, first);
        strcat(both, " ");
        strcat(both, second);
    }
}

void b(char *first, char *second, char *both)
{
    for (int i = 0; i != 1000000; i++)
        sprintf(both, "%s %s", first, second);
}

void c(char *first, char *second, char *both)
{
    std::string first_s(first) ;
    std::string second_s(second) ;
    std::string both_s(second) ;

    for (int i = 0; i != 1000000; i++)
        both_s = first_s + " " + second_s ;
}

int main(void)
{
    char* first= "First";
    char* second = "Second";
    char* both = (char*) malloc((strlen(first) + strlen(second) + 2) * sizeof(char));
    clock_t start ;

    start = clock() ;
    a(first, second, both);
    printf( "C string handling = %f seconds\n", (float)(clock() - start)/CLOCKS_PER_SEC) ;

    start = clock() ;
    b(first, second, both);
    printf( "sprintf           = %f seconds\n", (float)(clock() - start)/CLOCKS_PER_SEC) ;

    start = clock() ;
    c(first, second, both);
    printf( "std::string       = %f seconds\n", (float)(clock() - start)/CLOCKS_PER_SEC) ;

    return 0;
}

How can I move HEAD back to a previous location? (Detached head) & Undo commits

First reset locally:

git reset 23b6772

To see if you're on the right position, verify with:

git status

You will see something like:

On branch master Your branch is behind 'origin/master' by 17 commits, and can be fast-forwarded.

Then rewrite history on your remote tracking branch to reflect the change:

git push --force-with-lease // a useful command @oktober mentions in comments

Using --force-with-lease instead of --force will raise an error if others have meanwhile committed to the remote branch, in which case you should fetch first. More info in this article.

SSH to Elastic Beanstalk instance

Above answers are bit old.

Firstly create a key-pair and then attach it to Elastic Beanstalk environment.

Steps to create a key-pair

  1. Login to AWS
  2. Services -> EC2
  3. In left under NETWORK & SECURITY select key pairs
  4. Select Create new Key Pair, type key name and click on create. The key will be automatically downloaded to your system.

Steps to attach created key pair to Elastic Beanstalk environment

  1. AWS -> Services -> Elastic Beanstalk

  2. Select your environment and click on the configuration in left.

  3. In Configuration overview select modify from Security.

  4. Under Virtual machine permissions select key-pair that we created.

  5. Click on save and then on save configuration.

This will take some time to reflect to your EC2 instance.

Create Directory if it doesn't exist with Ruby

Another simple way:

Dir.mkdir('tmp/excel') unless Dir.exist?('tmp/excel')

How to set the color of an icon in Angular Material?

That's because the color input only accepts three attributes: "primary", "accent" or "warn". Hence, you'll have to style the icons the CSS way:

  1. Add a class to style your icon:

    .white-icon {
        color: white;
    }
    /* Note: If you're using an SVG icon, you should make the class target the `<svg>` element */
    .white-icon svg {
        fill: white;
    }
    
  2. Add the class to your icon:

    <mat-icon class="white-icon">menu</mat-icon>
    

How can I create an object based on an interface file definition in TypeScript?

You can set default values using Class.

Without Class Constructor:

interface IModal {
  content: string;
  form: string;
  href: string;
  isPopup: boolean;
};

class Modal implements IModal {
  content = "";
  form = "";
  href: string;  // will not be added to object
  isPopup = true;
}

const myModal = new Modal();
console.log(myModal); // output: {content: "", form: "", isPopup: true}

With Class Constructor

interface IModal {
  content: string;
  form: string;
  href: string;
  isPopup: boolean;
}

class Modal implements IModal {
  constructor() {
    this.content = "";
    this.form = "";
    this.isPopup = true;
  }

  content: string;

  form: string;

  href: string; // not part of constructor so will not be added to object

  isPopup: boolean;
}

const myModal = new Modal();
console.log(myModal); // output: {content: "", form: "", isPopup: true}

Java LinkedHashMap get first or last entry

        import java.util.Arrays;
        import java.util.LinkedHashMap;
        import java.util.List;
        import java.util.Map;

        public class Scratch {
           public static void main(String[] args) {

              // Plain java version

              Map<String, List<Integer>> linked = new LinkedHashMap<>();
              linked.put("a", Arrays.asList(1, 2, 3));
              linked.put("aa", Arrays.asList(1, 2, 3, 4));
              linked.put("b", Arrays.asList(1, 2, 3, 4, 5));
              linked.put("bb", Arrays.asList(1, 2, 3, 4, 5, 6));

              System.out.println("linked = " + linked);

              String firstKey = getFirstKey(linked);
              System.out.println("firstKey = " + firstKey);
              List<Integer> firstEntry = linked.get(firstKey);
              System.out.println("firstEntry = " + firstEntry);

              String lastKey = getLastKey(linked);
              System.out.println("lastKey = " + lastKey);
              List<Integer> lastEntry = linked.get(lastKey);
              System.out.println("lastEntry = " + lastEntry);



           }

           private static String getLastKey(Map<String, List<Integer>> linked) {
              int index = 0;
              for (String key : linked.keySet()) {
             index++;
             if (index == linked.size()) {
                return key;
             }
              }
              return null;
           }

           private static String getFirstKey(Map<String, List<Integer>> linked) {
              for (String key : linked.keySet()) {
             return key;
              }
              return null;
           }
        }

Trying to fire the onload event on script tag

You should set the src attribute after the onload event, f.ex:

el.onload = function() { //...
el.src = script;

You should also append the script to the DOM before attaching the onload event:

$body.append(el);
el.onload = function() { //...
el.src = script;

Remember that you need to check readystate for IE support. If you are using jQuery, you can also try the getScript() method: http://api.jquery.com/jQuery.getScript/

Android sample bluetooth code to send a simple string via bluetooth

private OutputStream outputStream;
private InputStream inStream;

private void init() throws IOException {
    BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
    if (blueAdapter != null) {
        if (blueAdapter.isEnabled()) {
            Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();

            if(bondedDevices.size() > 0) {
                Object[] devices = (Object []) bondedDevices.toArray();
                BluetoothDevice device = (BluetoothDevice) devices[position];
                ParcelUuid[] uuids = device.getUuids();
                BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
                socket.connect();
                outputStream = socket.getOutputStream();
                inStream = socket.getInputStream();
            }

            Log.e("error", "No appropriate paired devices.");
        } else {
            Log.e("error", "Bluetooth is disabled.");
        }
    }
}

public void write(String s) throws IOException {
    outputStream.write(s.getBytes());
}

public void run() {
    final int BUFFER_SIZE = 1024;
    byte[] buffer = new byte[BUFFER_SIZE];
    int bytes = 0;
    int b = BUFFER_SIZE;

    while (true) {
        try {
            bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Excel VBA For Each Worksheet Loop

You need to put the worksheet identifier in your range statements as shown below ...

 Option Explicit
 Dim ws As Worksheet, a As Range

Sub forEachWs()

For Each ws In ActiveWorkbook.Worksheets
Call resizingColumns
Next

End Sub

Sub resizingColumns()
ws.Range("A:A").ColumnWidth = 20.14
ws.Range("B:B").ColumnWidth = 9.71
ws.Range("C:C").ColumnWidth = 35.86
ws.Range("D:D").ColumnWidth = 30.57
ws.Range("E:E").ColumnWidth = 23.57
ws.Range("F:F").ColumnWidth = 21.43
ws.Range("G:G").ColumnWidth = 18.43
ws.Range("H:H").ColumnWidth = 23.86
ws.Range("i:I").ColumnWidth = 27.43
ws.Range("J:J").ColumnWidth = 36.71
ws.Range("K:K").ColumnWidth = 30.29
ws.Range("L:L").ColumnWidth = 31.14
ws.Range("M:M").ColumnWidth = 31
ws.Range("N:N").ColumnWidth = 41.14
ws.Range("O:O").ColumnWidth = 33.86
End Sub

How to modify memory contents using GDB?

The easiest is setting a program variable (see GDB: assignment):

(gdb) l
6       {
7           int i;
8           struct file *f, *ftmp;
9
(gdb) set variable i = 10
(gdb) p i
$1 = 10

Or you can just update arbitrary (writable) location by address:

(gdb) set {int}0x83040 = 4

There's more. Read the manual.

ComboBox SelectedItem vs SelectedValue

This is a long-standing "feature" of the list controls in .NET in my experience. Personally, I would just bind to the on change of the SelectedValue property and write whatever additional code is necessary to workaround this "feature" (such as having two properties, binding to one for SelectedValue, and then, on the set of that property, updating the value from SelectedItem in your custom code).

Anyway, I hope that helps =D

How do I get the RootViewController from a pushed controller?

A slightly less ugly version of the same thing mentioned in pretty much all these answers:

UIViewController *rootViewController = [[self.navigationController viewControllers] firstObject];

in your case, I'd probably do something like:

inside your UINavigationController subclass:

- (UIViewController *)rootViewController
{
    return [[self viewControllers] firstObject];
}

then you can use:

UIViewController *rootViewController = [self.navigationController rootViewController];

edit

OP asked for a property in the comments.

if you like, you can access this via something like self.navigationController.rootViewController by just adding a readonly property to your header:

@property (nonatomic, readonly, weak) UIViewController *rootViewController;

How can I erase all inline styles with javascript and leave only the styles specified in the css style sheet?

I was using the $('div').attr('style', ''); technique and it wasn't working in IE8.

I outputted the style attribute using alert() and it was not stripping out inline styles.

.removeAttr ended up doing the trick in IE8.

Laravel 4 with Sentry 2 add user to a group on Registration

Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.

Do you have this:

use Cartalyst\Sentry\Sentry; 

In your code?

Ok, but if this line is working for you:

$user = $this->sentry->register(array(     'username' => e($data['username']),     'email' => e($data['email']),      'password' => e($data['password'])     )); 

So you already have it instantiated and you can surely do:

$adminGroup = $this->sentry->findGroupById(5); 

How can I selectively escape percent (%) in Python strings?

You can't selectively escape %, as % always has a special meaning depending on the following character.

In the documentation of Python, at the bottem of the second table in that section, it states:

'%'        No argument is converted, results in a '%' character in the result.

Therefore you should use:

selectiveEscape = "Print percent %% in sentence and not %s" % (test, )

(please note the expicit change to tuple as argument to %)

Without knowing about the above, I would have done:

selectiveEscape = "Print percent %s in sentence and not %s" % ('%', test)

with the knowledge you obviously already had.

What is the most efficient way to store a list in the Django models?

Remember that this eventually has to end up in a relational database. So using relations really is the common way to solve this problem. If you absolutely insist on storing a list in the object itself, you could make it for example comma-separated, and store it in a string, and then provide accessor functions that split the string into a list. With that, you will be limited to a maximum number of strings, and you will lose efficient queries.

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

For those interested, this is code for creating SHA-256 hash using sjcl:

import sjcl from 'sjcl'

const myString = 'Hello'
const myBitArray = sjcl.hash.sha256.hash(myString)
const myHash = sjcl.codec.hex.fromBits(myBitArray)

How do I use IValidatableObject?

I liked cocogza's answer except that calling base.IsValid resulted in a stack overflow exception as it would re-enter the IsValid method again and again. So I modified it to be for a specific type of validation, in my case it was for an e-mail address.

[AttributeUsage(AttributeTargets.Property)]
class ValidEmailAddressIfTrueAttribute : ValidationAttribute
{
    private readonly string _nameOfBoolProp;

    public ValidEmailAddressIfTrueAttribute(string nameOfBoolProp)
    {
        _nameOfBoolProp = nameOfBoolProp;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (validationContext == null)
        {
            return null;
        }

        var property = validationContext.ObjectType.GetProperty(_nameOfBoolProp);
        if (property == null)
        {
            return new ValidationResult($"{_nameOfBoolProp} not found");
        }

        var boolVal = property.GetValue(validationContext.ObjectInstance, null);

        if (boolVal == null || boolVal.GetType() != typeof(bool))
        {
            return new ValidationResult($"{_nameOfBoolProp} not boolean");
        }

        if ((bool)boolVal)
        {
            var attribute = new EmailAddressAttribute {ErrorMessage = $"{value} is not a valid e-mail address."};
            return attribute.GetValidationResult(value, validationContext);
        }
        return null;
    }
}

This works much better! It doesn't crash and produces a nice error message. Hope this helps someone!

Disable firefox same origin policy

I realized my older answer is downvoted because I didn't specify how to disable FF's same origin policy specifically. Here I will give a more detailed answer:

Warning: This requires a re-compilation of FF, and the newly compiled version of Firefox will not be able to enable SOP again.

Check out Mozilla's Firefox's source code, find nsScriptSecurityManager.cpp in the src directory. I will use the one listed here as example: http://mxr.mozilla.org/aviarybranch/source/caps/src/nsScriptSecurityManager.cpp

Go to the function implementation nsScriptSecurityManager::CheckSameOriginURI, which is line 568 as of date 03/02/2016.

Make that function always return NS_OK.

This will disable SOP for good.

The browser addon answer by @Giacomo should be useful for most people and I have accepted that answer, however, for my personal research needs (TL;won't explain here) it is not enough and I figure other researchers may need to do what I did here to fully kill SOP.

increase font size of hyperlink text html

you can add class in anchor tag also like below

.a_class {font-size: 100px} 

Detect if PHP session exists

function is_session_started()
{
    if ( php_sapi_name() !== 'cli' ) {
        if ( version_compare(phpversion(), '5.4.0', '>=') ) {
            return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
        } else {
            return session_id() === '' ? FALSE : TRUE;
        }
    }
    return FALSE;
}

// Example
if ( is_session_started() === FALSE ) session_start();

Python's "in" set operator

Strings, though they are not set types, have a valuable in property during validation in scripts:

yn = input("Are you sure you want to do this? ")
if yn in "yes":
    #accepts 'y' OR 'e' OR 's' OR 'ye' OR 'es' OR 'yes'
    return True
return False

I hope this helps you better understand the use of in with this example.

input file appears to be a text format dump. Please use psql

If you have a full DB dump:

PGPASSWORD="your_pass" psql -h "your_host" -U "your_user" -d "your_database" -f backup.sql

If you have schemas kept separately, however, that won't work. Then you'll need to disable triggers for data insertion, akin to pg_restore --disable-triggers. You can then use this:

cat database_data_only.gzip | gunzip | PGPASSWORD="your_pass" psql -h "your_host" -U root "your_database" -c 'SET session_replication_role = replica;' -f /dev/stdin

On a side note, it is a very unfortunate downside of postgres, I think. The default way of creating a dump in pg_dump is incompatible with pg_restore. With some additional keys, however, it is. WTF?

Android set bitmap to Imageview

    //decode base64 string to image
    imageBytes = Base64.decode(encodedImage, Base64.DEFAULT);
    Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
    image.setImageBitmap(decodedImage);

  //setImageBitmap is imp

How can I fetch all items from a DynamoDB table without specifying the primary key?

I figured you are using PHP but not mentioned (edited). I found this question by searching internet and since I got solution working , for those who use nodejs here is a simple solution using scan :

  var dynamoClient = new AWS.DynamoDB.DocumentClient();
  var params = {
    TableName: config.dynamoClient.tableName, // give it your table name 
    Select: "ALL_ATTRIBUTES"
  };

  dynamoClient.scan(params, function(err, data) {
    if (err) {
       console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
    } else {
       console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
    }
  });

I assume same code can be translated to PHP too using different AWS SDK

Printing an array in C++?

// Just do this, use a vector with this code and you're good lol -Daniel

#include <Windows.h>
#include <iostream>
#include <vector>

using namespace std;


int main()
{

    std::vector<const char*> arry = { "Item 0","Item 1","Item 2","Item 3" ,"Item 4","Yay we at the end of the array"};
    
    if (arry.size() != arry.size() || arry.empty()) {
        printf("what happened to the array lol\n ");
        system("PAUSE");
    }
    for (int i = 0; i < arry.size(); i++)
    {   
        if (arry.max_size() == true) {
            cout << "Max size of array reached!";
        }
        cout << "Array Value " << i << " = " << arry.at(i) << endl;
            
    }
}

How can I detect browser type using jQuery?

$.browser.chrome = /chrom(e|ium)/.test(navigator.userAgent.toLowerCase()); 

if($.browser.chrome){
  alert(1);      
}

UPDATE:(10x to @Mr. Bacciagalupe)

jQuery has removed $.browser from 1.9 and their latest release.

But you can still use $.browser as a standalone plugin, found here

Most simple code to populate JTable from ResultSet

Class Row will handle one row from your database.

Complete implementation of UpdateTask responsible for filling up UI.

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JTable;
import javax.swing.SwingWorker;

public class JTableUpdateTask extends SwingWorker<JTable, Row> {

    JTable      table       = null;

    ResultSet   resultSet   = null;

    public JTableUpdateTask(JTable table, ResultSet rs) {
        this.table = table;
        this.resultSet = rs;
    }

    @Override
    protected JTable doInBackground() throws Exception {
        List<Row> rows = new ArrayList<Row>();
        Object[] values = new Object[6];
        while (resultSet.next()) {
            values = new Object[6];
            values[0] = resultSet.getString("id");
            values[1] = resultSet.getString("student_name");
            values[2] = resultSet.getString("street");
            values[3] = resultSet.getString("city");
            values[4] = resultSet.getString("state");
            values[5] = resultSet.getString("zipcode");
            Row row = new Row(values);
            rows.add(row);
        }
        process(rows); 
        return this.table;
    }

    protected void process(List<Row> chunks) {
        ResultSetTableModel tableModel = (this.table.getModel() instanceof ResultSetTableModel ? (ResultSetTableModel) this.table.getModel() : null);
        if (tableModel == null) {
            try {
                tableModel = new ResultSetTableModel(this.resultSet.getMetaData(), chunks);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            this.table.setModel(tableModel);
        } else {
            tableModel.getRows().addAll(chunks);
        }
        tableModel.fireTableDataChanged();
    }
}

Table Model:

import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.table.AbstractTableModel;

/**
 * Simple wrapper around Object[] representing a row from the ResultSet.
 */
class Row {
    private final Object[]  values;

    public Row(Object[] values) {
        this.values = values;
    }

    public int getSize() {
        return values.length;
    }

    public Object getValue(int i) {
        return values[i];
    }
}

// TableModel implementation that will be populated by SwingWorker.
public class ResultSetTableModel extends AbstractTableModel {
    private final ResultSetMetaData rsmd;

    private List<Row>               rows;

    public ResultSetTableModel(ResultSetMetaData rsmd, List<Row> rows) {
        this.rsmd = rsmd;
        if (rows != null) {
            this.rows = rows;
        } else {
            this.rows = new ArrayList<Row>();
        }

    }

    public int getRowCount() {
        return rows.size();
    }

    public int getColumnCount() {
        try {
            return rsmd.getColumnCount();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public Object getValue(int row, int column) {
        return rows.get(row).getValue(column);
    }

    public String getColumnName(int col) {
        try {
            return rsmd.getColumnName(col + 1);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return "";
    }

    public Class<?> getColumnClass(int col) {
        String className = "";
        try {
            className = rsmd.getColumnClassName(col);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return className.getClass();
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        if(rowIndex > rows.size()){
            return null;
        }
        return rows.get(rowIndex).getValue(columnIndex);
    }

    public List<Row> getRows() {
        return this.rows;
    }

    public void setRows(List<Row> rows) {
        this.rows = rows;
    }
}

Main Application which builds UI and does the database connection

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTable;

public class MainApp {
    static Connection conn = null;
    static void init(final ResultSet rs) {
        JFrame frame = new JFrame();
        frame.setLayout(new BorderLayout());
        final JTable table = new JTable();
        table.setPreferredSize(new Dimension(300,300));
        table.setMinimumSize(new Dimension(300,300));
        table.setMaximumSize(new Dimension(300,300));
        frame.add(table, BorderLayout.CENTER);
        JButton button = new JButton("Start Loading");
        button.setPreferredSize(new Dimension(30,30));
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JTableUpdateTask jTableUpdateTask = new JTableUpdateTask(table, rs);
                jTableUpdateTask.execute();

            }
        });
        frame.add(button, BorderLayout.SOUTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/test";
        String driver = "com.mysql.jdbc.Driver";
        String userName = "root";
        String password = "root";
        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url, userName, password);
            PreparedStatement pstmt = conn.prepareStatement("Select id, student_name, street, city, state,zipcode from student");
            ResultSet rs = pstmt.executeQuery();
            init(rs);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

How to test if a string contains one of the substrings in a list, in pandas?

One option is just to use the regex | character to try to match each of the substrings in the words in your Series s (still using str.contains).

You can construct the regex by joining the words in searchfor with |:

>>> searchfor = ['og', 'at']
>>> s[s.str.contains('|'.join(searchfor))]
0    cat
1    hat
2    dog
3    fog
dtype: object

As @AndyHayden noted in the comments below, take care if your substrings have special characters such as $ and ^ which you want to match literally. These characters have specific meanings in the context of regular expressions and will affect the matching.

You can make your list of substrings safer by escaping non-alphanumeric characters with re.escape:

>>> import re
>>> matches = ['$money', 'x^y']
>>> safe_matches = [re.escape(m) for m in matches]
>>> safe_matches
['\\$money', 'x\\^y']

The strings with in this new list will match each character literally when used with str.contains.

std::thread calling method of class

Not so hard:

#include <thread>

void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

If the result of the computation is still needed, use a future instead:

#include <future>

void Test::runMultiThread()
{
     auto f1 = std::async(&Test::calculate, this,  0, 10);
     auto f2 = std::async(&Test::calculate, this, 11, 20);

     auto res1 = f1.get();
     auto res2 = f2.get();
}

Query an XDocument for elements by name at any depth

This my variant of the solution based on LINQ and the Descendants method of the XDocument class

using System;
using System.Linq;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        XDocument xml = XDocument.Parse(@"
        <root>
          <child id='1'/>
          <child id='2'>
            <subChild id='3'>
                <extChild id='5' />
                <extChild id='6' />
            </subChild>
            <subChild id='4'>
                <extChild id='7' />
            </subChild>
          </child>
        </root>");

        xml.Descendants().Where(p => p.Name.LocalName == "extChild")
                         .ToList()
                         .ForEach(e => Console.WriteLine(e));

        Console.ReadLine();
    }
}

Results:

For more details on the Desendants method take a look here.

How to negate 'isblank' function

The solution is isblank(cell)=false

How many bits is a "word"?

This is from the book Hackers: Heroes of the Computer Revolution by Steven Levy.

.. the memory had been reduced to 4096 "words" of eighteen bits each. (A "bit" is a binary digit, either a 1 or 0. A series of binary numbers is called a "word").

As the other answers suggest, a "word" does not seem to have a fixed length.

Cannot declare instance members in a static class in C#

I know this post is old but...

I was able to do this, my problem was that I forgot to make my property static.

public static class MyStaticClass
{
    private static NonStaticObject _myObject = new NonStaticObject();

    //property
    public static NonStaticObject MyObject
    {
        get { return _myObject; }
        set { _myObject = value; }
    }
}

PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers

The accepted answer saved me (thanks, Bill!!!), but I ran into another related issue, just wanted to provide some details on my experience -

After upgrading to MySQL 8.0.11, I experienced the same problem as the OP when using PHP's mysqli_connect() function. In my MySQL directory (in my case, usr/local/mysql), I created the my.cnf file, added the content in the accepted answer, then restarted the MySQL server. However, this produced a new error:

mysqli_connect(): The server requested authentication method unknown to the client [caching_sha2_password]

I added the line default_authentication_plugin = mysql_native_password, so my.cnf now looked like:

[client]
default-character-set=utf8

[mysql]
default-character-set=utf8

[mysqld]
collation-server = utf8_unicode_ci
character-set-server = utf8
default_authentication_plugin = mysql_native_password

and I was good to go!

For additional reference: https://github.com/laradock/laradock/issues/1392

How to disable back swipe gesture in UINavigationController on iOS 7

All of these solutions manipulate Apple's gesture recognizer in a way they do not recommend. I've just been told by a friend that there's a better solution:

[navigationController.interactivePopGestureRecognizer requireGestureRecognizerToFail: myPanGestureRecognizer];

where myPanGestureRecognizer is the gesture recognizer you are using to e.g. show your menu. That way, Apple's gesture recognizer doesn't get turned back on by them when you push a new navigation controller and you don't need to rely on hacky delays that may fire too early if your phone is put to sleep or under heavy load.

Leaving this here because I know I'll not remember this the next time I need it, and then I'll have the solution to the issue here.

How to move an entire div element up x pixels?

$('div').css({
    position: 'relative',
    top: '-15px'
});

moment.js 24h format

Stating your time as HH will give you 24h format, and hh will give 12h format.

You can also find it here in the documentation :

    H, HH       24 hour time
    h, or hh    12 hour time (use in conjunction with a or A)

C++ trying to swap values in a vector

Both proposed possibilities (std::swap and std::iter_swap) work, they just have a slightly different syntax. Let's swap a vector's first and second element, v[0] and v[1].

We can swap based on the objects contents:

std::swap(v[0],v[1]);

Or swap based on the underlying iterator:

std::iter_swap(v.begin(),v.begin()+1);

Try it:

int main() {
  int arr[] = {1,2,3,4,5,6,7,8,9};
  std::vector<int> * v = new std::vector<int>(arr, arr + sizeof(arr) / sizeof(arr[0]));
  // put one of the above swap lines here
  // ..
  for (std::vector<int>::iterator i=v->begin(); i!=v->end(); i++)
    std::cout << *i << " ";
  std::cout << std::endl;
}

Both times you get the first two elements swapped:

2 1 3 4 5 6 7 8 9

How do I store data in local storage using Angularjs?

There is one more alternative module which has more activity than ngStorage

angular-local-storage:

https://github.com/grevory/angular-local-storage

how to count length of the JSON array element

I think you should try

data = {"shareInfo":[{"id":"1","a":"sss","b":"sss","question":"whi?"},
{"id":"2","a":"sss","b":"sss","question":"whi?"},
{"id":"3","a":"sss","b":"sss","question":"whi?"},
{"id":"4","a":"sss","b":"sss","question":"whi?"}]};

ShareInfoLength = data.shareInfo.length;
alert(ShareInfoLength);
for(var i=0; i<ShareInfoLength; i++)
{
alert(Object.keys(data.shareInfo[i]).length);
}

What is the difference between a web API and a web service?

API vs Web Service

Just pasted the summary of the linked article:

Summary:

  1. All Web services are APIs but all APIs are not Web services.

  2. Web services might not perform all the operations that an API would perform.

  3. A Web service uses only three styles of use: SOAP, REST and XML-RPC for communication whereas API may use any style for communication.

  4. A Web service always needs a network for its operation whereas an API doesn’t need a network for its operation.

  5. An API facilitates interfacing directly with an application whereas a Web service is a ...

Read more: Difference Between API and Web Service | Difference Between | API vs Web Service http://www.differencebetween.net/technology/internet/difference-between-api-and-web-service/#ixzz3e3WxplAv

See the above link for the complete answer.

Sending command line arguments to npm script

This doesn't really answer your question but you could always use environment variables instead:

"scripts": {
    "start": "PORT=3000 node server.js"
}

Then in your server.js file:

var port = process.env.PORT || 3000;

How to set UITextField height?

If you are using Auto Layout then you can do it on the Story board.

Add a height constraint to the text field, then change the height constraint constant to any desired value. Steps are shown below:

Step 1: Create a height constraint for the text field

enter image description here

Step 2: Select Height Constraint

enter image description here

Step 3: Change Height Constraint's constant value

enter image description here

How do I simulate a low bandwidth, high latency environment?

I've been looking for an easy to use tool for this type of testing for a while now. I just came across this the other day: Network Delay Simulator

If you're running Windows, you should check it out. It was super easy to set up and get going, and seems to work really well. It allows you to define bandwidth, latency, and packet loss in each direction. The other really nice thing is that you can define "Flow Match Conditions" so that it only affects the traffic you want it to. Oh yeah, and it's free.

How to delete shared preferences data from App in Android

If it's not necessary to be removed every time, you can remove it manually from:

Settings -> Applications -> Manage applications -> (choose your app) -> Clear data or Uninstall

Newer versions of Android:

Settings -> Applications -> (choose your app) -> Storage -> Clear data and Clear cache

Byte and char conversion in Java

A character in Java is a Unicode code-unit which is treated as an unsigned number. So if you perform c = (char)b the value you get is 2^16 - 56 or 65536 - 56.

Or more precisely, the byte is first converted to a signed integer with the value 0xFFFFFFC8 using sign extension in a widening conversion. This in turn is then narrowed down to 0xFFC8 when casting to a char, which translates to the positive number 65480.

From the language specification:

5.1.4. Widening and Narrowing Primitive Conversion

First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3).


To get the right point use char c = (char) (b & 0xFF) which first converts the byte value of b to the positive integer 200 by using a mask, zeroing the top 24 bits after conversion: 0xFFFFFFC8 becomes 0x000000C8 or the positive number 200 in decimals.


Above is a direct explanation of what happens during conversion between the byte, int and char primitive types.

If you want to encode/decode characters from bytes, use Charset, CharsetEncoder, CharsetDecoder or one of the convenience methods such as new String(byte[] bytes, Charset charset) or String#toBytes(Charset charset). You can get the character set (such as UTF-8 or Windows-1252) from StandardCharsets.

What is the HTML tabindex attribute?

tabindex is a global attribute responsible for two things:

  1. it sets the order of "focusable" elements and
  2. it makes elements "focusable".

In my mind the second thing is even more important than the first one. There are very few elements that are focusable by default (e.g. <a> and form controls). Developers very often add some JavaScript event handlers (like 'onclick') on not focusable elements (<div>, <span> and so on), and the way to make your interface be responsive not only to mouse events but also to keyboard events (e.g. 'onkeypress') is to make such elements focusable. Lastly, if you don't want to set the order but just make your element focusable use tabindex="0" on all such elements:

<div tabindex="0"></div>

Also, if you don't want it to be focusable via the tab key then use tabindex="-1". For example, the below link will not be focused while using tab keys to traverse.

<a href="#" tabindex="-1">Tab key cannot reach here!</a>

Refresh/reload the content in Div using jquery/ajax

$("#myDiv").load(location.href+" #myDiv>*","");

Mockito match any class argument

If you have no idea which Package you need to import:

import static org.mockito.ArgumentMatchers.any;
any(SomeClass.class)

OR

import org.mockito.ArgumentMatchers;
ArgumentMatchers.any(SomeClass.class)

Fix columns in horizontal scrolling

Solved using JavaScript + jQuery! I just need similar solution to my project but current solution with HTML and CSS is not ok for me because there is issue with column height + I need more then one column to be fixed. So I create simple javascript solution using jQuery

You can try it here https://jsfiddle.net/kindrosker/ffwqvntj/

All you need is setup home many columsn will be fixed in data-count-fixed-columns parameter

<table class="table" data-count-fixed-columns="2" cellpadding="0" cellspacing="0">

and run js function

app_handle_listing_horisontal_scroll($('#table-listing'))

Confirm deletion using Bootstrap 3 modal box

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

https://getbootstrap.com/docs/4.0/components/modal/

Java String remove all non numeric characters

With guava:

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

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

Number input type that takes only integers?

The integer input would mean that it can only take positive numbers, 0 and negative numbers too. This is how I have been able to achieve this using Javascript keypress.

<input type="number" (keypress)="keypress($event, $event.target.value)" >

keypress(evt, value){
  
    if (evt.charCode >= 48 && evt.charCode <= 57 || (value=="" && evt.charCode == 45))       
    {  
      return true;
    }
    return false;
}

The given code won't allow user to enter alphabets nor decimal on runtime, just positive and negative integer values.

How to listen to route changes in react router v4?

withRouter, history.listen, and useEffect (React Hooks) works quite nicely together:

import React, { useEffect } from 'react'
import { withRouter } from 'react-router-dom'

const Component = ({ history }) => {
    useEffect(() => history.listen(() => {
        // do something on route change
        // for my example, close a drawer
    }), [])

    //...
}

export default withRouter(Component)

The listener callback will fire any time a route is changed, and the return for history.listen is a shutdown handler that plays nicely with useEffect.

How to read a specific line using the specific line number from a file in Java?

If you are talking about a text file, then there is really no way to do this without reading all the lines that precede it - After all, lines are determined by the presence of a newline, so it has to be read.

Use a stream that supports readline, and just read the first X-1 lines and dump the results, then process the next one.

Laravel, sync() - how to sync an array and also pass additional pivot fields?

Add following trait to your project and append it to your model class as a trait. This is helpful, because this adds functionality to use multiple pivots. Probably someone can clean this up a little and improve on it ;)

namespace App\Traits;

trait AppTraits
{
    /**
     * Create pivot array from given values
     *
     * @param array $entities
     * @param array $pivots
     * @return array combined $pivots
     */
    public function combinePivot($entities, $pivots = [])
    {
        // Set array
        $pivotArray = [];
        // Loop through all pivot attributes
        foreach ($pivots as $pivot => $value) {
            // Combine them to pivot array
            $pivotArray += [$pivot => $value];
        }
        // Get the total of arrays we need to fill
        $total = count($entities);
        // Make filler array
        $filler = array_fill(0, $total, $pivotArray);
        // Combine and return filler pivot array with data
        return array_combine($entities, $filler);
    }
}

Model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Example extends Model
{
    use Traits\AppTraits;
    // ...
}

Usage:

// Get id's
$entities = [1, 2, 3];
// Create pivots
$pivots = [
    'price' => 634,
    'name'  => 'Example name',
];
// Combine the ids and pivots
$combination = $model->combinePivot($entities, $pivots);
// Sync the combination with the related model / pivot
$model->relation()->sync($combination);

How to send a JSON object using html form data

You can try something like:

<html>
<head>
    <title>test</title>
</head>

<body>
    <form id="formElem">
        <input type="text" name="firstname" value="Karam">
        <input type="text" name="lastname" value="Yousef">
        <input type="submit">
    </form>
    <div id="decoded"></div>
    <button id="encode">Encode</button>
    <div id="encoded"></div>
</body>
<script>
    encode.onclick = async (e) => {
        let response = await fetch('http://localhost:8482/encode', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                },
        })

        let text = await response.text(); // read response body as text
        data = JSON.parse(text);
        document.querySelector("#encoded").innerHTML = text;
      //  document.querySelector("#encoded").innerHTML = `First name = ${data.firstname} <br/> 
      //                                                  Last name = ${data.lastname} <br/>
      //                                                  Age    = ${data.age}`
    };

    formElem.onsubmit = async (e) => {
      e.preventDefault();
      var form = document.querySelector("#formElem");
     // var form = document.forms[0];

        data = {
          firstname : form.querySelector('input[name="firstname"]').value,
          lastname : form.querySelector('input[name="lastname"]').value,
          age : 5
        }

        let response = await fetch('http://localhost:8482/decode', {
                method: 'POST', // or 'PUT'
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data),
        })

        let text = await response.text(); // read response body as text
        document.querySelector("#decoded").innerHTML = text;
    };
</script>
</html>

PHP Regex to check date is in YYYY-MM-DD format

preg_match needs a / or another char as delimiter.

preg_match("/^[0-9]{4}-[0-1][0-9]-[0-3][0-9]$/",$date)

you also should check for validity of that date so you wouldn't end up with something like 9999-19-38

bool checkdate ( int $month , int $day , int $year )

Laravel: PDOException: could not find driver

In CentOS7,I try this: yum install php-mysql, then edit php.ini

Check/Uncheck all the checkboxes in a table

$(document).ready(function () {

            var someObj = {};

            $("#checkAll").click(function () {
                $('.chk').prop('checked', this.checked);
            });

            $(".chk").click(function () {

                $("#checkAll").prop('checked', ($('.chk:checked').length == $('.chk').length) ? true : false);
            });

            $("input:checkbox").change(function () {
                debugger;

                someObj.elementChecked = [];

                $("input:checkbox").each(function () {
                    if ($(this).is(":checked")) {
                        someObj.elementChecked.push($(this).attr("id"));

                    }

                });             
            });

            $("#button").click(function () {
                debugger;

                alert(someObj.elementChecked);

            });

        });
    </script>
</head>

<body>

    <ul class="chkAry">
        <li><input type="checkbox" id="checkAll" />Select All</li>

        <li><input class="chk" type="checkbox" id="Delhi">Delhi</li>

        <li><input class="chk" type="checkbox" id="Pune">Pune</li>

        <li><input class="chk" type="checkbox" id="Goa">Goa</li>

        <li><input class="chk" type="checkbox" id="Haryana">Haryana</li>

        <li><input class="chk" type="checkbox" id="Mohali">Mohali</li>

    </ul>
    <input type="button" id="button" value="Get" />

</body>

How to delete a folder with files using Java

Java isn't able to delete folders with data in it. You have to delete all files before deleting the folder.

Use something like:

String[]entries = index.list();
for(String s: entries){
    File currentFile = new File(index.getPath(),s);
    currentFile.delete();
}

Then you should be able to delete the folder by using index.delete() Untested!

SVN Commit specific files

Sure. Just list the files:

$ svn ci -m "Fixed all those horrible crashes" foo bar baz graphics/logo.png

I'm not aware of a way to tell it to ignore a certain set of files. Of course, if the files you do want to commit are easily listed by the shell, you can use that:

$ svn ci -m "No longer sets printer on fire" printer-driver/*.c

You can also have the svn command read the list of files to commit from a file:

$ svn ci -m "Now works" --targets fix4711.txt

How to add new line into txt file

No new line:

File.AppendAllText("file.txt", DateTime.Now.ToString());

and then to get a new line after OK:

File.AppendAllText("file.txt", string.Format("{0}{1}", "OK", Environment.NewLine));

How to increase dbms_output buffer?

Here you go:

DECLARE
BEGIN
  dbms_output.enable(NULL); -- Disables the limit of DBMS
  -- Your print here !
END;

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

  1. Delete .gradle data
  2. CtrlAltS then navigate to File -> Settings -> Build, Execution, Deployment -> Compiler then check "Sync project with gradle before building, if needed".

My problem was fixed with this method.

How to check if a stored procedure exists before creating it

I know it is a very old post, but since this appears in the top search results hence adding the latest update for those using SQL Server 2016 SP1 -

create or alter procedure procTest
as
begin
 print (1)
end;
go

This creates a Stored Procedure if does not already exist, but alters it if exists.

Reference

Changing tab bar item image and text color iOS

For Swift 4.0, it's now changed as:

tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.gray], for: .normal)
tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.blue], for: .selected)

You don't have to subclass the UITabBarItem if your requirement is only to change the text color. Just put the above code inside your view controller's viewDidLoad function.

For global settings change tabBarItem to UITabBarItem.appearance().

How to position absolute inside a div?

The problem is described (among other) in this article.

#box is relatively positioned, which makes it part of the "flow" of the page. Your other divs are absolutely positioned, so they are removed from the page's "flow".

Page flow means that the positioning of an element effects other elements in the flow.

In other words, as #box now sees the dom, .a and .b are no longer "inside" #box.

To fix this, you would want to make everything relative, or everything absolute.

One way would be:

.a {
   position:relative;
   margin-top:10px;
   margin-left:10px;
   background-color:red;
   width:210px;
   padding: 5px;
}

ORA-12170: TNS:Connect timeout occurred

It is because of conflicting SID. For example, in your Oracle12cBase\app\product\12.1.0\dbhome_1\NETWORK\ADMIN\tnsnames.ora file, connection description for ORCL is this:

ORCL =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = orcl)
    )
  )

And, you are trying to connect using the connection string using same SID but different IP, username/password, like this:

sqlplus username/[email protected]:1521/orcl

To resolve this, make changes in the tnsnames.ora file:

ORCL =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.130.52)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = orcl)
    )
  )

Access a JavaScript variable from PHP

As JavaScript is a client-side language and PHP is a server-side language you would need to physically push the variable to the PHP script, by either including the variable on the page load of the PHP script (script.php?var=test), which really has nothing to do with JavaScript, or by passing the variable to the PHP via an AJAX/AHAH call each time the variable is changed.

If you did want to go down the second path, you'd be looking at XMLHttpRequest, or my preference, jQuerys Ajax calls: http://docs.jquery.com/Ajax

Set JavaScript variable = null, or leave undefined?

I usually set it to whatever I expect to be returned from the function.

If a string, than i will set it to an empty string ='', same for object ={} and array=[], integers = 0.

using this method saves me the need to check for null / undefined. my function will know how to handle string/array/object regardless of the result.

How to programmatically send a 404 response with Express/Node?

From the Express site, define a NotFound exception and throw it whenever you want to have a 404 page OR redirect to /404 in the below case:

function NotFound(msg){
  this.name = 'NotFound';
  Error.call(this, msg);
  Error.captureStackTrace(this, arguments.callee);
}

NotFound.prototype.__proto__ = Error.prototype;

app.get('/404', function(req, res){
  throw new NotFound;
});

app.get('/500', function(req, res){
  throw new Error('keyboard cat!');
});

If using maven, usually you put log4j.properties under java or resources?

When putting resource files in another location is not the best solution you can use:

<build>
  <resources>
    <resource>
      <directory>src/main/java</directory>
      <excludes>
        <exclude>**/*.java</exclude>
      </excludes>
    </resource>
  </resources>
<build>

For example when resources files (e.g. jaxb.properties) goes deep inside packages along with Java classes.

Adding custom HTTP headers using JavaScript

If you're using XHR, then setRequestHeader should work, e.g.

xhr.setRequestHeader('custom-header', 'value');

P.S. You should use Hijax to modify the behavior of your anchors so that it works if for some reason the AJAX isn't working for your clients (like a busted script elsewhere on the page).

How does `scp` differ from `rsync`?

rysnc can be useful to run on slow and unreliable connections. So if your download aborts in the middle of a large file rysnc will be able to continue from where it left off when invoked again.

Use rsync -vP username@host:/path/to/file .

The -P option preserves partially downloaded files and also shows progress.

As usual check man rsync

Difference between two numpy arrays in python

You can also use numpy.subtract

It has the advantage over the difference operator, -, that you do not have to transform the sequences (list or tuples) into a numpy arrays — you save the two commands:

array1 = np.array([1.1, 2.2, 3.3])
array2 = np.array([1, 2, 3])

Example: (Python 3.5)

import numpy as np
result = np.subtract([1.1, 2.2, 3.3], [1, 2, 3])
print ('the difference =', result)

which gives you

the difference = [ 0.1  0.2  0.3]

Remember, however, that if you try to subtract sequences (lists or tuples) with the - operator you will get an error. In this case, you need the above commands to transform the sequences in numpy arrays

Wrong Code:

print([1.1, 2.2, 3.3] - [1, 2, 3])

OSX El Capitan: sudo pip install OSError: [Errno: 1] Operation not permitted

I had the same issues. As others have mentioned, don't run pip install with sudo. Run

brew doctor 

and fix the warnings and you should be able to proceed with your pip install.

How to know which version of Symfony I have?

Another way is to look at the source for Symfony\Component\HttpKernel\Kernel for where const VERSION is defined. Example on GitHub

Locally this would be located in vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php.

How to change the version of the 'default gradle wrapper' in IntelliJ IDEA?

First, let gradle set the correct distribution Url

cd projectDirectory
./gradlew wrapper --gradle-version 2.3.0

Then - might not be needed but that's what I did - edit the project's build.gradle to match the version

    dependencies {
    classpath 'com.android.tools.build:gradle:2.3.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}

Finally, delete the folders .gradle and gradle and the files gradlew and gradlew.bat. (Original Answer)

Now, rebuild the project.

As the other answers did not suffice for me and the comment pointing out these additional steps is easy to overlook, here as a separate answer

What does "yield break;" do in C#?

yield basically makes an IEnumerable<T> method behave similarly to a cooperatively (as opposed to preemptively) scheduled thread.

yield return is like a thread calling a "schedule" or "sleep" function to give up control of the CPU. Just like a thread, the IEnumerable<T> method regains controls at the point immediately afterward, with all local variables having the same values as they had before control was given up.

yield break is like a thread reaching the end of its function and terminating.

People talk about a "state machine", but a state machine is all a "thread" really is. A thread has some state (I.e. values of local variables), and each time it is scheduled it takes some action(s) in order to reach a new state. The key point about yield is that, unlike the operating system threads we're used to, the code that uses it is frozen in time until the iteration is manually advanced or terminated.

Comparing two files in linux terminal

Using awk for it. Test files:

$ cat a.txt
one
two
three
four
four
$ cat b.txt
three
two
one

The awk:

$ awk '
NR==FNR {                    # process b.txt  or the first file
    seen[$0]                 # hash words to hash seen
    next                     # next word in b.txt
}                            # process a.txt  or all files after the first
!($0 in seen)' b.txt a.txt   # if word is not hashed to seen, output it

Duplicates are outputed:

four
four

To avoid duplicates, add each newly met word in a.txt to seen hash:

$ awk '
NR==FNR {
    seen[$0]
    next
}
!($0 in seen) {              # if word is not hashed to seen
    seen[$0]                 # hash unseen a.txt words to seen to avoid duplicates 
    print                    # and output it
}' b.txt a.txt

Output:

four

If the word lists are comma-separated, like:

$ cat a.txt
four,four,three,three,two,one
five,six
$ cat b.txt
one,two,three

you have to do a couple of extra laps (forloops):

awk -F, '                    # comma-separated input
NR==FNR {
    for(i=1;i<=NF;i++)       # loop all comma-separated fields
        seen[$i]
    next
}
{
    for(i=1;i<=NF;i++)
        if(!($i in seen)) {
             seen[$i]        # this time we buffer output (below):
             buffer=buffer (buffer==""?"":",") $i
        }
    if(buffer!="") {         # output unempty buffers after each record in a.txt
        print buffer
        buffer=""
    }
}' b.txt a.txt

Output this time:

four
five,six

How to ignore PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException?

I also faced this issue. I was having JDK 1.8.0_121. I upgraded JDK to 1.8.0_181 and it worked like a charm.

javascript multiple OR conditions in IF statement

With an OR (||) operation, if any one of the conditions are true, the result is true.

I think you want an AND (&&) operation here.

How to display special characters in PHP

After much banging-head-on-table, I have a bit better understanding of the issue that I wanted to post for anyone else who may have had this issue.

While the UTF-8 character set will display special characters on the client, the server, on the other hand, may not be so accomodating and would print special characters such as à and è as ? and ?.

To make sure your server will print them correctly, use the ISO-8859-1 charset:

<?php
    /*Just for your server-side code*/
    header('Content-Type: text/html; charset=ISO-8859-1');
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"><!-- Your HTML file can still use UTF-8-->
        <title>Untitled Document</title>
    </head>
    <body>
        <?= "àè" ?>
    </body>
</html>

This will print correctly: àè


Edit (4 years later):

I have a little better understanding now. The reason this works is that the client (browser) is being told, through the response header(), to expect an ISO-8859-1 text/html file. (As others have mentioned, you can also do this by updating your .ini or .htaccess files.) Then, once the browser begins to parse that given file into the DOM, the output will obey any <meta charset=""> rule but keep your ISO characters intact.

Ping a site in Python?

You may find Noah Gift's presentation Creating Agile Commandline Tools With Python. In it he combines subprocess, Queue and threading to develop solution that is capable of pinging hosts concurrently and speeding up the process. Below is a basic version before he adds command line parsing and some other features. The code to this version and others can be found here

#!/usr/bin/env python2.5
from threading import Thread
import subprocess
from Queue import Queue

num_threads = 4
queue = Queue()
ips = ["10.0.1.1", "10.0.1.3", "10.0.1.11", "10.0.1.51"]
#wraps system ping command
def pinger(i, q):
    """Pings subnet"""
    while True:
        ip = q.get()
        print "Thread %s: Pinging %s" % (i, ip)
        ret = subprocess.call("ping -c 1 %s" % ip,
            shell=True,
            stdout=open('/dev/null', 'w'),
            stderr=subprocess.STDOUT)
        if ret == 0:
            print "%s: is alive" % ip
        else:
            print "%s: did not respond" % ip
        q.task_done()
#Spawn thread pool
for i in range(num_threads):

    worker = Thread(target=pinger, args=(i, queue))
    worker.setDaemon(True)
    worker.start()
#Place work in queue
for ip in ips:
    queue.put(ip)
#Wait until worker threads are done to exit    
queue.join()

He is also author of: Python for Unix and Linux System Administration

http://ecx.images-amazon.com/images/I/515qmR%2B4sjL._SL500_AA240_.jpg

What are some great online database modeling tools?

You may want to look at IBExpert Personal Edition. While not open source, this is a very good tool for designing, building, and administering Firebird and InterBase databases.

The Personal Edition is free, but some of the more advanced features are not available. Still, even without the slick extras, the free version is very powerful.

How to get row count in sqlite using Android?

Do you see what the DatabaseUtils.queryNumEntries() does? It's awful! I use this.

public int getRowNumberByArgs(Object... args) {
    String where = compileWhere(args);
    String raw = String.format("SELECT count(*) FROM %s WHERE %s;", TABLE_NAME, where);
    Cursor c = getWriteableDatabase().rawQuery(raw, null);
    try {
        return (c.moveToFirst()) ? c.getInt(0) : 0;
    } finally {
        c.close();
    }
}

How to use null in switch

You can also use String.valueOf((Object) nullableString) like

switch (String.valueOf((Object) nullableString)) {
case "someCase"
    //...
    break;
...
case "null": // or default:
    //...
        break;
}

See interesting SO Q/A: Why does String.valueOf(null) throw a NullPointerException

How often should you use git-gc?

I use when I do a big commit, above all when I remove more files from the repository.. after, the commits are faster

Adding placeholder text to textbox

I came up with a method that worked for me, but only because I was willing to use the textbox name as my placeholder. See below.

public TextBox employee = new TextBox();

private void InitializeHomeComponent()
{
    //
    //employee
    //
    this.employee.Name = "Caller Name";
    this.employee.Text = "Caller Name";
    this.employee.BackColor = System.Drawing.SystemColors.InactiveBorder;
    this.employee.Location = new System.Drawing.Point(5, 160);
    this.employee.Size = new System.Drawing.Size(190, 30);
    this.employee.TabStop = false;
    this.Controls.Add(employee);
    // I loop through all of my textboxes giving them the same function
    foreach (Control C in this.Controls)
    {
        if (C.GetType() == typeof(System.Windows.Forms.TextBox))
        {
            C.GotFocus += g_GotFocus;
            C.LostFocus += g_LostFocus;
        }
     }
 }

    private void g_GotFocus(object sender, EventArgs e)
    {
        var tbox = sender as TextBox;
        tbox.Text = "";
    }

    private void g_LostFocus(object sender, EventArgs e)
    {
        var tbox = sender as TextBox;
        if (tbox.Text == "")
        {
            tbox.Text = tbox.Name;
        }
    }

Using python's mock patch.object to change the return value of a method called within another method

There are two ways you can do this; with patch and with patch.object

Patch assumes that you are not directly importing the object but that it is being used by the object you are testing as in the following

#foo.py
def some_fn():
    return 'some_fn'

class Foo(object):
    def method_1(self):
        return some_fn()
#bar.py
import foo
class Bar(object):
    def method_2(self):
        tmp = foo.Foo()
        return tmp.method_1()
#test_case_1.py
import bar
from mock import patch

@patch('foo.some_fn')
def test_bar(mock_some_fn):
    mock_some_fn.return_value = 'test-val-1'
    tmp = bar.Bar()
    assert tmp.method_2() == 'test-val-1'
    mock_some_fn.return_value = 'test-val-2'
    assert tmp.method_2() == 'test-val-2'

If you are directly importing the module to be tested, you can use patch.object as follows:

#test_case_2.py
import foo
from mock import patch

@patch.object(foo, 'some_fn')
def test_foo(test_some_fn):
    test_some_fn.return_value = 'test-val-1'
    tmp = foo.Foo()
    assert tmp.method_1() == 'test-val-1'
    test_some_fn.return_value = 'test-val-2'
    assert tmp.method_1() == 'test-val-2'

In both cases some_fn will be 'un-mocked' after the test function is complete.

Edit: In order to mock multiple functions, just add more decorators to the function and add arguments to take in the extra parameters

@patch.object(foo, 'some_fn')
@patch.object(foo, 'other_fn')
def test_foo(test_other_fn, test_some_fn):
    ...

Note that the closer the decorator is to the function definition, the earlier it is in the parameter list.

How to completely uninstall Android Studio from windows(v10)?

I was having problem installing the latest v4.1.2 as it was having issue after I start it it shows my old blank project, so things I did were,

Caution: Please move your sdk and projects to a separate location before following steps if you haven't. So it might save your time downloading sdks and stuff.

1- Uninstall old Android Studio Completely (from Contorl panel -> Programs).

2- Delete this Android Studio Folder located at C:\Users<user_name>\AppData\Local\Google

3- Delete this Android Studio Folder located at C:\Users<user_name>\AppData\Roaming\Google

4- Delete these folders(.android ,.AndroidStudio*, .gradle) located at C:\Users<user_name>\

After doing all this I was managed to have fresh updated Android Studio v4.1.2

How do I get the real .height() of a overflow: hidden or overflow: scroll div?

Other possibility would be place the html in a non overflow:hidden element placed 'out' of screen, like a position absolute top and left lesse then 5000px, then read this elements height. Its ugly, but work well.

SQL Server equivalent to Oracle's CREATE OR REPLACE VIEW

In SQL Server 2016 (or newer) you can use this:

CREATE OR ALTER VIEW VW_NAMEOFVIEW AS ...

In older versions of SQL server you have to use something like

DECLARE @script NVARCHAR(MAX) = N'VIEW [dbo].[VW_NAMEOFVIEW] AS ...';

IF NOT EXISTS(SELECT * FROM sys.views WHERE name = 'VW_NAMEOFVIEW')
-- IF OBJECT_ID('[dbo].[VW_NAMEOFVIEW]') IS NOT NULL
BEGIN EXEC('CREATE ' + @script) END
ELSE
BEGIN EXEC('ALTER ' + @script) END

Or, if there are no dependencies on the view, you can just drop it and recreate:

IF EXISTS(SELECT * FROM sys.views WHERE name = 'VW_NAMEOFVIEW')
-- IF OBJECT_ID('[dbo].[VW_NAMEOFVIEW]') IS NOT NULL
BEGIN 
   DROP VIEW [VW_NAMEOFVIEW];
END

CREATE VIEW [VW_NAMEOFVIEW] AS ...

Creating layout constraints programmatically

Regarding your second question about properties, you can use self.myView only if you declared it as a property in class. Since myView is a local variable, you can not use it that way. For more details on this, I would recommend you to go through the apple documentation on Declared Properties,

Convert hex string to int

This is the right answer:

myPassedColor = "#ffff8c85" int colorInt = Color.parseColor(myPassedColor)

jQuery.getJSON - Access-Control-Allow-Origin Issue

It's simple, use $.getJSON() function and in your URL just include

callback=?

as a parameter. That will convert the call to JSONP which is necessary to make cross-domain calls. More info: http://api.jquery.com/jQuery.getJSON/

Should I use the datetime or timestamp data type in MySQL?

I prefer using timestamp so to keep everything in one common raw format and format the data in PHP code or in your SQL query. There are instances where it comes in handy in your code to keep everything in plain seconds.

Difference between web reference and service reference?

Service references deal with endpoints and bindings, which are completely configurable. They let you point your client proxy to a WCF via any transport protocol (HTTP, TCP, Shared Memory, etc)

They are designed to work with WCF.

If you use a WebProxy, you are pretty much binding yourself to using WCF over HTTP

How to limit file upload type file size in PHP?

Hope this helps :-)

if(isset($_POST['submit'])){
    ini_set("post_max_size", "30M");
    ini_set("upload_max_filesize", "30M");
    ini_set("memory_limit", "20000M"); 
    $fileName='product_demo.png';

    if($_FILES['imgproduct']['size'] > 0 && 
            (($_FILES["imgproduct"]["type"] == "image/gif") || 
                ($_FILES["imgproduct"]["type"] == "image/jpeg")|| 
                ($_FILES["imgproduct"]["type"] == "image/pjpeg") || 
                ($_FILES["imgproduct"]["type"] == "image/png") &&
                ($_FILES["imgproduct"]["size"] < 2097152))){

        if ($_FILES["imgproduct"]["error"] > 0){
            echo "Return Code: " . $_FILES["imgproduct"]["error"] . "<br />";
        } else {    
            $rnd=rand(100,999);
            $rnd=$rnd."_";
            $fileName = $rnd.trim($_FILES['imgproduct']['name']);
            $tmpName  = $_FILES['imgproduct']['tmp_name'];
            $fileSize = $_FILES['imgproduct']['size'];
            $fileType = $_FILES['imgproduct']['type'];  
            $target = "upload/";
            echo $target = $target .$rnd. basename( $_FILES['imgproduct']['name']) ; 
            move_uploaded_file($_FILES['imgproduct']['tmp_name'], $target);
        }
    } else {
        echo "Sorry, there was a problem uploading your file.";
    }
}

How to convert a std::string to const char* or char*?

Use the .c_str() method for const char *.

You can use &mystring[0] to get a char * pointer, but there are a couple of gotcha's: you won't necessarily get a zero terminated string, and you won't be able to change the string's size. You especially have to be careful not to add characters past the end of the string or you'll get a buffer overrun (and probable crash).

There was no guarantee that all of the characters would be part of the same contiguous buffer until C++11, but in practice all known implementations of std::string worked that way anyway; see Does “&s[0]” point to contiguous characters in a std::string?.

Note that many string member functions will reallocate the internal buffer and invalidate any pointers you might have saved. Best to use them immediately and then discard.

GitHub relative link in Markdown file

Just wanted to add this because none of the above solutions worked if target link is directory with spaces in it's name. If target link is a directory and it has space then even escaping space with \ doesn't render the link on Github. Only solution worked for me is using %20 for each space.

e.g.: if directory structure is this

Top_dir
|-----README.md
|-----Cur_dir1
      |----Dir A
           |----README.md
      |----Dir B
           |----README.md

To make link to Dir A in README.md present in Top_dir you can do this:

[Dir 1](Cur_dir1/Dir%20A)

What's the best way to add a drop shadow to my UIView

On viewWillLayoutSubviews:

override func viewWillLayoutSubviews() {
    sampleView.layer.masksToBounds =  false
    sampleView.layer.shadowColor = UIColor.darkGrayColor().CGColor;
    sampleView.layer.shadowOffset = CGSizeMake(2.0, 2.0)
    sampleView.layer.shadowOpacity = 1.0
}

Using Extension of UIView:

extension UIView {

    func addDropShadowToView(targetView:UIView? ){
        targetView!.layer.masksToBounds =  false
        targetView!.layer.shadowColor = UIColor.darkGrayColor().CGColor;
        targetView!.layer.shadowOffset = CGSizeMake(2.0, 2.0)
        targetView!.layer.shadowOpacity = 1.0
    }
}

Usage:

sampleView.addDropShadowToView(sampleView)

How to convert int to date in SQL Server 2008

You have to first convert it into datetime, then to date.

Try this, it might be helpful:

Select Convert(DATETIME, LEFT(20130101, 8))

then convert to date.

How to get the previous URL in JavaScript?

This will navigate to the previously visited URL.

javascript:history.go(-1)

Get the height and width of the browser viewport without scrollbars using jquery?

Description

The following will give you the size of the browsers viewport.

Sample

$(window).height();   // returns height of browser viewport
$(window).width();   // returns width of browser viewport

More Information

How can I auto increment the C# assembly version via our CI platform (Hudson)?

Here is an elegant solution that requires a little work upfront when adding a new project but handles the process very easily.

The idea is that each project links to a Solution file that only contains the assembly version information. So your build process only has to update a single file and all of the assembly versions pull from the one file upon compilation.

Steps:

  1. Add a class to you solution file *.cs file, I named min SharedAssemblyProperties.cs
  2. Remove all of the cs information from that new file
  3. Cut the assembly information from an AssemblyInfo file: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
  4. Add the statement "using System.Reflection;" to the file and then paste data into your new cs file (ex SharedAssemblyProperties.cs)
  5. Add an existing item to you project (wait... read on before adding the file)
  6. Select the file and before you click Add, click the dropdown next to the add button and select "Add As Link".
  7. Repeat steps 5 and 6 for all existing and new projects in the solution

When you add the file as a link, it stores the data in the project file and upon compilation pulls the assembly version information from this one file.

In you source control, you add a bat file or script file that simply increments the SharedAssemblyProperties.cs file and all of your projects will update their assembly information from that file.

How do I revert back to an OpenWrt router configuration?

Those who are facing this problem: Don't panic.

Short answer:

Restart your router, and this problem will be fixed. (But if your restart button is not working, you need to do a nine-step process to do the restart. Hitting the restart button is just one of them.)

Long answer: Let's learn how to restart the router.

  1. Set your PC's IP address: 192.168.1.2 and subnetmask 255.255.255.0 and gateway 192.168.1.1
  2. Power off the router
  3. Disconnect the WAN cable
  4. Only connect your PC Ethernet cable to ETH0
  5. Power on the router
  6. Wait for the router to start the boot sequence (SYS LED starts blinking)
  7. When the SYS LED is blinking, hit the restart button (the SYS LED will be blinking at a faster rate means your router is in failsafe mode). (You have to hit the button before the router boots.)
  8. telnet 192.168.1.1
  9. Run these commands:

    mount_root ## this remounts your partitions from read-only to read/write mode
    
    firstboot  ## This will reset your router after reboot
    
    reboot -f ## And force reboot
    
  10. Log in the web interface using web browser.

link to see the official failsafe mode.

Call async/await functions in parallel

I've created a gist testing some different ways of resolving promises, with results. It may be helpful to see the options that work.

How to play a sound in C#, .NET

Code bellow allows to play mp3-files and in-memory wave-files too

player.FileName = "123.mp3";
player.Play();

from http://alvas.net/alvas.audio,samples.aspx#sample6 or

Player pl = new Player();
byte[] arr = File.ReadAllBytes(@"in.wav");
pl.Play(arr);

from http://alvas.net/alvas.audio,samples.aspx#sample7

When should I use curly braces for ES6 import?

I would say there is also a starred notation for the import ES6 keyword worth to mention.

enter image description here

If you try to console log Mix:

import * as Mix from "./A";
console.log(Mix);

You will get:

enter image description here

When should I use curly braces for ES6 import?

The brackets are golden when you need only specific components from the module, which makes smaller footprints for bundlers like webpack.

COALESCE Function in TSQL

I've been told that COALESCE is less costly than ISNULL, but research doesn't indicate that. ISNULL takes only two parameters, the field being evaluated for NULL, and the result you want if it is evaluated as NULL. COALESCE will take any number of parameters, and return the first value encountered that isn't NULL.

There's a much more thorough description of the details here http://www.mssqltips.com/sqlservertip/2689/deciding-between-coalesce-and-isnull-in-sql-server/

mysqli_fetch_array while loop columns

This one was your solution.

$x = 0;
while($row = mysqli_fetch_array($result)) {             
    $posts[$x]['post_id'] = $row['post_id'];
    $posts[$x]['post_title'] = $row['post_title'];
    $posts[$x]['type'] = $row['type'];
    $posts[$x]['author'] = $row['author'];
    $x++;
}

SQL select max(date) and corresponding value

Each MAX function is evaluated individually. So MAX(CompletedDate) will return the value of the latest CompletedDate column and MAX(Notes) will return the maximum (i.e. alphabeticaly highest) value.

You need to structure your query differently to get what you want. This question had actually already been asked and answered several times, so I won't repeat it:

How to find the record in a table that contains the maximum value?

Finding the record with maximum value in SQL

Remove element from JSON Object

To iterate through the keys of an object, use a for .. in loop:

for (var key in json_obj) {
    if (json_obj.hasOwnProperty(key)) {
        // do something with `key'
    }
}

To test all elements for empty children, you can use a recursive approach: iterate through all elements and recursively test their children too.

Removing a property of an object can be done by using the delete keyword:

var someObj = {
    "one": 123,
    "two": 345
};
var key = "one";
delete someObj[key];
console.log(someObj); // prints { "two": 345 }

Documentation:

Can I have onScrollListener for a ScrollView?

Every instance of View calls getViewTreeObserver(). Now when holding an instance of ViewTreeObserver, you can add an OnScrollChangedListener() to it using the method addOnScrollChangedListener().

You can see more information about this class here.

It lets you be aware of every scrolling event - but without the coordinates. You can get them by using getScrollY() or getScrollX() from within the listener though.

scrollView.getViewTreeObserver().addOnScrollChangedListener(new OnScrollChangedListener() {
    @Override
    public void onScrollChanged() {
        int scrollY = rootScrollView.getScrollY(); // For ScrollView
        int scrollX = rootScrollView.getScrollX(); // For HorizontalScrollView
        // DO SOMETHING WITH THE SCROLL COORDINATES
    }
});

Start an external application from a Google Chrome Extension?

You can't launch arbitrary commands, but if your users are willing to go through some extra setup, you can use custom protocols.

E.g. you have the users set things up so that some-app:// links start "SomeApp", and then in my-awesome-extension you open a tab pointing to some-app://some-data-the-app-wants, and you're good to go!

How to find my php-fpm.sock?

Check the config file, the config path is /etc/php5/fpm/pool.d/www.conf, there you'll find the path by config and if you want you can change it.

EDIT:
well you're correct, you need to replace listen = 127.0.0.1:9000 to listen = /var/run/php5-fpm/php5-fpm.sock, then you need to run sudo service php5-fpm restart, and make sure it says that it restarted correctly, if not then make sure that /var/run/ has a folder called php5-fpm, or make it listen to /var/run/php5-fpm.sock cause i don't think the folder inside /var/run is created automatically, i remember i had to edit the start up script to create that folder, otherwise even if you mkdir /var/run/php5-fpm after restart that folder will disappear and the service starting will fail.

How to disable scrolling the document body?

Answer : document.body.scroll = 'no';

Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object

I got this error in react routing, problem was that I was using

<Route path="/" component={<Home/>} exact />

but it was wrong route requires component as a class/function so I changed it to

<Route path="/" component={Home} exact />

and it worked. (Just avoid the braces around the component)

X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode

As it turns out, this has to do with Microsoft's "intelligent" choice to make all intranet sites force to compatibility mode, even if X-UA-Compatible is set to IE=edge.

ORA-12528: TNS Listener: all appropriate instances are blocking new connections. Instance "CLRExtProc", status UNKNOWN

set ORACLE_SID=<YOUR_SID>
sqlplus "/as sysdba"
alter system disable restricted session;

or maybe

shutdown abort;

or maybe

lsnrctl stop

lsnrctl start

How to debug external class library projects in visual studio?

I run two instances of visual studio--one for the external dll and one for the main application.
In the project properties of the external dll, set the following:

Build Events:

  • copy /y "$(TargetDir)$(TargetName).dll" "C:\<path-to-main> \bin\$(ConfigurationName)\$(TargetName).dll"

  • copy /y "$(TargetDir)$(TargetName).pdb" "C:\<path-to-main> \bin\$(ConfigurationName)\$(TargetName).pdb"

Debug:

  • Start external program: C:\<path-to-main>\bin\debug\<AppName>.exe

  • Working Directory C:\<path-to-main>\bin\debug

This way, whenever I build the external dll, it gets updated in the main application's directory. If I hit debug from the external dll's project--the main application runs, but the debugger only hits breakpoints in the external dll. If I hit debug from the main project, the main application runs with the most recently built external dll, but now the debugger only hits breakpoints in the main project.

I realize one debugger will do the job for both, but I find it easier to keep the two straight this way.

PHP how to get the base domain/url?

Step-1

First trim the trailing backslash (/) from the URL. For example, If the URL is http://www.google.com/ then the resultant URL will be http://www.google.com

$url= trim($url, '/');

Step-2

If scheme not included in the URL, then prepend it. So for example if the URL is www.google.com then the resultant URL will be http://www.google.com

if (!preg_match('#^http(s)?://#', $url)) {
    $url = 'http://' . $url;
}

Step-3

Get the parts of the URL.

$urlParts = parse_url($url);

Step-4

Now remove www. from the URL

$domain = preg_replace('/^www\./', '', $urlParts['host']);

Your final domain without http and www is now stored in $domain variable.

Examples:

http://www.google.com => google.com

https://www.google.com => google.com

www.google.com => google.com

http://google.com => google.com

FileSystemWatcher Changed event is raised twice

I spent some significant amount of time using the FileSystemWatcher, and some of the approaches here will not work. I really liked the disabling events approach, but unfortunately, it doesn't work if there is >1 file being dropped, second file will be missed most if not all times. So I use the following approach:

private void EventCallback(object sender, FileSystemEventArgs e)
{
    var fileName = e.FullPath;

    if (!File.Exists(fileName))
    {
        // We've dealt with the file, this is just supressing further events.
        return;
    }

    // File exists, so move it to a working directory. 
    File.Move(fileName, [working directory]);

    // Kick-off whatever processing is required.
}

How do I remove a key from a JavaScript object?

The delete operator allows you to remove a property from an object.

The following examples all do the same thing.

// Example 1
var key = "Cow";
delete thisIsObject[key]; 

// Example 2
delete thisIsObject["Cow"];

// Example 3
delete thisIsObject.Cow;

If you're interested, read Understanding Delete for an in-depth explanation.

Observable Finally on Subscribe

I'm now using RxJS 5.5.7 in an Angular application and using finalize operator has a weird behavior for my use case since is fired before success or error callbacks.

Simple example:

// Simulate an AJAX callback...
of(null)
  .pipe(
    delay(2000),
    finalize(() => {
      // Do some work after complete...
      console.log('Finalize method executed before "Data available" (or error thrown)');
    })
  )
  .subscribe(
      response => {
        console.log('Data available.');
      },
      err => {
        console.error(err);
      }
  );

I have had to use the add medhod in the subscription to accomplish what I want. Basically a finally callback after the success or error callbacks are done. Like a try..catch..finally block or Promise.finally method.

Simple example:

// Simulate an AJAX callback...
of(null)
  .pipe(
    delay(2000)
  )
  .subscribe(
      response => {
        console.log('Data available.');
      },
      err => {
        console.error(err);
      }
  );
  .add(() => {
    // Do some work after complete...
    console.log('At this point the success or error callbacks has been completed.');
  });

Java Date cut off time information

With Joda you can easily get the expected date.

As of version 2.7 (maybe since some previous version greater than 2.2), as a commenter notes, toDateMidnight has been deprecated in favor or the aptly named withTimeAtStartOfDay(), making the convenient

DateTime.now().withTimeAtStartOfDay()

possible.

Benefit added of a way nicer API.

With older versions, you can do

new DateTime(new Date()).toDateMidnight().toDate()

2 column div layout: right column with fixed width, left fluid

Remove the float on the left column.

At the HTML code, the right column needs to come before the left one.

If the right has a float (and a width), and if the left column doesn't have a width and no float, it will be flexible :)

Also apply an overflow: hidden and some height (can be auto) to the outer div, so that it surrounds both inner divs.

Finally, at the left column, add a width: auto and overflow: hidden, this makes the left column independent from the right one (for example, if you resized the browser window, and the right column touched the left one, without these properties, the left column would run arround the right one, with this properties it remains in its space).

Example HTML:

<div class="container">
    <div class="right">
        right content fixed width
    </div>
    <div class="left">
        left content flexible width
    </div>
</div>

CSS:

.container {
   height: auto;
   overflow: hidden;
}

.right {
    width: 180px;
    float: right;
    background: #aafed6;
}

.left {
    float: none; /* not needed, just for clarification */
    background: #e8f6fe;
    /* the next props are meant to keep this block independent from the other floated one */
    width: auto;
    overflow: hidden;
}??

Example here: http://jsfiddle.net/jackJoe/fxWg7/

get dataframe row count based on conditions

For increased performance you should not evaluate the dataframe using your predicate. You can just use the outcome of your predicate directly as illustrated below:

In [1]: import pandas as pd
        import numpy as np
        df = pd.DataFrame(np.random.randn(20,4),columns=list('ABCD'))


In [2]: df.head()
Out[2]:
          A         B         C         D
0 -2.019868  1.227246 -0.489257  0.149053
1  0.223285 -0.087784 -0.053048 -0.108584
2 -0.140556 -0.299735 -1.765956  0.517803
3 -0.589489  0.400487  0.107856  0.194890
4  1.309088 -0.596996 -0.623519  0.020400

In [3]: %time sum((df['A']>0) & (df['B']>0))
CPU times: user 1.11 ms, sys: 53 µs, total: 1.16 ms
Wall time: 1.12 ms
Out[3]: 4

In [4]: %time len(df[(df['A']>0) & (df['B']>0)])
CPU times: user 1.38 ms, sys: 78 µs, total: 1.46 ms
Wall time: 1.42 ms
Out[4]: 4

Keep in mind that this technique only works for counting the number of rows that comply with your predicate.

How to get the first word of a sentence in PHP?

You Can do it using PHP string function substr without conveting string into array.

 $string = 'some text here';
 $stringLength= strlen($string);
 echo ucfirst(substr($string,-$stringLength-1, 1));

//output S

How to downgrade from Internet Explorer 11 to Internet Explorer 10?

  1. Save and close all Internet Explorer windows and then, run Windows Task Manager to end the running processes in background.
  2. Go to Control Panel.
  3. Click Programs and choose the View installed updates instead.
  4. Locate the following Windows Internet Explorer 11 or you can type "Internet Explorer" for a quick search.
  5. Choose the Yes option from the following "Uninstall an update".
  6. Please wait while Windows Internet Explorer 10 is being restored and reconfigured automatically.
  7. Follow the Microsoft Windows wizard to restart your system.

Note: You can do it for as many earlier versions you want, i.e. IE9, IE8 and so on.