Programs & Examples On #Base class

In Object Oriented Programming, a base class is one from which other classes inherit. For example, a child-class `Male` and another child-class `Female` may both inherit from the base-class `Human`.

Does delete on a pointer to a subclass call the base class destructor?

The destructor of A will run when its lifetime is over. If you want its memory to be freed and the destructor run, you have to delete it if it was allocated on the heap. If it was allocated on the stack this happens automatically (i.e. when it goes out of scope; see RAII). If it is a member of a class (not a pointer, but a full member), then this will happen when the containing object is destroyed.

class A
{
    char *someHeapMemory;
public:
    A() : someHeapMemory(new char[1000]) {}
    ~A() { delete[] someHeapMemory; }
};

class B
{
    A* APtr;
public:
    B() : APtr(new A()) {}
    ~B() { delete APtr; }
};

class C
{
    A Amember;
public:
    C() : Amember() {}
    ~C() {} // A is freed / destructed automatically.
};

int main()
{
    B* BPtr = new B();
    delete BPtr; // Calls ~B() which calls ~A() 
    C *CPtr = new C();
    delete CPtr;
    B b;
    C c;
} // b and c are freed/destructed automatically

In the above example, every delete and delete[] is needed. And no delete is needed (or indeed able to be used) where I did not use it.

auto_ptr, unique_ptr and shared_ptr etc... are great for making this lifetime management much easier:

class A
{
    shared_array<char> someHeapMemory;
public:
    A() : someHeapMemory(new char[1000]) {}
    ~A() { } // someHeapMemory is delete[]d automatically
};

class B
{
    shared_ptr<A> APtr;
public:
    B() : APtr(new A()) {}
    ~B() {  } // APtr is deleted automatically
};

int main()
{
    shared_ptr<B> BPtr = new B();
} // BPtr is deleted automatically

Creating a singleton in Python

Method 3 seems to be very neat, but if you want your program to run in both Python 2 and Python 3, it doesn't work. Even protecting the separate variants with tests for the Python version fails, because the Python 3 version gives a syntax error in Python 2.

Thanks to Mike Watkins: http://mikewatkins.ca/2008/11/29/python-2-and-3-metaclasses/. If you want the program to work in both Python 2 and Python 3, you need to do something like:

class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

MC = Singleton('MC', (object), {})

class MyClass(MC):
    pass    # Code for the class implementation

I presume that 'object' in the assignment needs to be replaced with the 'BaseClass', but I haven't tried that (I have tried code as illustrated).

Interface vs Base class

Well, Josh Bloch said himself in Effective Java 2d:

Prefer interfaces over abstract classes

Some main points:

  • Existing classes can be easily retrofitted to implement a new interface. All you have to do is add the required methods if they don’t yet exist and add an implements clause to the class declaration.

  • Interfaces are ideal for defining mixins. Loosely speaking, a mixin is a type that a class can implement in addition to its “primary type” to declare that it provides some optional behavior. For example, Comparable is a mixin interface that allows a class to declare that its instances are ordered with respect to other mutually comparable objects.

  • Interfaces allow the construction of nonhierarchical type frameworks. Type hierarchies are great for organizing some things, but other things don’t fall neatly into a rigid hierarchy.

  • Interfaces enable safe, powerful functionality enhancements via the wrap- per class idiom. If you use abstract classes to define types, you leave the programmer who wants to add functionality with no alternative but to use inheritance.

Moreover, you can combine the virtues of interfaces and abstract classes by providing an abstract skeletal implementation class to go with each nontrivial interface that you export.

On the other hand, interfaces are very hard to evolve. If you add a method to an interface it'll break all of it's implementations.

PS.: Buy the book. It's a lot more detailed.

Is it possible to assign a base class object to a derived class reference with an explicit typecast?

Is it possible to assign a base class object to a derived class reference with an explicit typecast in C#?.

Not only explicit, but also implicit conversions are possible.

C# language doesn't permit such conversion operators, but you can still write them using pure C# and they work. Note that the class which defines the implicit conversion operator (Derived) and the class which uses the operator (Program) must be defined in separate assemblies (e.g. the Derived class is in a library.dll which is referenced by program.exe containing the Program class).

//In library.dll:
public class Base { }

public class Derived {
    [System.Runtime.CompilerServices.SpecialName]
    public static Derived op_Implicit(Base a) {
        return new Derived(a); //Write some Base -> Derived conversion code here
    }

    [System.Runtime.CompilerServices.SpecialName]
    public static Derived op_Explicit(Base a) {
        return new Derived(a); //Write some Base -> Derived conversion code here
    }
}

//In program.exe:
class Program {
    static void Main(string[] args) {
        Derived z = new Base(); //Visual Studio can show squiggles here, but it compiles just fine.
    }
}

When you reference the library using the Project Reference in Visual Studio, VS shows squiggles when you use the implicit conversion, but it compiles just fine. If you just reference the library.dll, there are no squiggles.

Linux: is there a read or recv from socket with timeout?

Here's some simple code to add a time out to your recv function using poll in C:

struct pollfd fd;
int ret;

fd.fd = mySocket; // your socket handler 
fd.events = POLLIN;
ret = poll(&fd, 1, 1000); // 1 second for timeout
switch (ret) {
    case -1:
        // Error
        break;
    case 0:
        // Timeout 
        break;
    default:
        recv(mySocket,buf,sizeof(buf), 0); // get your data
        break;
}

Vue template or render function not defined yet I am using neither?

My previous code was

Vue.component('message', require('./components/message.vue'));

when i got such errors then i just add .default to it and it worked..

Vue.component('message', require('./components/message.vue').default);

Printing image with PrintDocument. how to adjust the image to fit paper size

The solution provided by BBoy works fine. But in my case I had to use

e.Graphics.DrawImage(memoryImage, e.PageBounds);

This will print only the form. When I use MarginBounds it prints the entire screen even if the form is smaller than the monitor screen. PageBounds solved that issue. Thanks to BBoy!

Windows batch: sleep

The Windows 2003 Resource Kit has a sleep batch file. If you ever move up to PowerShell, you can use:

Start-Sleep -s <time to sleep>

Or something like that.

Best way to serialize/unserialize objects in JavaScript?

I've added yet another JavaScript serializer repo to GitHub.

Rather than take the approach of serializing and deserializing JavaScript objects to an internal format the approach here is to serialize JavaScript objects out to native JavaScript. This has the advantage that the format is totally agnostic from the serializer, and the object can be recreated simply by calling eval().

https://github.com/iconico/JavaScript-Serializer

How to get the latest file in a folder?

Try to sort items by creation time. Example below sorts files in a folder and gets first element which is latest.

import glob
import os

files_path = os.path.join(folder, '*')
files = sorted(
    glob.iglob(files_path), key=os.path.getctime, reverse=True) 
print files[0]

Increasing nesting function calls limit

Personally I would suggest this is an error as opposed to a setting that needs adjusting. In my code it was because I had a class that had the same name as a library within one of my controllers and it seemed to trip it up.

Output errors and see where this is being triggered.

Reading local text file into a JavaScript array

Using Node.js

sync mode:

var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")

async mode:

var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
    var textByLine = text.split("\n")
});

UPDATE

As of at least Node 6, readFileSync returns a Buffer, so it must first be converted to a string in order for split to work:

var text = fs.readFileSync("./mytext.txt").toString('utf-8');

Or

var text = fs.readFileSync("./mytext.txt", "utf-8");

Difference between jQuery .hide() and .css("display", "none")

no difference

With no parameters, the .hide() method is the simplest way to hide an element:

$('.target').hide(); The matched elements will be hidden immediately, with no animation. This is roughly equivalent to calling .css('display', 'none'), except that the value of the display property is saved in jQuery's data cache so that display can later be restored to its initial value. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline.

Same about show

How can I check whether an array is null / empty?

Method to check array for null or empty also is present on org.apache.commons.lang:

import org.apache.commons.lang.ArrayUtils;

ArrayUtils.isEmpty(array);

Get name of current class?

You can access it by the class' private attributes:

cls_name = self.__class__.__name__

EDIT:

As said by Ned Batcheler, this wouldn't work in the class body, but it would in a method.

Check if element found in array c++

C++ has NULL as well, often the same as 0 (pointer to address 0x00000000).

Do you use NULL or 0 (zero) for pointers in C++?

So in C++ that null check would be:

 if (!foo)
    cout << "not found";

Filtering a pyspark dataframe using isin by exclusion

Got a gotcha for those with their headspace in Pandas and moving to pyspark

 from pyspark import SparkConf, SparkContext
 from pyspark.sql import SQLContext

 spark_conf = SparkConf().setMaster("local").setAppName("MyAppName")
 sc = SparkContext(conf = spark_conf)
 sqlContext = SQLContext(sc)

 records = [
     {"colour": "red"},
     {"colour": "blue"},
     {"colour": None},
 ]

 pandas_df = pd.DataFrame.from_dict(records)
 pyspark_df = sqlContext.createDataFrame(records)

So if we wanted the rows that are not red:

pandas_df[~pandas_df["colour"].isin(["red"])]

As expected in Pandas

Looking good, and in our pyspark DataFrame

pyspark_df.filter(~pyspark_df["colour"].isin(["red"])).collect()

Not what I expected

So after some digging, I found this: https://issues.apache.org/jira/browse/SPARK-20617 So to include nothingness in our results:

pyspark_df.filter(~pyspark_df["colour"].isin(["red"]) | pyspark_df["colour"].isNull()).show()

much ado about nothing

How can I pass variable to ansible playbook in the command line?

ansible-playbook release.yml --extra-vars "username=hello password=bye"

#you can now use the above command anywhere in the playbook as an example below:
tasks:
- name: Create a new user in Linux
shell: useradd -m -p {{username}} {{password}}"

How to get HTTP response code for a URL in Java?

This is what worked for me:

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class UrlHelpers {

    public static int getHTTPResponseStatusCode(String u) throws IOException {

        URL url = new URL(u);
        HttpURLConnection http = (HttpURLConnection)url.openConnection();
        return http.getResponseCode();
    }
}

Hope this helps someone :)

What does {0} mean when found in a string in C#?

In addition to the value you wish to print, the {0} {1}, etc., you can specify a format. For example, {0,4} will be a value that is padded to four spaces.

There are a number of built-in format specifiers, and in addition, you can make your own. For a decent tutorial/list see String Formatting in C#. Also, there is a FAQ here.

Read Variable from Web.Config

Assuming the key is contained inside the <appSettings> node:

ConfigurationSettings.AppSettings["theKey"];

As for "writing" - put simply, dont.

The web.config is not designed for that, if you're going to be changing a value constantly, put it in a static helper class.

Element count of an array in C++

First off, you can circumvent that problem by using std::vector instead of an array. Second, if you put objects of a derived class into an array of a super class, you will experience slicing, but the good news is, your formula will work. Polymorphic collections in C++ are achieved using pointers. There are three major options here:

How to read strings from a Scanner in a Java console application?

Replace:

System.out.println("Enter EmployeeName:");
                 ename=(scanner.next());

with:

System.out.println("Enter EmployeeName:");
                 ename=(scanner.nextLine());

This is because next() grabs only the next token, and the space acts as a delimiter between the tokens. By this, I mean that the scanner reads the input: "firstname lastname" as two separate tokens. So in your example, ename would be set to firstname and the scanner is attempting to set the supervisorId to lastname

Send JSON data from Javascript to PHP?

Simple example on JavaScript for HTML input-fields (sending to server JSON, parsing JSON in PHP and sending back to client) using AJAX:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<body>
<div align="center">
    <label for="LName">Last Name</label>
    <input type="text" class="form-control" name="LName" id="LName" maxlength="15"
           placeholder="Last name"/>
</div>
<br/>

<div align="center">
    <label for="Age">Age</label>
    <input type="text" class="form-control" name="Age" id="Age" maxlength="3"
           placeholder="Age"/>
</div>
<br/>

<div align="center">
    <button type="submit" name="submit_show" id="submit_show" value="show" onclick="actionSend()">Show
    </button>
</div>

<div id="result">
</div>

<script>
    var xmlhttp;

    function actionSend() {
        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        var values = $("input").map(function () {
            return $(this).val();
        }).get();
        var myJsonString = JSON.stringify(values);
        xmlhttp.onreadystatechange = respond;
        xmlhttp.open("POST", "ajax-test.php", true);
        xmlhttp.send(myJsonString);
    }

    function respond() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById('result').innerHTML = xmlhttp.responseText;
        }
    }

</script>

</body>
</html>

PHP file ajax-test.php :

<?php

$str_json = file_get_contents('php://input'); //($_POST doesn't work here)
$response = json_decode($str_json, true); // decoding received JSON to array

$lName = $response[0];
$age = $response[1];

echo '
<div align="center">
<h5> Received data: </h5>
<table border="1" style="border-collapse: collapse;">
 <tr> <th> First Name</th> <th> Age</th> </tr>
 <tr>
 <td> <center> '.$lName.'<center></td>
 <td> <center> '.$age.'</center></td>
 </tr>
 </table></div>
 ';
?>

Decimal to Hexadecimal Converter in Java

Another possible solution:

public String DecToHex(int dec){
  char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
              'A', 'B', 'C', 'D', 'E', 'F'};
  String hex = "";
  while (dec != 0) {
      int rem = dec % 16;
      hex = hexDigits[rem] + hex;
      dec = dec / 16;
  }
  return hex;
}

App installation failed due to application-identifier entitlement

I encountered this issue because I built to the phone with my code signing turned off from another machine, so you need to uninstall the app from the phone before installing/building to the phone with code signing on.

How to request Location Permission at runtime

This code work for me. I also handled case "Never Ask Me"

In AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

In build.gradle (Module: app)

dependencies {
    ....
    implementation "com.google.android.gms:play-services-location:16.0.0"
}

This is CurrentLocationManager.kt

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.IntentSender
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.os.CountDownTimer
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.util.Log
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.common.api.CommonStatusCodes
import com.google.android.gms.common.api.ResolvableApiException
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationServices
import com.google.android.gms.location.LocationSettingsRequest
import com.google.android.gms.location.LocationSettingsStatusCodes
import java.lang.ref.WeakReference


object CurrentLocationManager : LocationListener {

    const val REQUEST_CODE_ACCESS_LOCATION = 123

    fun checkLocationPermission(activity: Activity) {
        if (ContextCompat.checkSelfPermission(
                activity,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                activity,
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                REQUEST_CODE_ACCESS_LOCATION
            )
        } else {
            Thread(Runnable {
                // Moves the current Thread into the background
                android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND)
                //
                requestLocationUpdates(activity)
            }).start()
        }
    }

    /**
     * be used in HomeActivity.
     */
    const val REQUEST_CHECK_SETTINGS = 55
    /**
     * The number of millis in the future from the call to start().
     * until the countdown is done and onFinish() is called.
     *
     *
     * It is also the interval along the way to receive onTick(long) callbacks.
     */
    private const val TWENTY_SECS: Long = 20000
    /**
     * Timer to get location from history when requestLocationUpdates don't return result.
     */
    private var mCountDownTimer: CountDownTimer? = null
    /**
     * WeakReference of current activity.
     */
    private var mWeakReferenceActivity: WeakReference<Activity>? = null
    /**
     * user's location.
     */
    var currentLocation: Location? = null

    @Synchronized
    fun requestLocationUpdates(activity: Activity) {
        if (mWeakReferenceActivity == null) {
            mWeakReferenceActivity = WeakReference(activity)
        } else {
            mWeakReferenceActivity?.clear()
            mWeakReferenceActivity = WeakReference(activity)
        }
        //create location request: https://developer.android.com/training/location/change-location-settings.html#prompt
        val mLocationRequest = LocationRequest()
        // Which your app prefers to receive location updates. Note that the location updates may be
        // faster than this rate, or slower than this rate, or there may be no updates at all
        // (if the device has no connectivity)
        mLocationRequest.interval = 20000
        //This method sets the fastest rate in milliseconds at which your app can handle location updates.
        // You need to set this rate because other apps also affect the rate at which updates are sent
        mLocationRequest.fastestInterval = 10000
        mLocationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY

        //Get Current Location Settings
        val builder = LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest)
        //Next check whether the current location settings are satisfied
        val client = LocationServices.getSettingsClient(activity)
        val task = client.checkLocationSettings(builder.build())
        //Prompt the User to Change Location Settings
        task.addOnSuccessListener(activity) {
            Log.d("CurrentLocationManager", "OnSuccessListener")
            // All location settings are satisfied. The client can initialize location requests here.
            // If it's failed, the result after user updated setting is sent to onActivityResult of HomeActivity.
            val activity1 = mWeakReferenceActivity?.get()
            if (activity1 != null) {
                startRequestLocationUpdate(activity1.applicationContext)
            }
        }

        task.addOnFailureListener(activity) { e ->
            Log.d("CurrentLocationManager", "addOnFailureListener")
            val statusCode = (e as ApiException).statusCode
            when (statusCode) {
                CommonStatusCodes.RESOLUTION_REQUIRED ->
                    // Location settings are not satisfied, but this can be fixed
                    // by showing the user a dialog.
                    try {
                        val activity1 = mWeakReferenceActivity?.get()
                        if (activity1 != null) {
                            // Show the dialog by calling startResolutionForResult(),
                            // and check the result in onActivityResult().
                            val resolvable = e as ResolvableApiException
                            resolvable.startResolutionForResult(
                                activity1, REQUEST_CHECK_SETTINGS
                            )
                        }
                    } catch (sendEx: IntentSender.SendIntentException) {
                        // Ignore the error.
                        sendEx.printStackTrace()
                    }

                LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE -> {
                    // Location settings are not satisfied. However, we have no way
                    // to fix the settings so we won't show the dialog.
                }
            }
        }
    }

    fun startRequestLocationUpdate(appContext: Context) {
        val mLocationManager = appContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        if (ActivityCompat.checkSelfPermission(
                appContext.applicationContext,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            //Utilities.showProgressDialog(mWeakReferenceActivity.get());
            if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                mLocationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, 10000, 0f, this
                )
            } else {
                mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, 10000, 0f, this
                )
            }
        }

        /*Timer to call getLastKnownLocation() when requestLocationUpdates don 't return result*/
        countDownUpdateLocation()
    }

    override fun onLocationChanged(location: Location?) {
        if (location != null) {
            stopRequestLocationUpdates()
            currentLocation = location
        }
    }

    override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {

    }

    override fun onProviderEnabled(provider: String) {

    }

    override fun onProviderDisabled(provider: String) {

    }

    /**
     * Init CountDownTimer to to get location from history when requestLocationUpdates don't return result.
     */
    @Synchronized
    private fun countDownUpdateLocation() {
        mCountDownTimer?.cancel()
        mCountDownTimer = object : CountDownTimer(TWENTY_SECS, TWENTY_SECS) {
            override fun onTick(millisUntilFinished: Long) {}

            override fun onFinish() {
                if (mWeakReferenceActivity != null) {
                    val activity = mWeakReferenceActivity?.get()
                    if (activity != null && ActivityCompat.checkSelfPermission(
                            activity,
                            Manifest.permission.ACCESS_FINE_LOCATION
                        ) == PackageManager.PERMISSION_GRANTED
                    ) {
                        val location = (activity.applicationContext
                            .getSystemService(Context.LOCATION_SERVICE) as LocationManager)
                            .getLastKnownLocation(LocationManager.PASSIVE_PROVIDER)
                        stopRequestLocationUpdates()
                        onLocationChanged(location)
                    } else {
                        stopRequestLocationUpdates()
                    }
                } else {
                    mCountDownTimer?.cancel()
                    mCountDownTimer = null
                }
            }
        }.start()
    }

    /**
     * The method must be called in onDestroy() of activity to
     * removeUpdateLocation and cancel CountDownTimer.
     */
    fun stopRequestLocationUpdates() {
        val activity = mWeakReferenceActivity?.get()
        if (activity != null) {
            /*if (ActivityCompat.checkSelfPermission(activity,
                    Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {*/
            (activity.applicationContext
                .getSystemService(Context.LOCATION_SERVICE) as LocationManager).removeUpdates(this)
            /*}*/
        }
        mCountDownTimer?.cancel()
        mCountDownTimer = null
    }
}

In MainActivity.kt

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
...
CurrentLocationManager.checkLocationPermission(this@LoginActivity)
}

override fun onDestroy() {
        CurrentLocationManager.stopRequestLocationUpdates()
        super.onDestroy()
    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == CurrentLocationManager.REQUEST_CODE_ACCESS_LOCATION) {
            if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                //denied
                val builder = AlertDialog.Builder(this)
                builder.setMessage("We need permission to use your location for the purpose of finding friends near you.")
                    .setTitle("Device Location Required")
                    .setIcon(com.eswapp.R.drawable.ic_info)
                    .setPositiveButton("OK") { _, _ ->
                        if (ActivityCompat.shouldShowRequestPermissionRationale(
                                this,
                                Manifest.permission.ACCESS_FINE_LOCATION
                            )
                        ) {
                            //only deny
                            CurrentLocationManager.checkLocationPermission(this@LoginActivity)
                        } else {
                            //never ask again
                            val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                            val uri = Uri.fromParts("package", packageName, null)
                            intent.data = uri
                            startActivityForResult(intent, CurrentLocationManager.REQUEST_CHECK_SETTINGS)
                        }
                    }
                    .setNegativeButton("Ask Me Later") { _, _ ->

                    }
                // Create the AlertDialog object and return it
                val dialog = builder.create()
                dialog.show()
            } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                CurrentLocationManager.requestLocationUpdates(this)
            }
        }
    }

    //Forward Login result to the CallBackManager in OnActivityResult()
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        when (requestCode) {
            //case 1. After you allow the app access device location, Another dialog will be displayed to request you to turn on device location
            //case 2. Or You chosen Never Ask Again, you open device Setting and enable location permission
            CurrentLocationManager.REQUEST_CHECK_SETTINGS -> when (resultCode) {
                RESULT_OK -> {
                    Log.d("REQUEST_CHECK_SETTINGS", "RESULT_OK")
                    //case 1. You choose OK
                    CurrentLocationManager.startRequestLocationUpdate(applicationContext)
                }
                RESULT_CANCELED -> {
                    Log.d("REQUEST_CHECK_SETTINGS", "RESULT_CANCELED")
                    //case 1. You choose NO THANKS
                    //CurrentLocationManager.requestLocationUpdates(this)

                    //case 2. In device Setting screen: user can enable or not enable location permission,
                    // so when user back to this activity, we should re-call checkLocationPermission()
                    CurrentLocationManager.checkLocationPermission(this@LoginActivity)
                }
                else -> {
                    //do nothing
                }
            }
            else -> {
                super.onActivityResult(requestCode, resultCode, data)
            }
        }
    }

Datagridview: How to set a cell in editing mode?

Setting the CurrentCell and then calling BeginEdit(true) works well for me.

The following code shows an eventHandler for the KeyDown event that sets a cell to be editable.

My example only implements one of the required key press overrides but in theory the others should work the same. (and I'm always setting the [0][0] cell to be editable but any other cell should work)

    private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Tab && dataGridView1.CurrentCell.ColumnIndex == 1)
        {
            e.Handled = true;
            DataGridViewCell cell = dataGridView1.Rows[0].Cells[0];
            dataGridView1.CurrentCell = cell;
            dataGridView1.BeginEdit(true);               
        }
    }

If you haven't found it previously, the DataGridView FAQ is a great resource, written by the program manager for the DataGridView control, which covers most of what you could want to do with the control.

Make a div into a link

My smarty pants answer:

"Evasive answer to: "How to make block level element a hyperlink and validate in XHTML 1.1"

Just use HTML5 DOCTYPE DTD."

Didn't actually hold true for ie7

onclick="location.href='page.html';"

Works IE7-9, Chrome, Safari, Firefox,

Python 2.7.10 error "from urllib.request import urlopen" no module named request

Change

from urllib.request import urlopen

to

from urllib import urlopen

I was able to solve this problem by changing like this. For Python2.7 in macOS10.14

How good is Java's UUID.randomUUID?

Many of the answers discuss how many UUIDs would have to be generated to reach a 50% chance of a collision. But a 50%, 25%, or even 1% chance of collision is worthless for an application where collision must be (virtually) impossible.

Do programmers routinely dismiss as "impossible" other events that can and do occur?

When we write data to a disk or memory and read it back again, we take for granted that the data are correct. We rely on the device's error correction to detect any corruption. But the chance of undetected errors is actually around 2-50.

Wouldn't it make sense to apply a similar standard to random UUIDs? If you do, you will find that an "impossible" collision is possible in a collection of around 100 billion random UUIDs (236.5).

This is an astronomical number, but applications like itemized billing in a national healthcare system, or logging high frequency sensor data on a large array of devices could definitely bump into these limits. If you are writing the next Hitchhiker's Guide to the Galaxy, don't try to assign UUIDs to each article!

Clear Cache in Android Application programmatically

If you are looking for delete cache of your own application then simply delete your cache directory and its all done !

public static void deleteCache(Context context) {
    try {
        File dir = context.getCacheDir();
        deleteDir(dir);
    } catch (Exception e) { e.printStackTrace();}
}

public static boolean deleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
        return dir.delete();
    } else if(dir!= null && dir.isFile()) {
        return dir.delete();
    } else {
        return false;
    }
}

Automatic prune with Git fetch or pull

git config --global fetch.prune true

To always --prune for git fetch and git pull in all your Git repositories:

git config --global fetch.prune true

This above command appends in your global Git configuration (typically ~/.gitconfig) the following lines. Use git config -e --global to view your global configuration.

[fetch]
    prune = true

git config remote.origin.prune true

To always --prune but from one single repository:

git config remote.origin.prune true
                 #^^^^^^
                 #replace with your repo name

This above command adds in your local Git configuration (typically .git/config) the below last line. Use git config -e to view your local configuration.

[remote "origin"]
    url = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    fetch = +refs/heads/*:refs/remotes/origin/*
    prune = true

You can also use --global within the second command or use instead --local within the first command.


git config --global gui.pruneDuringFetch true

If you use git gui you may also be interested by:

git config --global gui.pruneDuringFetch true

that appends:

[gui]
    pruneDuringFetch = true

References

The corresponding documentations from git help config:

--global

  For writing options: write to global ~/.gitconfig file rather than the repository .git/config, write to $XDG_CONFIG_HOME/git/config file if this file exists and the ~/.gitconfig file doesn’t.

 

--local

  For writing options: write to the repository .git/config file. This is the default behavior.

 

fetch.prune

  If true, fetch will automatically behave as if the --prune option was given on the command line. See also remote.<name>.prune.

 

gui.pruneDuringFetch

  "true" if git-gui should prune remote-tracking branches when performing a fetch. The default value is "false".

 

remote.<name>.prune

  When set to true, fetching from this remote by default will also remove any remote-tracking references that no longer exist on the remote (as if the --prune option was given on the command line). Overrides fetch.prune settings, if any.

Get google map link with latitude/longitude

I've tried doing the request you need using an iframe to show the result for latitude, longitude, and zoom needed:

<iframe 
  width="300" 
  height="170" 
  frameborder="0" 
  scrolling="no" 
  marginheight="0" 
  marginwidth="0" 
  src="https://maps.google.com/maps?q='+YOUR_LAT+','+YOUR_LON+'&hl=es&z=14&amp;output=embed"
 >
 </iframe>
 <br />
 <small>
   <a 
    href="https://maps.google.com/maps?q='+data.lat+','+data.lon+'&hl=es;z=14&amp;output=embed" 
    style="color:#0000FF;text-align:left" 
    target="_blank"
   >
     See map bigger
   </a>
 </small>

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

From Node.js http.request API Docs you could use something similar to

var http = require('http');

var request = http.request({'hostname': 'www.example.com',
                            'auth': 'user:password'
                           }, 
                           function (response) {
                             console.log('STATUS: ' + response.statusCode);
                             console.log('HEADERS: ' + JSON.stringify(response.headers));
                             response.setEncoding('utf8');
                             response.on('data', function (chunk) {
                               console.log('BODY: ' + chunk);
                             });
                           });
request.end();

Utilizing multi core for tar+gzip/bzip compression/decompression

Common approach

There is option for tar program:

-I, --use-compress-program PROG
      filter through PROG (must accept -d)

You can use multithread version of archiver or compressor utility.

Most popular multithread archivers are pigz (instead of gzip) and pbzip2 (instead of bzip2). For instance:

$ tar -I pbzip2 -cf OUTPUT_FILE.tar.bz2 paths_to_archive
$ tar --use-compress-program=pigz -cf OUTPUT_FILE.tar.gz paths_to_archive

Archiver must accept -d. If your replacement utility hasn't this parameter and/or you need specify additional parameters, then use pipes (add parameters if necessary):

$ tar cf - paths_to_archive | pbzip2 > OUTPUT_FILE.tar.gz
$ tar cf - paths_to_archive | pigz > OUTPUT_FILE.tar.gz

Input and output of singlethread and multithread are compatible. You can compress using multithread version and decompress using singlethread version and vice versa.

p7zip

For p7zip for compression you need a small shell script like the following:

#!/bin/sh
case $1 in
  -d) 7za -txz -si -so e;;
   *) 7za -txz -si -so a .;;
esac 2>/dev/null

Save it as 7zhelper.sh. Here the example of usage:

$ tar -I 7zhelper.sh -cf OUTPUT_FILE.tar.7z paths_to_archive
$ tar -I 7zhelper.sh -xf OUTPUT_FILE.tar.7z

xz

Regarding multithreaded XZ support. If you are running version 5.2.0 or above of XZ Utils, you can utilize multiple cores for compression by setting -T or --threads to an appropriate value via the environmental variable XZ_DEFAULTS (e.g. XZ_DEFAULTS="-T 0").

This is a fragment of man for 5.1.0alpha version:

Multithreaded compression and decompression are not implemented yet, so this option has no effect for now.

However this will not work for decompression of files that haven't also been compressed with threading enabled. From man for version 5.2.2:

Threaded decompression hasn't been implemented yet. It will only work on files that contain multiple blocks with size information in block headers. All files compressed in multi-threaded mode meet this condition, but files compressed in single-threaded mode don't even if --block-size=size is used.

Recompiling with replacement

If you build tar from sources, then you can recompile with parameters

--with-gzip=pigz
--with-bzip2=lbzip2
--with-lzip=plzip

After recompiling tar with these options you can check the output of tar's help:

$ tar --help | grep "lbzip2\|plzip\|pigz"
  -j, --bzip2                filter the archive through lbzip2
      --lzip                 filter the archive through plzip
  -z, --gzip, --gunzip, --ungzip   filter the archive through pigz

DateTime to javascript date

Another late answer, but this is missing here. If you want to handle conversion of serialized /Date(1425408717000)/ in javascript, you can simply call:

var cSharpDate = "/Date(1425408717000)/"
var jsDate = new Date(parseInt(cSharpDate.replace(/[^0-9 +]/g, '')));

Source: amirsahib

VS2010 How to include files in project, to copy them to build output directory automatically during build or publish

  1. Add the file to your project.
  2. Go to the Properties of that file.
  3. Set "Build Action" to Embedded Resource.
  4. Set "Copy to Output Directory" to Copy Always.

What does the 'standalone' directive mean in XML?

standalone describes if the current XML document depends on an external markup declaration.

W3C describes its purpose in "Extensible Markup Language (XML) 1.0 (Fifth Edition)":

Test if numpy array contains only zeros

As another answer says, you can take advantage of truthy/falsy evaluations if you know that 0 is the only falsy element possibly in your array. All elements in an array are falsy iff there are not any truthy elements in it.*

>>> a = np.zeros(10)
>>> not np.any(a)
True

However, the answer claimed that any was faster than other options due partly to short-circuiting. As of 2018, Numpy's all and any do not short-circuit.

If you do this kind of thing often, it's very easy to make your own short-circuiting versions using numba:

import numba as nb

# short-circuiting replacement for np.any()
@nb.jit(nopython=True)
def sc_any(array):
    for x in array.flat:
        if x:
            return True
    return False

# short-circuiting replacement for np.all()
@nb.jit(nopython=True)
def sc_all(array):
    for x in array.flat:
        if not x:
            return False
    return True

These tend to be faster than Numpy's versions even when not short-circuiting. count_nonzero is the slowest.

Some input to check performance:

import numpy as np

n = 10**8
middle = n//2
all_0 = np.zeros(n, dtype=int)
all_1 = np.ones(n, dtype=int)
mid_0 = np.ones(n, dtype=int)
mid_1 = np.zeros(n, dtype=int)
np.put(mid_0, middle, 0)
np.put(mid_1, middle, 1)
# mid_0 = [1 1 1 ... 1 0 1 ... 1 1 1]
# mid_1 = [0 0 0 ... 0 1 0 ... 0 0 0]

Check:

## count_nonzero
%timeit np.count_nonzero(all_0) 
# 220 ms ± 8.73 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit np.count_nonzero(all_1)
# 150 ms ± 4.56 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

### all
# np.all
%timeit np.all(all_1)
%timeit np.all(mid_0)
%timeit np.all(all_0)
# 56.8 ms ± 3.41 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 57.4 ms ± 1.76 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 55.9 ms ± 2.13 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

# sc_all
%timeit sc_all(all_1)
%timeit sc_all(mid_0)
%timeit sc_all(all_0)
# 44.4 ms ± 2.49 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 22.7 ms ± 599 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 288 ns ± 6.36 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

### any
# np.any
%timeit np.any(all_0)
%timeit np.any(mid_1)
%timeit np.any(all_1)
# 60.7 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 60 ms ± 287 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 57.7 ms ± 1.12 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

# sc_any
%timeit sc_any(all_0)
%timeit sc_any(mid_1)
%timeit sc_any(all_1)
# 41.7 ms ± 1.24 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 22.4 ms ± 1.51 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 287 ns ± 12.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

* Helpful all and any equivalences:

np.all(a) == np.logical_not(np.any(np.logical_not(a)))
np.any(a) == np.logical_not(np.all(np.logical_not(a)))
not np.all(a) == np.any(np.logical_not(a))
not np.any(a) == np.all(np.logical_not(a))

Redirect Windows cmd stdout and stderr to a single file

In a batch file (Windows 7 and above) I found this method most reliable

Call :logging >"C:\Temp\NAME_Your_Log_File.txt" 2>&1
:logging
TITLE "Logging Commands"
ECHO "Read this output in your log file"
ECHO ..
Prompt $_
COLOR 0F

Obviously, use whatever commands you want and the output will be directed to the text file. Using this method is reliable HOWEVER there is NO output on the screen.

Print out the values of a (Mat) matrix in OpenCV C++

See the first answer to Accessing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++
Then just loop over all the elements in cout << M.at<double>(0,0); rather than just 0,0

Or better still with the C++ interface:

cv::Mat M;
cout << "M = " << endl << " "  << M << endl << endl;

Auto Increment after delete in MySQL

if($id == 1){ // deleting first row
            mysqli_query($db,"UPDATE employees  SET id=id-1 WHERE id>1");
        }
        else if($id>1 && $id<$num){ // deleting middle row
            mysqli_query($db,"UPDATE employees  SET id=id-1 WHERE id>$id");
        }
        else if($id == $num){ // deleting last row
            mysqli_query($db,"ALTER TABLE employees AUTO_INCREMENT = $num");
        }
        else{
            echo "ERROR";
        }

        mysqli_query($db,"ALTER TABLE employees AUTO_INCREMENT = $num");

How can I make a program wait for a variable change in javascript?

JavaScript interpreters are single threaded, so a variable can never change, when the code is waiting in some other code that does not change the variable.

In my opinion it would be the best solution to wrap the variable in some kind of object that has a getter and setter function. You can then register a callback function in the object that is called when the setter function of the object is called. You can then use the getter function in the callback to retrieve the current value:

function Wrapper(callback) {
    var value;
    this.set = function(v) {
        value = v;
        callback(this);
    }
    this.get = function() {
        return value;
    }  
}

This could be easily used like this:

<html>
<head>
<script type="text/javascript" src="wrapper.js"></script>
<script type="text/javascript">
function callback(wrapper) {
    alert("Value is now: " + wrapper.get());
}

wrapper = new Wrapper(callback);
</script>
</head>
<body>
    <input type="text" onchange="wrapper.set(this.value)"/>
</body>
</html>

How can I clone a JavaScript object except for one key?

If you use Ramda you can use its omit and clone functions to make a deep clone of your object and omit the unnecessary fields.

var object = {a: 1, b: 2, c: 3, y:25, z:26};
R.clone(R.omit(["z", "y"], object));

Check if checkbox is NOT checked on click - jQuery

The Answer already posted .But We can use the jquery in this way also

demo

$(function(){
    $('#check1').click(function() {
        if($('#check1').attr('checked'))
            alert('checked');
        else
            alert('unchecked');
    });

    $('#check2').click(function() {
        if(!$('#check2').attr('checked'))
            alert('unchecked');
        else
            alert('checked');
    });
});

WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server

If you are on Windows 7 or 8 then Apache might be seeing the connections coming from "::1" which is the IPv6 equivalent of 127.0.0.1.

You can check this by looking in the Apache Access Log (reachable from the WAMP menu)

::1 - - [20/Dec/2012:21:35:04 +0000] "GET /phpmyadmin/ HTTP/1.1" 403 213

The ::1 at the start is the clients address. The 403 at the end is the Access Denied code.

The answers above will remove all restrictions and open phpmyadmin to all, but if you still want to restrict phpmyadmin to your machine only (generally a good idea) then under the line...

Allow from 127.0.0.1

..add the following:

Allow from ::1

(edit: Added suggestion from Nukeface)

How do I add BundleConfig.cs to my project?

BundleConfig is nothing more than bundle configuration moved to separate file. It used to be part of app startup code (filters, bundles, routes used to be configured in one class)

To add this file, first you need to add the Microsoft.AspNet.Web.Optimization nuget package to your web project:

Install-Package Microsoft.AspNet.Web.Optimization

Then under the App_Start folder create a new cs file called BundleConfig.cs. Here is what I have in my mine (ASP.NET MVC 5, but it should work with MVC 4):

using System.Web;
using System.Web.Optimization;

namespace CodeRepository.Web
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));
        }
    }
}

Then modify your Global.asax and add a call to RegisterBundles() in Application_Start():

using System.Web.Optimization;

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

A closely related question: How to add reference to System.Web.Optimization for MVC-3-converted-to-4 app

Detect click outside React component

If you want to use a tiny component (466 Byte gzipped) that already exists for this functionality then you can check out this library react-outclick. It captures events outside of a react component or jsx element.

The good thing about the library is that it also lets you detect clicks outside of a component and inside of another. It also supports detecting other types of events.

How SID is different from Service name in Oracle tnsnames.ora

what is a SID and Service name

please look into oracle's documentation at https://docs.oracle.com/cd/B19306_01/network.102/b14212/concepts.htm

In case if the above link is not accessable in future, At the time time of writing this answer, the above link will direct you to, "Database Service and Database Instance Identification" topic in Connectivity Concepts chapter of "Database Net Services Administrator's Guide". This guide is published by oracle as part of "Oracle Database Online Documentation, 10g Release 2 (10.2)"

When I have to use one or another? Why do I need two of them?

Consider below mapping in a RAC Environment,

SID      SERVICE_NAME
bob1    bob
bob2    bob
bob3    bob
bob4    bob

if load balancing is configured, the listener will 'balance' the workload across all four SIDs. Even if load balancing is configured, you can connect to bob1 all the time if you want to by using the SID instead of SERVICE_NAME.

Please refer, https://community.oracle.com/thread/4049517

Parsing Json rest api response in C#

  1. Create classes that match your data,
  2. then use JSON.NET to convert the JSON data to regular C# objects.

Step 1: a great tool - http://json2csharp.com/ - the results generated by it are below

Step 2: JToken.Parse(...).ToObject<RootObject>().

public class Meta
{
    public int code { get; set; }
    public string status { get; set; }
    public string method_name { get; set; }
}

public class Photos
{
    public int total_count { get; set; }
}

public class Storage
{
    public int used { get; set; }
}

public class Stats
{
    public Photos photos { get; set; }
    public Storage storage { get; set; }
}

public class From
{
    public string id { get; set; }
    public string first_name { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public List<object> external_accounts { get; set; }
    public string email { get; set; }
    public string confirmed_at { get; set; }
    public string username { get; set; }
    public string admin { get; set; }
    public Stats stats { get; set; }
}

public class ParticipateUser
{
    public string id { get; set; }
    public string first_name { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public List<object> external_accounts { get; set; }
    public string email { get; set; }
    public string confirmed_at { get; set; }
    public string username { get; set; }
    public string admin { get; set; }
    public Stats stats { get; set; }
}

public class ChatGroup
{
    public string id { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public string message { get; set; }
    public List<ParticipateUser> participate_users { get; set; }
}

public class Chat
{
    public string id { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public string message { get; set; }
    public From from { get; set; }
    public ChatGroup chat_group { get; set; }
}

public class Response
{
    public List<Chat> chats { get; set; }
}

public class RootObject
{
    public Meta meta { get; set; }
    public Response response { get; set; }
}

How to disable margin-collapsing?

In newer browser (excluding IE11), a simple solution to prevent parent-child margin collapsing is to use display: flow-root. However, you would still need other techniques to prevent adjacent element collapsing.

DEMO (before)

_x000D_
_x000D_
.parent {_x000D_
  background-color: grey;_x000D_
}_x000D_
_x000D_
.child {_x000D_
  height: 16px;_x000D_
  margin-top: 16px;_x000D_
  margin-bottom: 16px;_x000D_
  background-color: blue;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

DEMO (after)

_x000D_
_x000D_
.parent {_x000D_
  display: flow-root;_x000D_
  background-color: grey;_x000D_
}_x000D_
_x000D_
.child {_x000D_
  height: 16px;_x000D_
  margin-top: 16px;_x000D_
  margin-bottom: 16px;_x000D_
  background-color: blue;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Detect if PHP session exists

The original code is from Sabry Suleiman.

Made it a bit prettier:

function is_session_started() {

    if ( php_sapi_name() === 'cli' )
        return false;

    return version_compare( phpversion(), '5.4.0', '>=' )
        ? session_status() === PHP_SESSION_ACTIVE
        : session_id() !== '';
}

First condition checks the Server API in use. If Command Line Interface is used, the function returns false.

Then we return the boolean result depending on the PHP version in use.

In ancient history you simply needed to check session_id(). If it's an empty string, then session is not started. Otherwise it is.

Since 5.4 to at least the current 8.0 the norm is to check session_status(). If it's not PHP_SESSION_ACTIVE, then either the session isn't started yet (PHP_SESSION_NONE) or sessions are not available altogether (PHP_SESSION_DISABLED).

How to send emails from my Android application?

I solved this issue with simple lines of code as the android documentation explains.

(https://developer.android.com/guide/components/intents-common.html#Email)

The most important is the flag: it is ACTION_SENDTO, and not ACTION_SEND

The other important line is

intent.setData(Uri.parse("mailto:")); ***// only email apps should handle this***

By the way, if you send an empty Extra, the if() at the end won't work and the app won't launch the email client.

According to Android documentation. If you want to ensure that your intent is handled only by an email app (and not other text messaging or social apps), then use the ACTION_SENDTO action and include the "mailto:" data scheme. For example:

public void composeEmail(String[] addresses, String subject) {
    Intent intent = new Intent(Intent.ACTION_SENDTO);
    intent.setData(Uri.parse("mailto:")); // only email apps should handle this
    intent.putExtra(Intent.EXTRA_EMAIL, addresses);
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

Cannot find or open the PDB file in Visual Studio C++ 2010

Working with VS 2013.
Try the following Tools -> Options -> Debugging -> Output Window -> Module Load Messages -> Off

It will disable the display of modules loaded.

jquery loop on Json data using $.each

getJSON will evaluate the data to JSON for you, as long as the correct content-type is used. Make sure that the server is returning the data as application/json.

Why is printing "B" dramatically slower than printing "#"?

Pure speculation is that you're using a terminal that attempts to do word-wrapping rather than character-wrapping, and treats B as a word character but # as a non-word character. So when it reaches the end of a line and searches for a place to break the line, it sees a # almost immediately and happily breaks there; whereas with the B, it has to keep searching for longer, and may have more text to wrap (which may be expensive on some terminals, e.g., outputting backspaces, then outputting spaces to overwrite the letters being wrapped).

But that's pure speculation.

What is the difference between single and double quotes in SQL?

A simple rule for us to remember what to use in which case:

  • [S]ingle quotes are for [S]trings ; [D]ouble quotes are for [D]atabase identifiers;

In MySQL and MariaDB, the ` (backtick) symbol is the same as the " symbol. You can use " when your SQL_MODE has ANSI_QUOTES enabled.

How to parse JSON array in jQuery?

Careful with the eval, the JSON specs http://json.org/js.html recommend something like

var myObject = eval('(' + myJSONtext + ')');

And there may be some more gotchas. There is a plugin for jQuery that will take care of it, i guess:

http://code.google.com/p/jquery-json/

password for postgres

What's the default superuser username/password for postgres after a new install?:

CAUTION The answer about changing the UNIX password for "postgres" through "$ sudo passwd postgres" is not preferred, and can even be DANGEROUS!

This is why: By default, the UNIX account "postgres" is locked, which means it cannot be logged in using a password. If you use "sudo passwd postgres", the account is immediately unlocked. Worse, if you set the password to something weak, like "postgres", then you are exposed to a great security danger. For example, there are a number of bots out there trying the username/password combo "postgres/postgres" to log into your UNIX system.

What you should do is follow Chris James's answer:

sudo -u postgres psql postgres

# \password postgres

Enter new password: 

To explain it a little bit...

Create array of all integers between two numbers, inclusive, in Javascript/jQuery

function range(j, k) { 
    return Array
        .apply(null, Array((k - j) + 1))
        .map(function(_, n){ return n + j; }); 
}

this is roughly equivalent to

function range(j, k) { 
    var targetLength = (k - j) + 1;
    var a = Array(targetLength);
    var b = Array.apply(null, a);
    var c = b.map(function(_, n){ return n + j; });
    return c;
}

breaking it down:

var targetLength = (k - j) + 1;

var a = Array(targetLength);

this creates a sparse matrix of the correct nominal length. Now the problem with a sparse matrix is that although it has the correct nominal length, it has no actual elements, so, for

j = 7, k = 13

console.log(a);

gives us

Array [ <7 empty slots> ]

Then

var b = Array.apply(null, a);

passes the sparse matrix as an argument list to the Array constructor, which produces a dense matrix of (actual) length targetLength, where all elements have undefined value. The first argument is the 'this' value for the the array constructor function execution context, and plays no role here, and so is null.

So now,

 console.log(b);

yields

 Array [ undefined, undefined, undefined, undefined, undefined, undefined, undefined ]

finally

var c = b.map(function(_, n){ return n + j; });

makes use of the fact that the Array.map function passes: 1. the value of the current element and 2. the index of the current element, to the map delegate/callback. The first argument is discarded, while the second can then be used to set the correct sequence value, after adjusting for the start offset.

So then

console.log(c);

yields

 Array [ 7, 8, 9, 10, 11, 12, 13 ]

Taking multiple inputs from user in python

How about making the input a list. Then you may use standard list operations.

a=list(input("Enter the numbers"))

How to "properly" print a list?

Using only print:

>>> l = ['x', 3, 'b']
>>> print(*l, sep='\n')
x
3
b
>>> print(*l, sep=', ')
x, 3, b

jQuery event to trigger action when a div is made visible

I changed the hide/show event trigger from Catalint based on Glenns idea. My problem was that I have a modular application. I change between modules showing and hiding divs parents. Then when I hide a module and show another one, with his method I have a visible delay when I change between modules. I only need sometimes to liten this event, and in some special childs. So I decided to notify only the childs with the class "displayObserver"

$.each(["show", "hide", "toggleClass", "addClass", "removeClass"], function () {
    var _oldFn = $.fn[this];
    $.fn[this] = function () {
        var hidden = this.find(".displayObserver:hidden").add(this.filter(":hidden"));
        var visible = this.find(".displayObserver:visible").add(this.filter(":visible"));
        var result = _oldFn.apply(this, arguments);
        hidden.filter(":visible").each(function () {
            $(this).triggerHandler("show");
        }); 
        visible.filter(":hidden").each(function () {
            $(this).triggerHandler("hide");
        });
        return result;
    }
});

Then when a child wants to listen for "show" or "hide" event I have to add him the class "displayObserver", and when It does not want to continue listen it, I remove him the class

bindDisplayEvent: function () {
   $("#child1").addClass("displayObserver");
   $("#child1").off("show", this.onParentShow);
   $("#child1").on("show", this.onParentShow);
},

bindDisplayEvent: function () {
   $("#child1").removeClass("displayObserver");
   $("#child1").off("show", this.onParentShow);
},

I wish help

How can I do an OrderBy with a dynamic string parameter?

Absolutely. You can use the LINQ Dynamic Query Library, found on Scott Guthrie's blog. There's also an updated version available on CodePlex.

It lets you create OrderBy clauses, Where clauses, and just about everything else by passing in string parameters. It works great for creating generic code for sorting/filtering grids, etc.

var result = data
    .Where(/* ... */)
    .Select(/* ... */)
    .OrderBy("Foo asc");

var query = DbContext.Data
    .Where(/* ... */)
    .Select(/* ... */)
    .OrderBy("Foo ascending");

curl: (35) SSL connect error

If you are using curl versions curl-7.19.7-46.el6.x86_64 or older. Please provide an option as -k1 (small K1).

Random color generator

Just because I can, I created an unreadable snippet that randomizes between min and max hex codes...:

function a(f, s){
    if(!s || !s.length > 1) return "";
    var c = Math.floor(Math.random()*(parseInt("0x" + s.substr(0,2))-parseInt("0x" +     f.substr(0,2))+1)+parseInt("0x" + f.substr(0,2))).toString(16);
    return  (Array(3 - c.length).join("0")) + c + a(f.substr(2,f.length),s.substr(2,s.length));
}

a("990099","ff00ff") ? might randomize ? b5009e

It does it in pairs, so a("12","f2") ? might randomize ? 8f. But it won't go above 'f2'.

var color = "#" + a("11","22") + a("33","44") + a("55","66");

It is the same as:

var color = "#" + a("113355","224466")

But slower.

Binding ng-model inside ng-repeat loop in AngularJS

For each iteration of the ng-repeat loop, line is a reference to an object in your array. Therefore, to preview the value, use {{line.text}}.

Similarly, to databind to the text, databind to the same: ng-model="line.text". You don't need to use value when using ng-model (actually you shouldn't).

Fiddle.

For a more in-depth look at scopes and ng-repeat, see What are the nuances of scope prototypal / prototypical inheritance in AngularJS?, section ng-repeat.

Adding a JAR to an Eclipse Java library

In Eclipse Ganymede (3.4.0):

  1. Select the library and click "Edit" (left side of the window)
  2. Click "User Libraries"
  3. Select the library again and click "Add JARs"

Change string color with NSAttributedString?

In Swift 4:

// Custom color
let greenColor = UIColor(red: 10/255, green: 190/255, blue: 50/255, alpha: 1)
// create the attributed colour
let attributedStringColor = [NSAttributedStringKey.foregroundColor : greenColor];
// create the attributed string
let attributedString = NSAttributedString(string: "Hello World!", attributes: attributedStringColor)
// Set the label
label.attributedText = attributedString

In Swift 3:

// Custom color
let greenColor = UIColor(red: 10/255, green: 190/255, blue: 50/255, alpha: 1)
// create the attributed color
let attributedStringColor : NSDictionary = [NSForegroundColorAttributeName : greenColor];
// create the attributed string
let attributedString = NSAttributedString(string: "Hello World!", attributes: attributedStringColor as? [String : AnyObject])
// Set the label
label.attributedText = attributedString 

Enjoy.

When to use malloc for char pointers

malloc for single chars or integers and calloc for dynamic arrays. ie pointer = ((int *)malloc(sizeof(int)) == NULL), you can do arithmetic within the brackets of malloc but you shouldnt because you should use calloc which has the definition of void calloc(count, size)which means how many items you want to store ie count and size of data ie int , char etc.

How to set a default value for an existing column

ALTER TABLE [dbo].[Employee] ADD  DEFAULT ('N') FOR [CityBorn]

What is __gxx_personality_v0 for?

A quick grep of the libstd++ code base revealed the following two usages of __gx_personality_v0:

In libsupc++/unwind-cxx.h

// GNU C++ personality routine, Version 0.                                      
extern "C" _Unwind_Reason_Code __gxx_personality_v0
     (int, _Unwind_Action, _Unwind_Exception_Class,
      struct _Unwind_Exception *, struct _Unwind_Context *);

In libsupc++/eh_personality.cc

#define PERSONALITY_FUNCTION    __gxx_personality_v0
extern "C" _Unwind_Reason_Code
PERSONALITY_FUNCTION (int version,
                      _Unwind_Action actions,
                      _Unwind_Exception_Class exception_class,
                      struct _Unwind_Exception *ue_header,
                      struct _Unwind_Context *context)
{
  // ... code to handle exceptions and stuff ...
}

(Note: it's actually a little more complicated than that; there's some conditional compilation that can change some details).

So, as long as your code isn't actually using exception handling, defining the symbol as void* won't affect anything, but as soon as it does, you're going to crash - __gxx_personality_v0 is a function, not some global object, so trying to call the function is going to jump to address 0 and cause a segfault.

How to write subquery inside the OUTER JOIN Statement

I think you don't have to use sub query in this scenario.You can directly left outer join the DEPRMNT table .

While using Left Outer Join ,don't use columns in the RHS table of the join in the where condition, you ll get wrong output

Copying sets Java

Java 8+:

Set<String> copy = new HashSet<>(mySet); 

How to return a result (startActivityForResult) from a TabHost Activity?

You could implement a onActivityResult in Class B as well and launch Class C using startActivityForResult. Once you get the result in Class B then set the result there (for Class A) based on the result from Class C. I haven't tried this out but I think this should work.

Another thing to look out for is that Activity A should not be a singleInstance activity. For startActivityForResult to work your Class B needs to be a sub activity to Activity A and that is not possible in a single instance activity, the new Activity (Class B) starts in a new task.

R define dimensions of empty data frame

You may use NULL instead of NA. This creates a truly empty data frame.

Load JSON text into class object in c#

copy your Json and paste at textbox on http://json2csharp.com/ and click on Generate button,

A cs class will be generated use that cs file as below:

var generatedcsResponce = JsonConvert.DeserializeObject(yourJson);

where RootObject is the name of the generated cs file;

Select the top N values by group

You can write a function that splits the database by a factor, orders by another desired variable, extract the number of rows you want in each factor (category) and combine these into a database.

top<-function(x, num, c1,c2){
sorted<-x[with(x,order(x[,c1],x[,c2],decreasing=T)),]
splits<-split(sorted,sorted[,c1])
df<-lapply(splits,head,num)
do.call(rbind.data.frame,df)}

x is the dataframe;

num is the number of number of rows you would like to see;

c1 is the column number of the variable you would like to split by;

c2 is the column number of the variable you would like to rank by or handle ties.

Using the mtcars data, the function extracts the 3 heaviest cars (mtcars$wt is the 6th column) in each cylinder class (mtcars$cyl is the 2nd column)

 top(mtcars,3,2,6)
                         mpg cyl  disp  hp drat    wt  qsec vs am gear carb
 4.Merc 240D           24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
 4.Merc 230            22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
 4.Volvo 142E          21.4   4 121.0 109 4.11 2.780 18.60  1  1    4    2
 6.Valiant             18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
 6.Merc 280            19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
 6.Merc 280C           17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4
 8.Lincoln Continental 10.4   8 460.0 215 3.00 5.424 17.82  0  0    3    4
 8.Chrysler Imperial   14.7   8 440.0 230 3.23 5.345 17.42  0  0    3    4
 8.Cadillac Fleetwood  10.4   8 472.0 205 2.93 5.250 17.98  0  0    3    4

You can also easily get the lightest in a class by changing head in the lapply function to tail OR by removing the decreasing=T argument in the order function which will return it to its default, decreasing=F.

How to add elements of a string array to a string array list?

Arrays.asList is bridge between Array and collection framework and it returns a fixed size List backed by Array.

species = Arrays.asList(speciesArr);

Receiving "fatal: Not a git repository" when attempting to remote add a Git repo

I had this issue with the Jenkins Git plugin after authentication issues with GitLab. Jenkins was reporting 'hudson.plugins.git.GitException:[...]stderr: GitLab: The project you were looking for could not be found. fatal: Could not read from remote repository.'

However if I did a 'git clone' or 'git fetch' direct from the Jenkins box (command line) it worked without issue.

The issue was resolved by deleting the entire /workspace directory in the Jenkins jobs folder for that particular job, e.g.

rm -Rf $JENKINS_HOME/jobs/myJenkinsJob/workspace/

Presumably the local .git folder had got stale/corrupted ?

Java random numbers using a seed

That's the principle of a Pseudo-RNG. The numbers are not really random. They are generated using a deterministic algorithm, but depending on the seed, the sequence of generated numbers vary. Since you always use the same seed, you always get the same sequence.

What is the difference between Digest and Basic Authentication?

Let us see the difference between the two HTTP authentication using Wireshark (Tool to analyse packets sent or received) .

1. Http Basic Authentication

Basic

As soon as the client types in the correct username:password,as requested by the Web-server, the Web-Server checks in the Database if the credentials are correct and gives the access to the resource .

Here is how the packets are sent and received :

enter image description here In the first packet the Client fill the credentials using the POST method at the resource - lab/webapp/basicauth .In return the server replies back with http response code 200 ok ,i.e, the username:password were correct .

Detail of HTTP packet

Now , In the Authorization header it shows that it is Basic Authorization followed by some random string .This String is the encoded (Base64) version of the credentials admin:aadd (including colon ) .

2 . Http Digest Authentication(rfc 2069)

So far we have seen that the Basic Authentication sends username:password in plaintext over the network .But the Digest Auth sends a HASH of the Password using Hash algorithm.

Here are packets showing the requests made by the client and response from the server .

Digest

As soon as the client types the credentials requested by the server , the Password is converted to a response using an algorithm and then is sent to the server , If the server Database has same response as given by the client the server gives the access to the resource , otherwise a 401 error .

Detailed digest auth packet In the above Authorization , the response string is calculated using the values of Username,Realm,Password,http-method,URI and Nonce as shown in the image :

Response algorithm (colons are included)

Hence , we can see that the Digest Authentication is more Secure as it involve Hashing (MD5 encryption) , So the packet sniffer tools cannot sniff the Password although in Basic Auth the exact Password was shown on Wireshark.

How to concatenate strings in a Windows batch file?

Note that the variables @fname or @ext can be simply concatenated. This:

forfiles /S /M *.pdf /C "CMD /C REN @path @fname_old.@ext"

renames all PDF files to "filename_old.pdf"

Use NSInteger as array index

According to the error message, you declared myLoc as a pointer to an NSInteger (NSInteger *myLoc) rather than an actual NSInteger (NSInteger myLoc). It needs to be the latter.

How can I debug my JavaScript code?

As with most answers, it really depends: What are you trying to achieve with your debugging? Basic development, fixing performance issues? For basic development, all the previous answers are more than adequate.

For performance testing specifically, I recommend Firebug. Being able to profile which methods are the most expensive in terms of time has been invaluable for a number of projects I have worked on. As client-side libraries become more and more robust, and more responsibility is placed client-side in general, this type of debugging and profiling will only become more useful.

Firebug Console API: http://getfirebug.com/console.html

When to use IList and when to use List

Microsoft guidelines as checked by FxCop discourage use of List<T> in public APIs - prefer IList<T>.

Incidentally, I now almost always declare one-dimensional arrays as IList<T>, which means I can consistently use the IList<T>.Count property rather than Array.Length. For example:

public interface IMyApi
{
    IList<int> GetReadOnlyValues();
}

public class MyApiImplementation : IMyApi
{
    public IList<int> GetReadOnlyValues()
    {
        List<int> myList = new List<int>();
        ... populate list
        return myList.AsReadOnly();
    }
}
public class MyMockApiImplementationForUnitTests : IMyApi
{
    public IList<int> GetReadOnlyValues()
    {
        IList<int> testValues = new int[] { 1, 2, 3 };
        return testValues;
    }
}

What does "Failure [INSTALL_FAILED_OLDER_SDK]" mean in Android Studio?

In your manifest file package attribute is set to com.test.helloworld however your activity class is under different package. Change your MyActivity class package to com.example.helloworld

How can I create my own comparator for a map?

std::map takes up to four template type arguments, the third one being a comparator. E.g.:

struct cmpByStringLength {
    bool operator()(const std::string& a, const std::string& b) const {
        return a.length() < b.length();
    }
};

// ...
std::map<std::string, std::string, cmpByStringLength> myMap;

Alternatively you could also pass a comparator to maps constructor.

Note however that when comparing by length you can only have one string of each length in the map as a key.

How to make Visual Studio copy a DLL file to the output directory?

xcopy /y /d  "$(ProjectDir)External\*.dll" "$(TargetDir)"

You can also refer to a relative path, the next example will find the DLL in a folder located one level above the project folder. If you have multiple projects that use the DLL in a single solution, this places the source of the DLL in a common area reachable when you set any of them as the Startup Project.

xcopy /y /d  "$(ProjectDir)..\External\*.dll" "$(TargetDir)"

The /y option copies without confirmation. The /d option checks to see if a file exists in the target and if it does only copies if the source has a newer timestamp than the target.

I found that in at least newer versions of Visual Studio, such as VS2109, $(ProjDir) is undefined and had to use $(ProjectDir) instead.

Leaving out a target folder in xcopy should default to the output directory. That is important to understand reason $(OutDir) alone is not helpful.

$(OutDir), at least in recent versions of Visual Studio, is defined as a relative path to the output folder, such as bin/x86/Debug. Using it alone as the target will create a new set of folders starting from the project output folder. Ex: … bin/x86/Debug/bin/x86/Debug.

Combining it with the project folder should get you to the proper place. Ex: $(ProjectDir)$(OutDir).

However $(TargetDir) will provide the output directory in one step.

Microsoft's list of MSBuild macros for current and previous versions of Visual Studio

How can one use multi threading in PHP applications

You could simulate threading. PHP can run background processes via popen (or proc_open). Those processes can be communicated with via stdin and stdout. Of course those processes can themselves be a php program. That is probably as close as you'll get.

How do I increase memory on Tomcat 7 when running as a Windows Service?

//ES/tomcat -> This may not work if you have changed the service name during the installation.

Either run the command without any service name

.\bin\tomcat7w.exe //ES

or with exact service name

.\bin\tomcat7w.exe //ES/YourServiceName

load external css file in body tag

No, it is not okay to put a link element in the body tag. See the specification (links to the HTML4.01 specs, but I believe it is true for all versions of HTML):

“This element defines a link. Unlike A, it may only appear in the HEAD section of a document, although it may appear any number of times.”

JSON.Net Self referencing loop detected

You must set Preserving Object References:

var jsonSerializerSettings = new JsonSerializerSettings
{
    PreserveReferencesHandling = PreserveReferencesHandling.Objects
};

Then call your query var q = (from a in db.Events where a.Active select a).ToList(); like

string jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(q, jsonSerializerSettings);

See: https://www.newtonsoft.com/json/help/html/PreserveObjectReferences.htm

PHP: How to check if a date is today, yesterday or tomorrow

First. You have mistake in using function strtotime see PHP documentation

int strtotime ( string $time [, int $now = time() ] )

You need modify your code to pass integer timestamp into this function.

Second. You use format d.m.Y H:i that includes time part. If you wish to compare only dates, you must remove time part, e.g. `$date = date("d.m.Y");``

Third. I am not sure if it works in the same way for you, but my PHP doesn't understand date format from $timestamp and returns 01.01.1970 02:00 into $match_date

$timestamp = "2014.09.02T13:34";
date('d.m.Y H:i', strtotime($timestamp)) === "01.01.1970 02:00";

You need to check if strtotime($timestamp) returns correct date string. If no, you need to specify format which is used in $timestamp variable. You can do this using one of functions date_parse_from_format or DateTime::createFromFormat

This is a work example:

$timestamp = "2014.09.02T13:34";

$today = new DateTime(); // This object represents current date/time
$today->setTime( 0, 0, 0 ); // reset time part, to prevent partial comparison

$match_date = DateTime::createFromFormat( "Y.m.d\\TH:i", $timestamp );
$match_date->setTime( 0, 0, 0 ); // reset time part, to prevent partial comparison

$diff = $today->diff( $match_date );
$diffDays = (integer)$diff->format( "%R%a" ); // Extract days count in interval

switch( $diffDays ) {
    case 0:
        echo "//Today";
        break;
    case -1:
        echo "//Yesterday";
        break;
    case +1:
        echo "//Tomorrow";
        break;
    default:
        echo "//Sometime";
}

How do I stop Notepad++ from showing autocomplete for all words in the file

The answer is to DISABLE "Enable auto-completion on each input". Tested and works perfectly.

Bulk Insert Correctly Quoted CSV File in SQL Server

I had this same problem, and I didn't want to have to go the SSIS route, so I found a PowerShell script that is easy to run and handles the case of the quotes with the comma in that particular field:

Source Code and DLL for the PowerShell Script: https://github.com/billgraziano/CsvDataReader

Here's a blog that explains the usage: http://www.sqlteam.com/article/fast-csv-import-in-powershell-to-sql-server

Java: Instanceof and Generics

Old post, but a simple way to do generic instanceOf checking.

public static <T> boolean isInstanceOf(Class<T> clazz, Class<T> targetClass) {
    return clazz.isInstance(targetClass);
}

How do I change the root directory of an Apache server?

You need to change the DocumentRoot setting in your httpd.conf file. Chances are it will be under something like /etc/apache2/conf/httpd.conf.

Use your favourite editor (I recommend Vim) and look for the DocumentRoot and change it to /users/spencer/projects. Also look a little further down for a setting that looks like this:

<Directory "/var/www">

You will also want to change what is in the quotes to your new directory. This gives Apache access to read from that directory when a user makes a request that call on it.

Now restart your Apache service (httpd -k restart) and you should be good to go.

Apache 2 site configuration files are now typically kept in /etc/apache2/sites-available/ (Debian, Ubuntu, etc.).

Best way to extract a subvector from a vector?

You could just use insert

vector<type> myVec { n_elements };

vector<type> newVec;

newVec.insert(newVec.begin(), myVec.begin() + X, myVec.begin() + Y);

SQL DELETE with INNER JOIN

if the database is InnoDB you dont need to do joins in deletion. only

DELETE FROM spawnlist WHERE spawnlist.type = "monster";

can be used to delete the all the records that linked with foreign keys in other tables, to do that you have to first linked your tables in design time.

CREATE TABLE IF NOT EXIST spawnlist (
  npc_templateid VARCHAR(20) NOT NULL PRIMARY KEY

)ENGINE=InnoDB;

CREATE TABLE IF NOT EXIST npc (
  idTemplate VARCHAR(20) NOT NULL,

  FOREIGN KEY (idTemplate) REFERENCES spawnlist(npc_templateid) ON DELETE CASCADE

)ENGINE=InnoDB;

if you uses MyISAM you can delete records joining like this

DELETE a,b
FROM `spawnlist` a
JOIN `npc` b
ON a.`npc_templateid` = b.`idTemplate`
WHERE a.`type` = 'monster';

in first line i have initialized the two temp tables for delet the record, in second line i have assigned the existance table to both a and b but here i have linked both tables together with join keyword, and i have matched the primary and foreign key for both tables that make link, in last line i have filtered the record by field to delete.

Android Bitmap to Base64 String

All of these answers are inefficient as they needlessly decode to a bitmap and then recompress the bitmap. When you take a photo on Android, it is stored as a jpeg in the temp file you specify when you follow the android docs.

What you should do is directly convert that file to a Base64 string. Here is how to do that in easy copy-paste (in Kotlin). Note you must close the base64FilterStream to truly flush its internal buffer.

fun convertImageFileToBase64(imageFile: File): String {

    return FileInputStream(imageFile).use { inputStream ->
        ByteArrayOutputStream().use { outputStream ->
            Base64OutputStream(outputStream, Base64.DEFAULT).use { base64FilterStream ->
                inputStream.copyTo(base64FilterStream)
                base64FilterStream.close()
                outputStream.toString()
            }
        }
    }
}

As a bonus, your image quality should be slightly improved, due to bypassing the re-compressing.

Can gcc output C code after preprocessing?

Yes. Pass gcc the -E option. This will output preprocessed source code.

What is the difference between putting a property on application.yml or bootstrap.yml in spring boot?

Just my 2 Cents here ..

Bootstrap.yml or Bootstrap.properties is used to fetch the config from Spring Cloud Server.

For Example, in My Bootstrap.properties file I have the following Config

spring.application.name=Calculation-service
spring.cloud.config.uri=http://localhost:8888

On starting the application , It tries to fetch the configuration for the service by connecting to http://localhost:8888 and looks at Calculation-service.properties present in Spring Cloud Config server

You can validate the same from logs of Calcuation-Service when you start it up

INFO 10988 --- [ restartedMain] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at : http://localhost:8888

Create a folder if it doesn't already exist

If you want to avoid the file_exists VS is_dir problem, I would suggest you to look here

I tried this and it only creates the directory if the directory does not exist. It does not care it there is a file with that name.

/* Creates the directory if it does not exist */
$path_to_directory = 'path/to/directory';
if (!file_exists($path_to_directory) && !is_dir($path_to_directory)) {
    mkdir($path_to_directory, 0777, true);
}

How to start new activity on button click

Start another activity from this activity and u can pass parameters via Bundle Object also.

Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "[email protected]");
startActivity(intent);

Retrive data in another activity (YourActivity)

String s = getIntent().getStringExtra("USER_NAME");

What's wrong with foreign keys?

I have heard this argument too - from people who forgot to put an index on their foreign keys and then complained that certain operations were slow (because constraint checking could take advantage of any index). So to sum up: There is no good reason not to use foreign keys. All modern databases support cascaded deletes, so...

How to read data From *.CSV file using javascript?

Don't split on commas -- it won't work for most CSV files, and this question has wayyyy too many views for the asker's kind of input data to apply to everyone. Parsing CSV is kind of scary since there's no truly official standard, and lots of delimited text writers don't consider edge cases.

This question is old, but I believe there's a better solution now that Papa Parse is available. It's a library I wrote, with help from contributors, that parses CSV text or files. It's the only JS library I know of that supports files gigabytes in size. It also handles malformed input gracefully.

1 GB file parsed in 1 minute: Parsed 1 GB file in 1 minute

(Update: With Papa Parse 4, the same file took only about 30 seconds in Firefox. Papa Parse 4 is now the fastest known CSV parser for the browser.)

Parsing text is very easy:

var data = Papa.parse(csvString);

Parsing files is also easy:

Papa.parse(file, {
    complete: function(results) {
        console.log(results);
    }
});

Streaming files is similar (here's an example that streams a remote file):

Papa.parse("http://example.com/bigfoo.csv", {
    download: true,
    step: function(row) {
        console.log("Row:", row.data);
    },
    complete: function() {
        console.log("All done!");
    }
});

If your web page locks up during parsing, Papa can use web workers to keep your web site reactive.

Papa can auto-detect delimiters and match values up with header columns, if a header row is present. It can also turn numeric values into actual number types. It appropriately parses line breaks and quotes and other weird situations, and even handles malformed input as robustly as possible. I've drawn on inspiration from existing libraries to make Papa, so props to other JS implementations.

HTML anchor link - href and onclick both?

<a href="#Foo" onclick="return runMyFunction();">Do it!</a>

and

function runMyFunction() {
  //code
  return true;
}

This way you will have youf function executed AND you will follow the link AND you will follow the link exactly after your function was successfully run.

String variable interpolation Java

If you're using Java 5 or higher, you can use String.format:

urlString += String.format("u1=%s;u2=%s;u3=%s;u4=%s;", u1, u2, u3, u4);

See Formatter for details.

Unzipping files in Python

You can also import only ZipFile:

from zipfile import ZipFile
zf = ZipFile('path_to_file/file.zip', 'r')
zf.extractall('path_to_extract_folder')
zf.close()

Works in Python 2 and Python 3.

How do I modify the URL without reloading the page?

HTML5 introduced the history.pushState() and history.replaceState() methods, which allow you to add and modify history entries, respectively.

window.history.pushState('page2', 'Title', '/page2.php');

Read more about this from here

How to check if a string is null in python

Try this:

if cookie and not cookie.isspace():
    # the string is non-empty
else:
    # the string is empty

The above takes in consideration the cases where the string is None or a sequence of white spaces.

What should I set JAVA_HOME environment variable on macOS X 10.6?

I've found this stack to help, i was having the same issue and i could fix:

My java path was here:

/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home

and was needed to put into my .bash_profile:

export JAVA_HOME=\"/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home\"

Hope help

How to increase the distance between table columns in HTML?

Set the width of the <td>s to 50px and then add your <td> + another fake <td>

Fiddle.

_x000D_
_x000D_
table tr td:empty {_x000D_
  width: 50px;_x000D_
}_x000D_
  _x000D_
table tr td {_x000D_
  padding-top: 10px;_x000D_
  padding-bottom: 10px;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>First Column</td>_x000D_
    <td></td>_x000D_
    <td>Second Column</td>_x000D_
    <td></td>_x000D_
    <td>Third Column</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Code Explained:

The first CSS rule checks for empty td's and give them a width of 50px then the second rule give the padding of top and bottom to all the td's.

Comparing the contents of two files in Sublime Text

View - Layout and View - Groups will do in latest Sublime 3

eg:

Shift+Alt+2 --> creates 2 columns

Ctrl+2 --> move selected file to column 2

This is for side by side comparison. For actual diff, there is the diff function other already mentioned. Unfortunately, I can't find a way to make columns scroll at the same time, which would be a nice feature.

CodeIgniter: "Unable to load the requested class"

I had a similar issue when deploying from OSx on my local to my Linux live site.

It ran fine on OSx, but on Linux I was getting:

An Error Was Encountered

Unable to load the requested class: Ckeditor

The problem was that Linux paths are apparently case-sensitive so I had to rename my library files from "ckeditor.php" to "CKEditor.php".

I also changed my load call to match the capitalization:

$this->load->library('CKEditor');

How to get row data by clicking a button in a row in an ASP.NET gridview

Is there any specific reason you would want your buttons in an item template.You can alternatively do it the following way , there by giving you the full power of the grid row editing event.You are also given a bonus of wiring easily the cancel and delete functionality.

Mark up

<asp:TemplateField HeaderText="Edit">
            <ItemTemplate>
   <asp:ImageButton ID="EditImageButton" runat="server" CommandName="Edit"
    ImageUrl="~/images/Edit.png" Style="height: 16px" ToolTip="Edit" 
    CausesValidation="False"  />

      </ItemTemplate>

         <EditItemTemplate>

                    <asp:LinkButton ID="btnUpdate" runat="server" CommandName="Update" 
                        Text="Update"  Visible="true" ImageUrl="~/images/saveHS.png" 
                        />
                   <asp:LinkButton ID="btnCancel" runat="server" CommandName="Cancel"   
                        ImageUrl="~/images/Edit_UndoHS.png"  />

                 <asp:LinkButton ID="btnDelete" runat="server" CommandName="Delete"   
                        ImageUrl="~/images/delete.png"  />

             </EditItemTemplate>


        <ControlStyle BackColor="Transparent" BorderStyle="None" />
               <FooterStyle HorizontalAlign="Center" />
           <ItemStyle HorizontalAlign="Center" />
       </asp:TemplateField>

Code behind

 protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{

    GridView1.EditIndex = e.NewEditIndex;
    GridView1.DataBind();

TextBox txtledName =   (TextBox) GridView1.Rows[e.NewEditIndex].FindControl("txtAccountName");

 //then do something with the retrieved textbox's text.

}

How can I find whitespace in a String?

public static void main(String[] args) {
    System.out.println("test word".contains(" "));
}

Using Node.JS, how do I read a JSON file into (server) memory?

In Node 8 you can use the built-in util.promisify() to asynchronously read a file like this

const {promisify} = require('util')
const fs = require('fs')
const readFileAsync = promisify(fs.readFile)

readFileAsync(`${__dirname}/my.json`, {encoding: 'utf8'})
  .then(contents => {
    const obj = JSON.parse(contents)
    console.log(obj)
  })
  .catch(error => {
    throw error
  })

ErrorActionPreference and ErrorAction SilentlyContinue for Get-PSSessionConfiguration

It looks like that's an "unhandled exception", meaning the cmdlet itself hasn't been coded to recognize and handle that exception. It blew up without ever getting to run it's internal error handling, so the -ErrorAction setting on the cmdlet never came into play.

Submit a form in a popup, and then close the popup

The Solution on top won't work because a submit redirects the page to the endpoint of form and wait for response to redirect. I see that this is an old Question but Most Asked and even i came to know the answer.Still here is my solution what i am implementing. I tried to keep it secure with Nonce but if you don't care then not required.

Method 1: You need to Pop up the form.

document.getElementById('edit_info_button').addEventListener('click',function(){
        window.open('{% url "updateuserinfo" %}','newwindow', 'width=400,height=600,scrollbars=no');
    });

Then you have the form open.

Submit the form normally.

Then return an HTTPResponse in render to a template(HTML file) With a STRICT Content Security Policy. A Variable that contains the following script. Nonce contains a Base64 128bits or larger randomly generated string for every request made to server.

<script nonce="{{nonce}}">window.close()</script>

Method 2:

Or you can redirect to another Page which is suppose to close ... Which already Contains the window.close() script. This will close the pop up window.

Method 3:

Otherwise the simplest will be Use a Ajax call if you are comfortable with one.Use then() and check your condition to the httpresponse from the server.Close the window when success.

How to convert latitude or longitude to meters?

    'below is from
'http://www.zipcodeworld.com/samples/distance.vbnet.html
Public Function distance(ByVal lat1 As Double, ByVal lon1 As Double, _
                         ByVal lat2 As Double, ByVal lon2 As Double, _
                         Optional ByVal unit As Char = "M"c) As Double
    Dim theta As Double = lon1 - lon2
    Dim dist As Double = Math.Sin(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) + _
                            Math.Cos(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) * _
                            Math.Cos(deg2rad(theta))
    dist = Math.Acos(dist)
    dist = rad2deg(dist)
    dist = dist * 60 * 1.1515
    If unit = "K" Then
        dist = dist * 1.609344
    ElseIf unit = "N" Then
        dist = dist * 0.8684
    End If
    Return dist
End Function
Public Function Haversine(ByVal lat1 As Double, ByVal lon1 As Double, _
                         ByVal lat2 As Double, ByVal lon2 As Double, _
                         Optional ByVal unit As Char = "M"c) As Double
    Dim R As Double = 6371 'earth radius in km
    Dim dLat As Double
    Dim dLon As Double
    Dim a As Double
    Dim c As Double
    Dim d As Double
    dLat = deg2rad(lat2 - lat1)
    dLon = deg2rad((lon2 - lon1))
    a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Cos(deg2rad(lat1)) * _
            Math.Cos(deg2rad(lat2)) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2)
    c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a))
    d = R * c
    Select Case unit.ToString.ToUpper
        Case "M"c
            d = d * 0.62137119
        Case "N"c
            d = d * 0.5399568
    End Select
    Return d
End Function
Private Function deg2rad(ByVal deg As Double) As Double
    Return (deg * Math.PI / 180.0)
End Function
Private Function rad2deg(ByVal rad As Double) As Double
    Return rad / Math.PI * 180.0
End Function

standard size for html newsletter template

Short answer: 400-800 pixels.

What I have read is that HTML newsletter width should be as narrow as possible without being too narrow. For instance, 400-500 pixels for a one column layout is a lower limit. Any less may look too weird.

Today's widescreen monitors allow for more horizontal pixels and most web email clients will either be of the two-column variety (Gmail) or 3-pane layout where the content window bellow the inbox list (Hotmail and Yahoo). In either case, you can be okay with 800 pixels if you're targeting the 1280 wide audience. An older or less technical audience may have older, square monitors.

There is the problem of Outlook having a three-column layout. That limits the width of your email even more. With them, you may want to go even narrower.

I just recently created a template that required an ad banner that is 730 pixels wide. It was near in the wide range, but not so much that most people could not double-click the email an open a new window in Outlook (the web email users should be okay for the most part).

Hope this advice helps.

Combining INSERT INTO and WITH/CTE

The WITH clause for Common Table Expressions go at the top.

Wrapping every insert in a CTE has the benefit of visually segregating the query logic from the column mapping.

Spot the mistake:

WITH _INSERT_ AS (
  SELECT
    [BatchID]      = blah
   ,[APartyNo]     = blahblah
   ,[SourceRowID]  = blahblahblah
  FROM Table1 AS t1
)
INSERT Table2
      ([BatchID], [SourceRowID], [APartyNo])
SELECT [BatchID], [APartyNo], [SourceRowID]   
FROM _INSERT_

Same mistake:

INSERT Table2 (
  [BatchID]
 ,[SourceRowID]
 ,[APartyNo]
)
SELECT
  [BatchID]      = blah
 ,[APartyNo]     = blahblah
 ,[SourceRowID]  = blahblahblah
FROM Table1 AS t1

A few lines of boilerplate make it extremely easy to verify the code inserts the right number of columns in the right order, even with a very large number of columns. Your future self will thank you later.

Javascript objects: get parent

You will need the child to store the parents this variable. As the Parent is the only object that has access to it's this variable it will also need a function that places the this variable into the child's that variable, something like this.

var Parent = {
  Child : {
    that : {},
  },
  init : function(){
    this.Child.that = this;
  }
}

To test this out try to run this in Firefox's Scratchpad, it worked for me.

var Parent = {
  data : "Parent Data",

  Child : {
    that : {},
    data : "Child Data",
    display : function(){
      console.log(this.data);
      console.log(this.that.data);
    }
  },
  init : function(){
    this.Child.that = this;
  }
}

Parent.init();
Parent.Child.display();

How to specify a port to run a create-react-app based project?

just run below command

PORT=3001 npm start

Magento addFieldToFilter: Two fields, match as OR, not AND

This is the real magento way:

    $collection=Mage::getModel('sales/order')
                ->getCollection()
                ->addFieldToFilter(
                        array(
                            'customer_firstname',//attribute_1 with key 0
                            'remote_ip',//attribute_2 with key 1
                        ),
                        array(
                            array('eq'=>'gabe'),//condition for attribute_1 with key 0
                            array('eq'=>'127.0.0.1'),//condition for attribute_2
                                )
                            )
                        );

Generating HTML email body in C#

I use dotLiquid for exactly this task.

It takes a template, and fills special identifiers with the content of an anonymous object.

//define template
String templateSource = "<h1>{{Heading}}</h1>Dear {{UserName}},<br/><p>First part of the email body goes here");
Template bodyTemplate = Template.Parse(templateSource); // Parses and compiles the template source

//Create DTO for the renderer
var bodyDto = new {
    Heading = "Heading Here",
    UserName = userName
};
String bodyText = bodyTemplate.Render(Hash.FromAnonymousObject(bodyDto));

It also works with collections, see some online examples.

How to get a property value based on the name

Expanding on Adam Rackis's answer - we can make the extension method generic simply like this:

public static TResult GetPropertyValue<TResult>(this object t, string propertyName)
{
    object val = t.GetType().GetProperties().Single(pi => pi.Name == propertyName).GetValue(t, null);
    return (TResult)val;
}

You can throw some error handling around that too if you like.

Ignoring NaNs with str.contains

import folium
import pandas

data= pandas.read_csv("maps.txt")

lat = list(data["latitude"])
lon = list(data["longitude"])

map= folium.Map(location=[31.5204, 74.3587], zoom_start=6, tiles="Mapbox Bright")

fg = folium.FeatureGroup(name="My Map")

for lt, ln in zip(lat, lon):
c1 = fg.add_child(folium.Marker(location=[lt, ln], popup="Hi i am a Country",icon=folium.Icon(color='green')))

child = fg.add_child(folium.Marker(location=[31.5204, 74.5387], popup="Welcome to Lahore", icon= folium.Icon(color='green')))

map.add_child(fg)

map.save("Lahore.html")


Traceback (most recent call last):
  File "C:\Users\Ryan\AppData\Local\Programs\Python\Python36-32\check2.py", line 14, in <module>
    c1 = fg.add_child(folium.Marker(location=[lt, ln], popup="Hi i am a Country",icon=folium.Icon(color='green')))
  File "C:\Users\Ryan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\folium\map.py", line 647, in __init__
    self.location = _validate_coordinates(location)
  File "C:\Users\Ryan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\folium\utilities.py", line 48, in _validate_coordinates
    'got:\n{!r}'.format(coordinates))
ValueError: Location values cannot contain NaNs, got:
[nan, nan]

Multipart File upload Spring Boot

Latest version of SpringBoot makes uploading multiple files very easy also. On the browser side you just need the standard HTML upload form, but with multiple input elements (one per file to upload, which is very important), all having the same element name (name="files" for the example below)

Then in your Spring @Controller class on the server all you need is something like this:

@RequestMapping(value = "/upload", method = RequestMethod.POST)
    public @ResponseBody ResponseEntity<?> upload(
        @RequestParam("files") MultipartFile[] uploadFiles) throws Exception     
{
    ...now loop over all uploadFiles in the array and do what you want
  return new ResponseEntity<>(HttpStatus.OK);
}

Those are the tricky parts. That is, knowing to create multiple input elements each named "files", and knowing to use a MultipartFile[] (array) as the request parameter are the tricky things to know, but it's just that simple. I won't get into how to process a MultipartFile entry, because there's plenty of docs on that already.

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

I think it'd be okay if you commented it, e.g. // ^ == XOR.

Merging cells in Excel using Apache POI

i made a method that merge cells and put border.

protected void setMerge(Sheet sheet, int numRow, int untilRow, int numCol, int untilCol, boolean border) {
    CellRangeAddress cellMerge = new CellRangeAddress(numRow, untilRow, numCol, untilCol);
    sheet.addMergedRegion(cellMerge);
    if (border) {
        setBordersToMergedCells(sheet, cellMerge);
    }

}



protected void setBordersToMergedCells(Sheet sheet, CellRangeAddress rangeAddress) {
    RegionUtil.setBorderTop(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderLeft(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderRight(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderBottom(BorderStyle.MEDIUM, rangeAddress, sheet);
}

JOIN two SELECT statement results

Try something like this:

SELECT 
* 
FROM
(SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks) t1 
INNER JOIN
(SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks) t2
ON t1.ks = t2.ks

How to change workspace and build record Root Directory on Jenkins?

If you go into Configure under Home there is a "Help" note on how to:

Home directory /var/lib/jenkins Help for feature: Home directory

By default, Jenkins stores all of its data in this directory on the file system.

There are a few ways to change the Jenkins home directory:

Edit the JENKINS_HOME variable in your Jenkins configuration file (e.g. /etc/sysconfig/jenkins on Red Hat Linux).
Use your web container's admin tool to set the JENKINS_HOME environment variable.
Set the environment variable JENKINS_HOME before launching your web container, or before launching Jenkins directly from the WAR file.
Set the JENKINS_HOME Java system property when launching your web container, or when launching Jenkins directly from the WAR file.
Modify web.xml in jenkins.war (or its expanded image in your web container). This is not recommended. 

This value cannot be changed while Jenkins is running. It is shown here to help you ensure that your configuration is taking effect.

How to acces external json file objects in vue.js app

I have recently started working on a project using Vue JS, JSON Schema. I am trying to access nested JSON Objects from a JSON Schema file in the Vue app. I tried the below code and now I can load different JSON objects inside different Vue template tags. In the script tag add the below code

import  {JsonObject1name, JsonObject2name} from 'your Json file path';

Now you can access JsonObject1,2 names in data section of export default part as below:

data: () => ({ 
  
  schema: JsonObject1name,
  schema1: JsonObject2name,   
  
  model: {} 
}),

Now you can load the schema, schema1 data inside Vue template according to your requirement. See below code for example :

      <SchemaForm id="unique name representing your Json object1" class="form"  v-model="model" :schema="schema" :components="components">
      </SchemaForm>  

      <SchemaForm id="unique name representing your Json object2" class="form" v-model="model" :schema="schema1" :components="components">
      </SchemaForm>

SchemaForm is the local variable name for @formSchema/native library. I have implemented the data of different JSON objects through forms in different CSS tabs.

I hope this answer helps someone. I can help if there are any questions.

Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

It's pretty simple. You're trying to test the wrapper component generated by calling connect()(MyPlainComponent). That wrapper component expects to have access to a Redux store. Normally that store is available as context.store, because at the top of your component hierarchy you'd have a <Provider store={myStore} />. However, you're rendering your connected component by itself, with no store, so it's throwing an error.

You've got a few options:

  • Create a store and render a <Provider> around your connected component
  • Create a store and directly pass it in as <MyConnectedComponent store={store} /> , as the connected component will also accept "store" as a prop
  • Don't bother testing the connected component. Export the "plain", unconnected version, and test that instead. If you test your plain component and your mapStateToProps function, you can safely assume the connected version will work correctly.

You probably want to read through the "Testing" page in the Redux docs: https://redux.js.org/recipes/writing-tests.

edit:

After actually seeing that you posted source, and re-reading the error message, the real problem is not with the SportsTopPane component. The problem is that you're trying to "fully" render SportsTopPane, which also renders all of its children, rather than doing a "shallow" render like you were in the first case. The line searchComponent = <SportsDatabase sportsWholeFramework="desktop" />; is rendering a component that I assume is also connected, and therefore expects a store to be available in React's "context" feature.

At this point, you have two new options:

  • Only do "shallow" rendering of SportsTopPane, so that you're not forcing it to fully render its children
  • If you do want to do "deep" rendering of SportsTopPane, you'll need to provide a Redux store in context. I highly suggest you take a look at the Enzyme testing library, which lets you do exactly that. See http://airbnb.io/enzyme/docs/api/ReactWrapper/setContext.html for an example.

Overall, I would note that you might be trying to do too much in this one component and might want to consider breaking it into smaller pieces with less logic per component.

Check if DataRow exists by column name in c#?

You can use the DataColumnCollection of Your datatable to check if the column is in the collection.

Something like:

DataColumnCollection Columns = dtItems.Columns;

if (Columns.Contains(ColNameToCheck))
{
  row["ColNameToCheck"] = "Checked";
}

How to convert dataframe into time series?

R has multiple ways of represeting time series. Since you're working with daily prices of stocks, you may wish to consider that financial markets are closed on weekends and business holidays so that trading days and calendar days are not the same. However, you may need to work with your times series in terms of both trading days and calendar days. For example, daily returns are calculated from sequential daily closing prices regardless of whether a weekend intervenes. But you may also want to do calendar-based reporting such as weekly price summaries. For these reasons the xts package, an extension of zoo, is commonly used with financial data in R. An example of how it could be used with your data follows.

Assuming the data shown in your example is in the dataframe df

  library(xts)
  stocks <- xts(df[,-1], order.by=as.Date(df[,1], "%m/%d/%Y"))
#
#  daily returns
#
   returns <- diff(stocks, arithmetic=FALSE ) - 1
#
#  weekly open, high, low, close reports
#
   to.weekly(stocks$Hero_close, name="Hero")

which gives the output

           Hero.Open Hero.High Hero.Low Hero.Close
2013-03-15    1669.1   1684.45   1669.1    1684.45
2013-03-22    1690.5   1690.50   1623.3    1659.60
2013-03-28    1617.7   1617.70   1542.0    1542.00

Create an array or List of all dates between two dates

I know this is an old post but try using an extension method:

    public static IEnumerable<DateTime> Range(this DateTime startDate, DateTime endDate)
    {
        return Enumerable.Range(0, (endDate - startDate).Days + 1).Select(d => startDate.AddDays(d));
    }

and use it like this

    var dates = new DateTime(2000, 1, 1).Range(new DateTime(2000, 1, 31));

Feel free to choose your own dates, you don't have to restrict yourself to January 2000.

Include an SVG (hosted on GitHub) in MarkDown

I contacted GitHub to say that github.io-hosted SVGs are no longer displayed in GitHub READMEs. I received this reply:

We have had to disable svg image rendering on GitHub.com due to potential cross site scripting vulnerabilities.

Django datetime issues (default=datetime.now())

it looks like datetime.now() is being evaluated when the model is defined, and not each time you add a record.

Django has a feature to accomplish what you are trying to do already:

date = models.DateTimeField(auto_now_add=True, blank=True)

or

date = models.DateTimeField(default=datetime.now, blank=True)

The difference between the second example and what you currently have is the lack of parentheses. By passing datetime.now without the parentheses, you are passing the actual function, which will be called each time a record is added. If you pass it datetime.now(), then you are just evaluating the function and passing it the return value.

More information is available at Django's model field reference

Trying to get Laravel 5 email to work

None of the above solutions worked for me on localhost. I even allowed access from less secure apps, allowed access through display unlock captcha and set the verify peer and verify peer name to false for SSL.

Eventually, I used the open source SMTP testing solution of MailHog. The steps are as follows:

  1. Download the latest version of MailHog for your OS
  2. Specify the following settings in your .env file

MAIL_DRIVER=smtp

MAIL_HOST=127.0.0.1

MAIL_PORT=1025

MAIL_USERNAME=testuser

MAIL_PASSWORD=testpwd

MAIL_ENCRYPTION=null

[email protected]

  1. Run the downloaded file of MailHog
  2. Send Email
  3. Check sent email by going to localhost:8025

dropping rows from dataframe based on a "not in" condition

You can use Series.isin:

df = df[~df.datecolumn.isin(a)]

While the error message suggests that all() or any() can be used, they are useful only when you want to reduce the result into a single Boolean value. That is however not what you are trying to do now, which is to test the membership of every values in the Series against the external list, and keep the results intact (i.e., a Boolean Series which will then be used to slice the original DataFrame).

You can read more about this in the Gotchas.

Lombok added but getters and setters not recognized in Intellij IDEA

Go to settings->Plugins->Browse repositories and search for Lombok it will display the Lombok plugin also you will see the install option on the right side panel. Please install it. Then restart your intelliJ IDE. This has solved my issue.

Calling UserForm_Initialize() in a Module

SOLUTION After all this time, I managed to resolve the problem.

In Module: UserForms(Name).Userform_Initialize

This method works best to dynamically init the current UserForm

How do I set a value in CKEditor with Javascript?

Take care to strip out newlines from any string you pass to setData(). Otherwise an exception gets thrown.

Also note that even if you do that, then subsequently get that data again using getData(), CKEditor puts the line breaks back in.

How to parse JSON response from Alamofire API in Swift?

swift 3

pod 'Alamofire', '~> 4.4'
pod 'SwiftyJSON'

File json format:
{
    "codeAd": {
        "dateExpire": "2017/12/11",
        "codeRemoveAd":"1231243134"
        }
}

import Alamofire
import SwiftyJSON
    private func downloadJson() {
        Alamofire.request("https://yourlinkdownloadjson/abc").responseJSON { response in
            debugPrint(response)

            if let json = response.data {
                let data = JSON(data: json)
                print("data\(data["codeAd"]["dateExpire"])")
                print("data\(data["codeAd"]["codeRemoveAd"])")
            }
        }
    }

How do I detect a page refresh using jquery?

There are two events on client side as given below.

1. window.onbeforeunload (calls on Browser/tab Close & Page Load)

2. window.onload (calls on Page Load)

On server Side

public JsonResult TestAjax( string IsRefresh)
    {
        JsonResult result = new JsonResult();
        return result = Json("Called", JsonRequestBehavior.AllowGet);
    }

On Client Side

_x000D_
_x000D_
 <script type="text/javascript">_x000D_
    window.onbeforeunload = function (e) {_x000D_
        _x000D_
        $.ajax({_x000D_
            type: 'GET',_x000D_
            async: false,_x000D_
            url: '/Home/TestAjax',_x000D_
            data: { IsRefresh: 'Close' }_x000D_
        });_x000D_
    };_x000D_
_x000D_
    window.onload = function (e) {_x000D_
_x000D_
        $.ajax({_x000D_
            type: 'GET',_x000D_
            async: false,_x000D_
            url: '/Home/TestAjax',_x000D_
            data: {IsRefresh:'Load'}_x000D_
        });_x000D_
    };_x000D_
</script>
_x000D_
_x000D_
_x000D_

On Browser/Tab Close: if user close the Browser/tab, then window.onbeforeunload will fire and IsRefresh value on server side will be "Close".

On Refresh/Reload/F5: If user will refresh the page, first window.onbeforeunload will fire with IsRefresh value = "Close" and then window.onload will fire with IsRefresh value = "Load", so now you can determine at last that your page is refreshing.

Easy way to make a confirmation dialog in Angular?

Adding more options to the answer.

You could use npm i sweetalert2

Don't forget to add the style to your angular.json

"styles": [
         ...
          "node_modules/sweetalert2/src/sweetalert2.scss"
          ]

Then just import,

// ES6 Modules or TypeScript
import Swal from 'sweetalert2'


// CommonJS
const Swal = require('sweetalert2')

Boom, you are ready to go.

Swal.fire({
  title: 'Are you sure?',
  text: 'You will not be able to recover this imaginary file!',
  icon: 'warning',
  showCancelButton: true,
  confirmButtonText: 'Yes, delete it!',
  cancelButtonText: 'No, keep it'
}).then((result) => {
  if (result.value) {
    Swal.fire(
      'Deleted!',
      'Your imaginary file has been deleted.',
      'success'
    )
  // For more information about handling dismissals please visit
  // https://sweetalert2.github.io/#handling-dismissals
  } else if (result.dismiss === Swal.DismissReason.cancel) {
    Swal.fire(
      'Cancelled',
      'Your imaginary file is safe :)',
      'error'
    )
  }
})

More on this:- https://www.npmjs.com/package/sweetalert2

I do hope this helps someone.

Thanks.

How to change TextBox's Background color?

webforms;

TextBox.Background = System.Drawing.Color.Red;

How to align a div to the top of its parent but keeping its inline-block behaviour?

Or you could just add some content to the div and use inline-table

How can one grab a stack trace in C?

You can do it by walking the stack backwards. In reality, though, it's frequently easier to add an identifier onto a call stack at the beginning of each function and pop it at the end, then just walk that printing the contents. It's a bit of a PITA, but it works well and will save you time in the end.

Multiline TextView in Android?

TextView will be multi line when it wont get enough space to fit in the single line and singLine not set to true.

If it gets the space in one line it wont be multi line.

Spring MVC: how to create a default controller for index page?

We can simply map a Controller method for the default view. For eg, we have a index.html as the default page.

@RequestMapping(value = "/", method = GET)
public String index() {
    return "index";
}

once done we can access the page with default application context.

E.g http://localhost:8080/myapp

Only variables should be passed by reference

PHP complains because end() expects a reference to something that it wants to change (which can be a variable only). You however pass the result of explode() directly to end() without saving it to a variable first. At the moment when explode() returns your value, it exists only in memory and no variable points to it. You cannot create a reference to something (or to something unknown in the memory), that does not exists.

Or in other words: PHP does not know, if the value you give him is the direct value or just a pointer to the value (a pointer is also a variable (integer), which stores the offset of the memory, where the actual value resides). So PHP expects here a pointer (reference) always.

But since this is still just a notice (not even deprecated) in PHP 7, you can savely ignore notices and use the ignore-operator instead of completely deactivating error reporting for notices:

$file_extension = @end(explode('.', $file_name));

How to add an element to Array and shift indexes?

The most simple way of doing this is to use an ArrayList<Integer> and use the add(int, T) method.

List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);

// Now, we will insert the number
list.add(4, 87);

How do I commit only some files?

If you have already staged files, simply unstage them:

git reset HEAD [file-name-A.ext] [file-name-B.ext]

Then add them bit by bit back in.

What is C# analog of C++ std::pair?

The PowerCollections library (formerly available from Wintellect but now hosted on Codeplex @ http://powercollections.codeplex.com) has a generic Pair structure.

How to Get a Specific Column Value from a DataTable?

Datatables have a .Select method, which returns a rows array according to the criteria you specify. Something like this:

Dim oRows() As DataRow

oRows = dtCountries.Select("CountryName = '" & userinput & "'")

If oRows.Count = 0 Then
   ' No rows found
Else
   ' At least one row found. Could be more than one
End If

Of course, if userinput contains ' character, it would raise an exception (like if you query the database). You should escape the ' characters (I use a function to do that).

Left Join without duplicate rows from left table

You can do this using generic SQL with group by:

SELECT C.Content_ID, C.Content_Title, MAX(M.Media_Id)
FROM tbl_Contents C LEFT JOIN
     tbl_Media M
     ON M.Content_Id = C.Content_Id 
GROUP BY C.Content_ID, C.Content_Title
ORDER BY MAX(C.Content_DatePublished) ASC;

Or with a correlated subquery:

SELECT C.Content_ID, C.Contt_Title,
       (SELECT M.Media_Id
        FROM tbl_Media M
        WHERE M.Content_Id = C.Content_Id
        ORDER BY M.MEDIA_ID DESC
        LIMIT 1
       ) as Media_Id
FROM tbl_Contents C 
ORDER BY C.Content_DatePublished ASC;

Of course, the syntax for limit 1 varies between databases. Could be top. Or rownum = 1. Or fetch first 1 rows. Or something like that.

Concatenate a vector of strings/character

Matt Turner's answer is definitely the right answer. However, in the spirit of Ken Williams' answer, you could also do:

capture.output(cat(sdata, sep="")) 

What is the difference between Builder Design pattern and Factory Design pattern?

Abstract Factory & Builder pattern are both Creational patterns but with different intent.

Abstract Factory Pattern emphasizes object creation for families of related objects where:

  • Each family is a set of classes derived from a common base class/Interface.
  • Each object is returned immediately as a result of one call.

Builder pattern focuses on constructing a complex object step by step. It decouples the representation from the process of constructing the complex object, so that the same construction process can be used for different representations.

  • Builder object encapsulates configuration of the complex object.
  • Director object knows the protocol of using the Builder, where the protocol defines all logical steps required to build the complex object.

How can I reconcile detached HEAD with master/origin?

Just do this:

git checkout master

Or, if you have changes that you want to keep, do this:

git checkout -b temp
git checkout -B master temp

Fastest way to compute entropy in Python

@Sanjeet Gupta answer is good but could be condensed. This question is specifically asking about the "Fastest" way but I only see times on one answer so I'll post a comparison of using scipy and numpy to the original poster's entropy2 answer with slight alterations.

Four different approaches: scipy/numpy, numpy/math, pandas/numpy, numpy

import numpy as np
from scipy.stats import entropy
from math import log, e
import pandas as pd

import timeit

def entropy1(labels, base=None):
  value,counts = np.unique(labels, return_counts=True)
  return entropy(counts, base=base)

def entropy2(labels, base=None):
  """ Computes entropy of label distribution. """

  n_labels = len(labels)

  if n_labels <= 1:
    return 0

  value,counts = np.unique(labels, return_counts=True)
  probs = counts / n_labels
  n_classes = np.count_nonzero(probs)

  if n_classes <= 1:
    return 0

  ent = 0.

  # Compute entropy
  base = e if base is None else base
  for i in probs:
    ent -= i * log(i, base)

  return ent

def entropy3(labels, base=None):
  vc = pd.Series(labels).value_counts(normalize=True, sort=False)
  base = e if base is None else base
  return -(vc * np.log(vc)/np.log(base)).sum()

def entropy4(labels, base=None):
  value,counts = np.unique(labels, return_counts=True)
  norm_counts = counts / counts.sum()
  base = e if base is None else base
  return -(norm_counts * np.log(norm_counts)/np.log(base)).sum()

Timeit operations:

repeat_number = 1000000

a = timeit.repeat(stmt='''entropy1(labels)''',
                  setup='''labels=[1,3,5,2,3,5,3,2,1,3,4,5];from __main__ import entropy1''',
                  repeat=3, number=repeat_number)

b = timeit.repeat(stmt='''entropy2(labels)''',
                  setup='''labels=[1,3,5,2,3,5,3,2,1,3,4,5];from __main__ import entropy2''',
                  repeat=3, number=repeat_number)

c = timeit.repeat(stmt='''entropy3(labels)''',
                  setup='''labels=[1,3,5,2,3,5,3,2,1,3,4,5];from __main__ import entropy3''',
                  repeat=3, number=repeat_number)

d = timeit.repeat(stmt='''entropy4(labels)''',
                  setup='''labels=[1,3,5,2,3,5,3,2,1,3,4,5];from __main__ import entropy4''',
                  repeat=3, number=repeat_number)

Timeit results:

# for loop to print out results of timeit
for approach,timeit_results in zip(['scipy/numpy', 'numpy/math', 'pandas/numpy', 'numpy'], [a,b,c,d]):
  print('Method: {}, Avg.: {:.6f}'.format(approach, np.array(timeit_results).mean()))

Method: scipy/numpy, Avg.: 63.315312
Method: numpy/math, Avg.: 49.256894
Method: pandas/numpy, Avg.: 884.644023
Method: numpy, Avg.: 60.026938

Winner: numpy/math (entropy2)

It's also worth noting that the entropy2 function above can handle numeric AND text data. ex: entropy2(list('abcdefabacdebcab')). The original poster's answer is from 2013 and had a specific use-case for binning ints but it won't work for text.

How to return a dictionary | Python

I followed approach as shown in code below to return a dictionary. Created a class and declared dictionary as global and created a function to add value corresponding to some keys in dictionary.

**Note have used Python 2.7 so some minor modification might be required for Python 3+

class a:
    global d
    d={}
    def get_config(self,x):
        if x=='GENESYS':
            d['host'] = 'host name'
            d['port'] = '15222'
        return d

Calling get_config method using class instance in a separate python file:

from constant import a
class b:
    a().get_config('GENESYS')
    print a().get_config('GENESYS').get('host')
    print a().get_config('GENESYS').get('port')

Dropdown select with images

Check this example .. everything has been done easily http://jsfiddle.net/GHzfD/

EDIT: Updated/working as of 2013, July 02: jsfiddle.net/GHzfD/357

#webmenu{
    width:340px;
}

<select name="webmenu" id="webmenu">
    <option value="calendar" title="http://www.abe.co.nz/edit/image_cache/Hamach_300x60c0.JPG"></option>
    <option value="shopping_cart" title="http://www.nationaldirectory.com.au/sites/itchnomore/thumbs/screenshot2013-01-23at12.05.50pm_300_60.png"></option>
    <option value="cd" title="http://www.mitenterpriseforum.co.uk/wp-content/uploads/2013/01/MIT_EF_logo_300x60.jpg"></option>
    <option value="email"  selected="selected" title="http://annualreport.tacomaartmuseum.org/sites/default/files/L_AnnualReport_300x60.png"></option>
    <option value="faq" title="http://fleetfootmarketing.com/wp-content/uploads/2013/01/Wichita-Apartment-Video-Tours-CTA60-300x50.png"></option>
    <option value="games" title="http://krishnapatrika.com/images/300x50/pellipandiri300-50.gif"></option>
</select>

$("body select").msDropDown();

Getting indices of True values in a boolean list

Simply do this:

def which_index(self):
    return [
        i for i in range(len(self.states))
        if self.states[i] == True
    ]

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

For files changed between a given SHA and your current commit:

git diff --name-only <starting SHA> HEAD

or if you want to include changed-but-not-yet-committed files:

git diff --name-only <starting SHA>

More generally, the following syntax will always tell you which files changed between two commits (specified by their SHAs or other names):

git diff --name-only <commit1> <commit2>

Get href attribute on jQuery

Use $(this) for get the desire element.

function openAll()
{
     $("tr.b_row").each(function(){
        var a_href = $(this).find('.cpt h2 a').attr('href');
        alert ("Href is: "+a_href);
     });
}

Sum of Numbers C++

try this:

#include <iostream>
using namespace std;

int main()
{
    int positiveInteger;
    int startingNumber = 1;

    cout << "Please input an integer upto 100." << endl;

    cin >> positiveInteger;

    int result = 0;
    for (int i=startingNumber; i <= positiveInteger; i++)
    {
        result += i;
        cout << result;
    }

    cout << result;

    return 0;

}

Run class in Jar file

There are two types of JAR files available in Java:

  1. Runnable/Executable jar file which contains manifest file. To run a Runnable jar you can use java -jar fileName.jar or java -jar -classpath abc.jar fileName.jar

  2. Simple jar file that does not contain a manifest file so you simply run your main class by giving its path java -cp ./fileName.jar MainClass

How to convert a Java 8 Stream to an Array?

You can create a custom collector that convert a stream to array.

public static <T> Collector<T, ?, T[]> toArray( IntFunction<T[]> converter )
{
    return Collectors.collectingAndThen( 
                  Collectors.toList(), 
                  list ->list.toArray( converter.apply( list.size() ) ) );
}

and a quick use

List<String> input = Arrays.asList( ..... );

String[] result = input.stream().
         .collect( CustomCollectors.**toArray**( String[]::new ) );

Run java jar file on a server as background process

You can try this:

#!/bin/sh
nohup java -jar /web/server.jar &

The & symbol, switches the program to run in the background.

The nohup utility makes the command passed as an argument run in the background even after you log out.

Passing parameters in rails redirect_to

Route your path, and take the params, and return:

redirect_to controller: "client", action: "get_name", params: request.query_parameters and return

How to find the Vagrant IP?

Open a terminal, cd to the path of your Vagrantfile and write this

(Linux)

vagrant ssh -c "hostname -I | cut -d' ' -f2" 2>/dev/null

(OS X)

vagrant ssh -c "hostname -I | cut -d' ' -f2" 2>/dev/null | pbcopy

The command for Linux also works for windows. I have no way to test, sorry.

source: https://coderwall.com/p/etzdmq/get-vagrant-box-guest-ip-from-host

Common CSS Media Queries Break Points

Rather than try to target @media rules at specific devices, it is arguably more practical to base them on your particular layout instead. That is, gradually narrow your desktop browser window and observe the natural breakpoints for your content. It's different for every site. As long as the design flows well at each browser width, it should work pretty reliably on any screen size (and there are lots and lots of them out there.)

data.frame rows to a list

Like @flodel wrote: This converts your dataframe into a list that has the same number of elements as number of rows in dataframe:

NewList <- split(df, f = seq(nrow(df)))

You can additionaly add a function to select only those columns that are not NA in each element of the list:

NewList2 <- lapply(NewList, function(x) x[,!is.na(x)])

Where does VBA Debug.Print log to?

Debug.Print outputs to the "Immediate" window.

Debug.Print outputs to the Immediate window

Also, you can simply type ? and then a statement directly into the immediate window (and then press Enter) and have the output appear right below, like this:

simply type ? and then a statement directly into the immediate window

This can be very handy to quickly output the property of an object...

? myWidget.name

...to set the property of an object...

myWidget.name = "thingy"

...or to even execute a function or line of code, while in debugging mode:

Sheet1.MyFunction()

In .NET, which loop runs faster, 'for' or 'foreach'?

At least I haven't seen any of my collegues or higher ups saying that, that's just ridiculous considering the fact that there is no significant speed difference between for and foreach. The same applies if he is asking to use it in all cases!

How can I find the number of days between two Date objects in Ruby?

all of these steered me to the correct result, but I wound up doing

DateTime.now.mjd - DateTime.parse("01-01-1995").mjd

python: creating list from string

If you need to convert some of them to numbers and don't know in advance which ones, some additional code will be needed. Try something like this:

b = []
for x in a:
    temp = []
    items = x.split(",")
    for item in items:
        try:
            n = int(item)
        except ValueError:
            temp.append(item)
        else:
            temp.append(n)
    b.append(temp)

This is longer than the other answers, but it's more versatile.

iOS 7 status bar back to iOS 6 default style in iPhone app?

This may be a overwhelming problem if you use Auto layout because you can not directly manipulate frames anymore. There is a simple solution without too much work.

I ended up writing an utility method in an Utility Class and called it from all the view controllers's viewDidLayoutSubviews Method.

+ (void)addStatusBarIfiOS7:(UIViewController *)vc
    {
        if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {
            CGRect viewFrame = vc.view.frame;
            if(viewFrame.origin.y == 20) {
                //If the view's y origin is already 20 then don't move it down.
                return;
            }
            viewFrame.origin.y+=20.0;
            viewFrame.size.height-= 20.0;
            vc.view.frame = viewFrame;
            [vc.view layoutIfNeeded];
        }
    }

Override your viewDidLayoutSubviews method in the view controller, where you want status bar. It will get you through the burden of Autolayout.

- (void)viewDidLayoutSubviews
{
    [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleLightContent];
    [super viewDidLayoutSubviews];
    [MyUtilityClass addStatusBarIfiOS7:self];
}

How to set index.html as root file in Nginx?

in your location block you can do:

location / {
  try_files $uri $uri/index.html;
}

which will tell ngingx to look for a file with the exact name given first, and if none such file is found it will try uri/index.html. So if a request for https://www.example.com/ comes it it would look for an exact file match first, and not finding that would then check for index.html

How to send a stacktrace to log4j?

You pass the exception directly to the logger, e.g.

try {
   ...
} catch (Exception e) {
    log.error( "failed!", e );
}

It's up to log4j to render the stack trace.

find difference between two text files with one item per line

You can try

grep -f file1 file2

or

grep -v -F -x -f file1 file2

Node.js: Python not found exception due to node-sass and node-gyp

My machine is Windows 10, I've faced similar problems while tried to compile SASS using node-sass package. My node version is v10.16.3 and npm version is 6.9.0

The way that I resolved the problem:

  1. At first delete package-lock.json file and node_modules/ folder.
  2. Open Windows PowerShell as Administrator.
  3. Run the command npm i -g node-sass.
  4. After that, go to the project folder and run npm install
  5. And finally, run the SASS compiling script, in my case, it is npm run build:css

And it works!!

Bootstrap 3 panel header with buttons wrong position

You should apply a "clearfix" to clear the parent element. Next thing, the h4 for the header title, extend all the way across the header, so after you apply clearfix, it will push down the child element causing the header div to have a larger height.

Here is a fix, just replace it with your code.

  <div class="panel-heading clearfix">
     <b>Panel header</b>
       <div class="btn-group pull-right">
        <a href="#" class="btn btn-default btn-sm">## Lock</a>
        <a href="#" class="btn btn-default btn-sm">## Delete</a>
        <a href="#" class="btn btn-default btn-sm">## Move</a>
      </div>
   </div>

Editted on 12/22/2015 - added .clearfix to heading div

Dropping a connected user from an Oracle 10g database schema

my proposal is this simple anonymous block:

DECLARE
   lc_username   VARCHAR2 (32) := 'user-name-to-kill-here';
BEGIN
   FOR ln_cur IN (SELECT sid, serial# FROM v$session WHERE username = lc_username)
   LOOP
      EXECUTE IMMEDIATE ('ALTER SYSTEM KILL SESSION ''' || ln_cur.sid || ',' || ln_cur.serial# || ''' IMMEDIATE');
   END LOOP;
END;
/

How to use support FileProvider for sharing content to other apps?

As far as I can tell this will only work on newer versions of Android, so you will probably have to figure out a different way to do it. This solution works for me on 4.4, but not on 4.0 or 2.3.3, so this will not be a useful way to go about sharing content for an app that's meant to run on any Android device.

In manifest.xml:

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="com.mydomain.myapp.SharingActivity"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

Take careful note of how you specify the authorities. You must specify the activity from which you will create the URI and launch the share intent, in this case the activity is called SharingActivity. This requirement is not obvious from Google's docs!

file_paths.xml:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="just_a_name" path=""/>
</paths>

Be careful how you specify the path. The above defaults to the root of your private internal storage.

In SharingActivity.java:

Uri contentUri = FileProvider.getUriForFile(getActivity(),
"com.mydomain.myapp.SharingActivity", myFile);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("image/jpeg");
shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "Share with"));

In this example we are sharing a JPEG image.

Finally it is probably a good idea to assure yourself that you have saved the file properly and that you can access it with something like this:

File myFile = getActivity().getFileStreamPath("mySavedImage.jpeg");
if(myFile != null){
    Log.d(TAG, "File found, file description: "+myFile.toString());
}else{
    Log.w(TAG, "File not found!");
}

Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls

According to this, DatabaseGeneratedOption.Identity is not detected by a specific migration if it's added after the table has been created, which is the case I run into. So I dropped the database and that specific migration and added a new migration, finally update the database, then everything works as expected. I am using EF 6.1, SQL2014 and VS2013.

Why can't I see the "Report Data" window when creating reports?

First of all select report file with rdlc extension and then go to View > Report Data

Foreach loop in C++ equivalent of C#

The simple form:

std::string  data[] = {"ram","mohan","sita"};
std::for_each(data,data+3,std::bind1st(std::mem_fun(&Y::add), &(listbox.items)));

An example in action:

#include <algorithm>
#include <string>
#include <iostream>
#include <functional>

class Y
{
    public:
      void add(std::string value)
      {
          std::cout << "Got(" << value << ")\n";
      }
};
class X
{
    public:
      Y  items;
};

int main()
{
    X listbox;

    std::string  data[] = {"ram","mohan","sita"};
    std::for_each(data,data+3,std::bind1st(std::mem_fun(&Y::add), &(listbox.items)));
}

Adding a module (Specifically pymorph) to Spyder (Python IDE)

Using ! on the IPython console within spyder allows you to use pip. So, in the example, you could do:

[1] !pip install pymorph

Note, this is also available (though perhaps unreliably) on the Python console for Spyder versions before ~2.3.3. Thanks to @CarlosCordoba for this clarification.

How do I find out which process is locking a file using .NET?

It is very complex to invoke Win32 from C#.

You should use the tool Handle.exe.

After that your C# code have to be the following:

string fileName = @"c:\aaa.doc";//Path to locked file

Process tool = new Process();
tool.StartInfo.FileName = "handle.exe";
tool.StartInfo.Arguments = fileName+" /accepteula";
tool.StartInfo.UseShellExecute = false;
tool.StartInfo.RedirectStandardOutput = true;
tool.Start();           
tool.WaitForExit();
string outputTool = tool.StandardOutput.ReadToEnd();

string matchPattern = @"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";
foreach(Match match in Regex.Matches(outputTool, matchPattern))
{
    Process.GetProcessById(int.Parse(match.Value)).Kill();
}

onCreateOptionsMenu inside Fragments

Call

setSupportActionBar(toolbar)

inside

onViewCreated(...) 

of Fragment

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
    ((MainActivity)getActivity()).setSupportActionBar(toolbar);
    setHasOptionsMenu(true);
}