Programs & Examples On #Xcconfig

Xcode couldn't find any provisioning profiles matching

Try to check Signing settings in Build settings for your project and target. Be sure that code signing identity section has correct identities for Debug and Release.

image description here

cordova run with ios error .. Error code 65 for command: xcodebuild with args:

How to do what @connor said:

iOS

  • Open platforms/ios on XCode
  • Find & Replace io.ionic.starter in all files for a unique identifier
  • Click the project to open settings
  • Signing > Select a team
  • Go to your device Settings > General > DeviceManagement
    • Trust your account/team
  • ionic cordova run ios --device --livereload

The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig

For me the problem was with my targets tests. I already had the $(inherited) flag in my main app target.

I added it to MyAppTests Other Linker flags. After that when I ran pod install the warning message was gone. enter image description here

how to bind img src in angular 2 in ngFor?

Angular 2 and Angular 4 

In a ngFor loop it must be look like this:

<div class="column" *ngFor="let u of events ">
                <div class="thumb">
                    <img src="assets/uploads/{{u.image}}">
                    <h4>{{u.name}}</h4>
                </div>
                <div class="info">
                    <img src="assets/uploads/{{u.image}}">
                    <h4>{{u.name}}</h4>
                    <p>{{u.text}}</p>
                </div>
            </div>

What is the difference between pip and conda?

Not to confuse you further, but you can also use pip within your conda environment, which validates the general vs. python specific managers comments above.

conda install -n testenv pip
source activate testenv
pip <pip command>

you can also add pip to default packages of any environment so it is present each time so you don't have to follow the above snippet.

Enable UTF-8 encoding for JavaScript

The encoding for the page is not set correctly. Either add a header

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

or use set the appropriate http header.

Content-Type:text/html; charset=UTF-8

Firefox also allows you to change the encoding in View -> Character encoding.

If that's ok, I think javascript should handle UTF8 just fine.

How to access to the parent object in c#

Why not change the constructor on Production to let you pass in a reference at construction time:

public class Meter
{
   private int _powerRating = 0; 
   private Production _production;

   public Meter()
   {
      _production = new Production(this);
   }
}

In the Production constructor you can assign this to a private field or a property. Then Production will always have access to is parent.

How Can I Resolve:"can not open 'git-upload-pack' " error in eclipse?

You are using the wrong URL (you are using the URL for the html webpage). Try either of these instead:

  • https://github.com/facebook/facebook-android-sdk.git
  • git://github.com/facebook/facebook-android-sdk.git

Map with Key as String and Value as List in Groovy

One additional small piece that is helpful when dealing with maps/list as the value in a map is the withDefault(Closure) method on maps in groovy. Instead of doing the following code:

Map m = [:]
for(object in listOfObjects)
{
  if(m.containsKey(object.myKey))
  {
    m.get(object.myKey).add(object.myValue)
  }
  else
  {
    m.put(object.myKey, [object.myValue]
  }
}

You can do the following:

Map m = [:].withDefault{key -> return []}
for(object in listOfObjects)
{
  List valueList = m.get(object.myKey)
  m.put(object.myKey, valueList)
}

With default can be used for other things as well, but I find this the most common use case for me.

API: http://www.groovy-lang.org/gdk.html

Map -> withDefault(Closure)

Syntax error on print with Python 3

In Python 3, print became a function. This means that you need to include parenthesis now like mentioned below:

print("Hello World")

Access a URL and read Data with R

Beside of read.csv(url("...")) you also can use read.table("http://...").

Example:

> sample <- read.table("http://www.ats.ucla.edu/stat/examples/ara/angell.txt")
> sample
                V1   V2   V3   V4 V5
1        Rochester 19.0 20.6 15.0  E
2         Syracuse 17.0 15.6 20.2  E
...
43         Atlanta  4.2 70.6 32.6  S
> 

Verify a method call using Moq

You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.

You should be doing something more like this:

class MyClassTest
{
    [TestMethod]
    public void MyMethodTest()
    {
        string action = "test";
        Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();

        mockSomeClass.Setup(mock => mock.DoSomething());

        MyClass myClass = new MyClass(mockSomeClass.Object);
        myClass.MyMethod(action);

        // Explicitly verify each expectation...
        mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());

        // ...or verify everything.
        // mockSomeClass.VerifyAll();
    }
}

In other words, you are verifying that calling MyClass#MyMethod, your class will definitely call SomeClass#DoSomething once in that process. Note that you don't need the Times argument; I was just demonstrating its value.

C# DateTime to "YYYYMMDDHHMMSS" format

using C# 6.0

$"Date-{DateTime.Now:yyyyMMddHHmmss}"

How to approach a "Got minus one from a read call" error when connecting to an Amazon RDS Oracle instance

The immediate cause of the problem is that the JDBC driver has attempted to read from a network Socket that has been closed by "the other end".

This could be due to a few things:

  • If the remote server has been configured (e.g. in the "SQLNET.ora" file) to not accept connections from your IP.

  • If the JDBC url is incorrect, you could be attempting to connect to something that isn't a database.

  • If there are too many open connections to the database service, it could refuse new connections.

Given the symptoms, I think the "too many connections" scenario is the most likely. That suggests that your application is leaking connections; i.e. creating connections and then failing to (always) close them.

How can I make Bootstrap columns all the same height?

There is a problem with using Solution 1 while appling it on only column in rows. Would like to improve Solution 1.

 [class^="col-"]:not([class*="-12"]){
      margin-bottom: -99999px;
      padding-bottom: 99999px;
  }

(Sorry, can't comment Popnoodles's anwer. I have not enough reputations)

Simple calculations for working with lat/lon and km distance?

Interesting that I didn't see a mention of UTM coordinates.

https://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system.

At least if you want to add km to the same zone, it should be straightforward (in Python : https://pypi.org/project/utm/ )

utm.from_latlon and utm.to_latlon.

How do change the color of the text of an <option> within a <select>?

Try just this without the span tag:

<option selected="selected" class="grey_color">select one option</option>

For bigger flexibility you can use any JS widget.

Find the 2nd largest element in an array with minimum number of comparisons

The following solution would take 2(N-1) comparisons:

arr  #array with 'n' elements
first=arr[0]
second=-999999  #large negative no
i=1
while i is less than length(arr):
    if arr[i] greater than first:
        second=first
        first=arr[i]
    else:
        if arr[i] is greater than second and arr[i] less than first:
            second=arr[i]
    i=i+1
print second

Get value of a specific object property in C# without knowing the class behind

Use reflection

System.Reflection.PropertyInfo pi = item.GetType().GetProperty("name");
String name = (String)(pi.GetValue(item, null));

Adding a HTTP header to the Angular HttpClient doesn't send the header, why?

First, you need to add HttpHeaders with HttpClient

import { HttpClient,HttpHeaders  } from '@angular/common/http';

your constructor should be like this.

constructor(private http: HttpClient) { }

then you can use like this

   let header = new HttpHeaders({ "Authorization": "Bearer "+token});

   const requestOptions = {  headers: header};                                                                                                                                                                            

    return this.http.get<any>(url, requestOptions)
        .toPromise()
        .then(data=> {
            //...
            return data;
    });

Querying data by joining two tables in two database on different servers

A join of two tables is best done by a DBMS, so it should be done that way. You could mirror the smaller table or subset of it on one of the databases and then join them. One might get tempted of doing this on an ETL server like informatica but I guess its not advisable if the tables are huge.

Swift: Determine iOS Screen size

In Swift 3.0

let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

In older swift: Do something like this:

let screenSize: CGRect = UIScreen.mainScreen().bounds

then you can access the width and height like this:

let screenWidth = screenSize.width
let screenHeight = screenSize.height

if you want 75% of your screen's width you can go:

let screenWidth = screenSize.width * 0.75

Swift 4.0

// Screen width.
public var screenWidth: CGFloat {
    return UIScreen.main.bounds.width
}

// Screen height.
public var screenHeight: CGFloat {
    return UIScreen.main.bounds.height
}

In Swift 5.0

let screenSize: CGRect = UIScreen.main.bounds

Getting the current date in SQL Server?

SELECT CAST(GETDATE() AS DATE)

Returns the current date with the time part removed.

DATETIMEs are not "stored in the following format". They are stored in a binary format.

SELECT CAST(GETDATE() AS BINARY(8))

The display format in the question is independent of storage.

Formatting into a particular display format should be done by your application.

Python 3.4.0 with MySQL database

Maybe you can use a work around and try something like:

import datetime
#import mysql
import MySQLdb
conn = MySQLdb.connect(host = '127.0.0.1',user = 'someUser', passwd = 'foobar',db = 'foobardb')
cursor = conn.cursor()

How do I rename a column in a database table using SQL?

ALTER TABLE is standard SQL. But it's not completely implemented in many database systems.

How do I format axis number format to thousands with a comma in matplotlib?

x = [10000.21, 22000.32, 10120.54]

Perhaps make a list (comprehension) for the labels, and then apply them "manually".

xlables = [f'{label:,}' for label in x]
plt.xticks(x, xlabels)

adding noise to a signal in python

Awesome answers above. I recently had a need to generate simulated data and this is what I landed up using. Sharing in-case helpful to others as well,

import logging
__name__ = "DataSimulator"
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

import numpy as np
import pandas as pd

def generate_simulated_data(add_anomalies:bool=True, random_state:int=42):
    rnd_state = np.random.RandomState(random_state)
    time = np.linspace(0, 200, num=2000)
    pure = 20*np.sin(time/(2*np.pi))

    # concatenate on the second axis; this will allow us to mix different data 
    # distribution
    data = np.c_[pure]
    mu = np.mean(data)
    sd = np.std(data)
    logger.info(f"Data shape : {data.shape}. mu: {mu} with sd: {sd}")
    data_df = pd.DataFrame(data, columns=['Value'])
    data_df['Index'] = data_df.index.values

    # Adding gaussian jitter
    jitter = 0.3*rnd_state.normal(mu, sd, size=data_df.shape[0])
    data_df['with_jitter'] = data_df['Value'] + jitter

    index_further_away = None
    if add_anomalies:
        # As per the 68-95-99.7 rule(also known as the empirical rule) mu+-2*sd 
        # covers 95.4% of the dataset.
        # Since, anomalies are considered to be rare and typically within the 
        # 5-10% of the data; this filtering
        # technique might work 
        #for us(https://en.wikipedia.org/wiki/68%E2%80%9395%E2%80%9399.7_rule)
        indexes_furhter_away = np.where(np.abs(data_df['with_jitter']) > (mu + 
         2*sd))[0]
        logger.info(f"Number of points further away : 
        {len(indexes_furhter_away)}. Indexes: {indexes_furhter_away}")
        # Generate a point uniformly and embed it into the dataset
        random = rnd_state.uniform(0, 5, 1)
        data_df.loc[indexes_furhter_away, 'with_jitter'] +=  
        random*data_df.loc[indexes_furhter_away, 'with_jitter']
    return data_df, indexes_furhter_away

In Perl, how to remove ^M from a file?

^M is carriage return. You can do this:

$str =~ s/\r//g

Jquery array.push() not working

another workaround:

var myarray = [];
$("#test").click(function() {
    myarray[index]=$("#drop").val();
    alert(myarray);
});

i wanted to add all checked checkbox to array. so example, if .each is used:

var vpp = [];
var incr=0;
$('.prsn').each(function(idx) {
   if (this.checked) {
       var p=$('.pp').eq(idx).val();
       vpp[incr]=(p);
       incr++;
   }
});
//do what ever with vpp array;

Should I use Java's String.format() if performance is important?

I just modified hhafez's test to include StringBuilder. StringBuilder is 33 times faster than String.format using jdk 1.6.0_10 client on XP. Using the -server switch lowers the factor to 20.

public class StringTest {

   public static void main( String[] args ) {
      test();
      test();
   }

   private static void test() {
      int i = 0;
      long prev_time = System.currentTimeMillis();
      long time;

      for ( i = 0; i < 1000000; i++ ) {
         String s = "Blah" + i + "Blah";
      }
      time = System.currentTimeMillis() - prev_time;

      System.out.println("Time after for loop " + time);

      prev_time = System.currentTimeMillis();
      for ( i = 0; i < 1000000; i++ ) {
         String s = String.format("Blah %d Blah", i);
      }
      time = System.currentTimeMillis() - prev_time;
      System.out.println("Time after for loop " + time);

      prev_time = System.currentTimeMillis();
      for ( i = 0; i < 1000000; i++ ) {
         new StringBuilder("Blah").append(i).append("Blah");
      }
      time = System.currentTimeMillis() - prev_time;
      System.out.println("Time after for loop " + time);
   }
}

While this might sound drastic, I consider it to be relevant only in rare cases, because the absolute numbers are pretty low: 4 s for 1 million simple String.format calls is sort of ok - as long as I use them for logging or the like.

Update: As pointed out by sjbotha in the comments, the StringBuilder test is invalid, since it is missing a final .toString().

The correct speed-up factor from String.format(.) to StringBuilder is 23 on my machine (16 with the -server switch).

How to limit depth for recursive file list?

All I'm really interested in is the ownership and permissions information for the first level subdirectories.

I found a easy solution while playing my fish, which fits your need perfectly.

ll `ls`

or

ls -l $(ls)

$(...).datepicker is not a function - JQuery - Bootstrap

Not the right function name I think

$(document).ready(function() {

    $('.datepicker').datetimepicker({
        format: 'dd/mm/yyyy'
    });
});

How do you delete all text above a certain line

kdgg

delete all lines above the current one.

How to get names of enum entries?

To get the list of the enum values you have to use:

enum AnimalEnum {
  DOG = "dog", 
  CAT = "cat", 
  MOUSE = "mouse"
}

Object.values(AnimalEnum);

How can I tell where mongoDB is storing data? (its not in the default /data/db!)

While this question is targeted for Linux/Unix instances of Mongo, it's one of the first search results regardless of the operating system used, so for future Windows users that find this:

If MongoDB is set up as a Windows Service in the default manner, you can usually find it by looking at the 'Path to executable' entry in the MongoDB Service's Properties:

Properties Window showing 'Path to Executable' option

get DATEDIFF excluding weekends using sql server

I just want to share the code I created that might help you.

DECLARE @MyCounter int = 0, @TempDate datetime, @EndDate datetime;
SET @TempDate = DATEADD(d,1,'2017-5-27')
SET @EndDate = '2017-6-3'

WHILE @TempDate <= @EndDate
    BEGIN
    IF DATENAME(DW,@TempDate) = 'Sunday' OR DATENAME(DW,@TempDate) = 'Saturday'
        SET @MyCounter = @MyCounter
    ELSE IF @TempDate not in ('2017-1-1', '2017-1-16', '2017-2-20', '2017-5-29', '2017-7-4', '2017-9-4', '2017-10-9', '2017-11-11', '2017-12-25')
        SET @MyCounter = @MyCounter + 1

    SET @TempDate = DATEADD(d,1,@TempDate)
    CONTINUE

END
PRINT @MyCounter
PRINT @TempDate

If you do have a holiday table, you can also use that so that you don't have to list all the holidays in the ELSE IF section of the code. You can also create a function for this code and use the function whenever you need it in your query.

I hope this might help too.

Laravel PHP Command Not Found

I set the PATH,but it didn't work.I find other way to solve it. (OSX 10.10 & laravel 5.2)
1) find the executable file:

~/.composer/vendor/laravel/installer/laravel 

2) give execute permissions:

chmod +x ~/.composer/vendor/laravel/installer/laravel 

3) make a soft link to /usr/bin:

sudo ln -s /Users/zhao/.composer/vendor/laravel/installer/laravel /usr/bin/laravel

img tag displays wrong orientation

Your image is actually upside down. But it has a meta attribute "Orientation" which tells the viewer it should be the rotated 180 degrees. Some devices/viewers don't obey this rule.

Open it in Chrome: right way up Open it in FF: right way up Open it in IE: upside down

Open it in Paint: Upside down Open it in Photoshop: Right way up. etc.

How to set the holo dark theme in a Android app?

By default android will set Holo to the Dark theme. There is no theme called Holo.Dark, there's only Holo.Light, that's why you are getting the resource not found error.

So just set it to:

<style name="AppTheme" parent="android:Theme.Holo" />

Android: How to use webcam in emulator?

Follow the below steps in Eclipse.

  1. Goto -> AVD Manager
  2. Create/Edit the AVD.
  3. Hardware > New:
  4. Configures camera facing back
  5. Click on the property value and choose = "webcam0".
  6. Once done all the above the webcam should be connected. If it doesnt then you need to check your WebCam drivers.

Check here for more information : How to use web camera in android emulator to capture a live image?

enter image description here

How can I call a method in Objective-C?

Use this:

[self score]; you don't need @sel for calling directly

How to convert column with dtype as object to string in Pandas Dataframe

Did you try assigning it back to the column?

df['column'] = df['column'].astype('str') 

Referring to this question, the pandas dataframe stores the pointers to the strings and hence it is of type 'object'. As per the docs ,You could try:

df['column_new'] = df['column'].str.split(',') 

How to split string using delimiter char using T-SQL?

It is terrible, but you can try to use

select
SUBSTRING(Table1.Col1,0,PATINDEX('%|%=',Table1.Col1)) as myString
from
Table1

This code is probably not 100% right though. need to be adjusted

pop/remove items out of a python tuple

ok I figured out a crude way of doing it.

I store the "n" value in the for loop when condition is satisfied in a list (lets call it delList) then do the following:

    for ii in sorted(delList, reverse=True):
    tupleX.pop(ii)

Any other suggestions are welcome too.

Why do I get the error "Unsafe code may only appear if compiling with /unsafe"?

To use unsafe code blocks, open the properties for the project, go to the Build tab and check the Allow unsafe code checkbox, then compile and run.

class myclass
{
     public static void Main(string[] args)
     {
         unsafe
         {
             int iData = 10;
             int* pData = &iData;
             Console.WriteLine("Data is " + iData);
             Console.WriteLine("Address is " + (int)pData);
         }
     }
}

Output:

Data is 10
Address is 1831848

Received an invalid column length from the bcp client for colid 6

One of the data columns in the excel (Column Id 6) has one or more cell data that exceed the datacolumn datatype length in the database.

Verify the data in excel. Also verify the data in the excel for its format to be in compliance with the database table schema.

To avoid this, try exceeding the data-length of the string datatype in the database table.

Hope this helps.

How to change the data type of a column without dropping the column with query?

ALTER TABLE YourTableNameHere ALTER COLUMN YourColumnNameHere VARCHAR(20)

How can I get screen resolution in java?

This is the resolution of the screen that the given component is currently assigned (something like most part of the root window is visible on that screen).

public Rectangle getCurrentScreenBounds(Component component) {
    return component.getGraphicsConfiguration().getBounds();
}

Usage:

Rectangle currentScreen = getCurrentScreenBounds(frameOrWhateverComponent);
int currentScreenWidth = currentScreen.width // current screen width
int currentScreenHeight = currentScreen.height // current screen height
// absolute coordinate of current screen > 0 if left of this screen are further screens
int xOfCurrentScreen = currentScreen.x

If you want to respect toolbars, etc. you'll need to calculate with this, too:

GraphicsConfiguration gc = component.getGraphicsConfiguration();
Insets screenInsets = Toolkit.getDefaultToolkit().getScreenInsets(gc);

Uncaught TypeError: data.push is not a function

Also make sure that the name of the variable is not some kind of a language keyword. For instance, the following produces the same type of error:

var history = [];
history.push("what a mess");

replacing it for:

var history123 = [];
history123.push("pray for a better language");

works as expected.

Display PDF within web browser

I recently needed to provide a more mobile-friendly, responsive version of a .pdf document, because narrow phone screens required scrolling right and left a lot. To allow just vertical scrolling and avoid horizontal scrolling, the following steps worked for me:

  • Open the .pdf in Chrome browser
  • Click Open with Google Docs
  • Click File > Download > Web Page
  • Click on the downloaded document to unzip it
  • Click on the unzipped HTML document to open it in Chrome browser
  • Press fn F12 to open Chrome Dev Tools
  • Paste copy(document.documentElement.outerHTML.replace(/padding:72pt 72pt 72pt 72pt;/, '').replace(/margin-right:.*?pt/g, '')) into the Console, and press Enter to copy the tweaked document to the clipboard
  • Open a text editor (e.g., Notepad), or in my case VSCode, paste, and save with a .html extension.

The result looked good and was usable in both desktop and mobile environments.

Using Colormaps to set color of line in matplotlib

U may do as I have written from my deleted account (ban for new posts :( there was). Its rather simple and nice looking.

Im using 3-rd one of these 3 ones usually, also I wasny checking 1 and 2 version.

from matplotlib.pyplot import cm
import numpy as np

#variable n should be number of curves to plot (I skipped this earlier thinking that it is obvious when looking at picture - sorry my bad mistake xD): n=len(array_of_curves_to_plot)
#version 1:

color=cm.rainbow(np.linspace(0,1,n))
for i,c in zip(range(n),color):
   ax1.plot(x, y,c=c)

#or version 2: - faster and better:

color=iter(cm.rainbow(np.linspace(0,1,n)))
c=next(color)
plt.plot(x,y,c=c)

#or version 3:

color=iter(cm.rainbow(np.linspace(0,1,n)))
for i in range(n):
   c=next(color)
   ax1.plot(x, y,c=c)

example of 3:

Ship RAO of Roll vs Ikeda damping in function of Roll amplitude A44

How do I find out which keystore was used to sign an app?

You can do this with the apksigner tool that is part of the Android SDK:

apksigner verify --print-certs my_app.apk

You can find apksigner inside the build-tools directory. For example: ~/Library/Android/sdk/build-tools/29.0.1/apksigner

subsetting a Python DataFrame

Just for someone looking for a solution more similar to R:

df[(df.Product == p_id) & (df.Time> start_time) & (df.Time < end_time)][['Time','Product']]

No need for data.loc or query, but I do think it is a bit long.

How can I get argv[] as int?

You can use the function int atoi (const char * str);.
You need to include #include <stdlib.h> and use the function in this way:
int x = atoi(argv[1]);
Here more information if needed: atoi - C++ Reference

What arguments are passed into AsyncTask<arg1, arg2, arg3>?

Google's Android Documentation Says that :

An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

AsyncTask's generic types :

The three types used by an asynchronous task are the following:

Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the background computation.
Result, the type of the result of the background computation.

Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:

 private class MyTask extends AsyncTask<Void, Void, Void> { ... }

You Can further refer : http://developer.android.com/reference/android/os/AsyncTask.html

Or You Can clear whats the role of AsyncTask by refering Sankar-Ganesh's Blog

Well The structure of a typical AsyncTask class goes like :

private class MyTask extends AsyncTask<X, Y, Z>

    protected void onPreExecute(){

    }

This method is executed before starting the new Thread. There is no input/output values, so just initialize variables or whatever you think you need to do.

    protected Z doInBackground(X...x){

    }

The most important method in the AsyncTask class. You have to place here all the stuff you want to do in the background, in a different thread from the main one. Here we have as an input value an array of objects from the type “X” (Do you see in the header? We have “...extends AsyncTask” These are the TYPES of the input parameters) and returns an object from the type “Z”.

   protected void onProgressUpdate(Y y){

   }

This method is called using the method publishProgress(y) and it is usually used when you want to show any progress or information in the main screen, like a progress bar showing the progress of the operation you are doing in the background.

  protected void onPostExecute(Z z){

  }

This method is called after the operation in the background is done. As an input parameter you will receive the output parameter of the doInBackground method.

What about the X, Y and Z types?

As you can deduce from the above structure:

 X – The type of the input variables value you want to set to the background process. This can be an array of objects.

 Y – The type of the objects you are going to enter in the onProgressUpdate method.

 Z – The type of the result from the operations you have done in the background process.

How do we call this task from an outside class? Just with the following two lines:

MyTask myTask = new MyTask();

myTask.execute(x);

Where x is the input parameter of the type X.

Once we have our task running, we can find out its status from “outside”. Using the “getStatus()” method.

 myTask.getStatus();

and we can receive the following status:

RUNNING - Indicates that the task is running.

PENDING - Indicates that the task has not been executed yet.

FINISHED - Indicates that onPostExecute(Z) has finished.

Hints about using AsyncTask

  1. Do not call the methods onPreExecute, doInBackground and onPostExecute manually. This is automatically done by the system.

  2. You cannot call an AsyncTask inside another AsyncTask or Thread. The call of the method execute must be done in the UI Thread.

  3. The method onPostExecute is executed in the UI Thread (here you can call another AsyncTask!).

  4. The input parameters of the task can be an Object array, this way you can put whatever objects and types you want.

FragmentActivity to Fragment

first of all;

a Fragment must be inside a FragmentActivity, that's the first rule,

a FragmentActivity is quite similar to a standart Activity that you already know, besides having some Fragment oriented methods

second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView, where you inflate your layout, think of it as the setContentLayout

here is an example:

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     mView       = inflater.inflate(R.layout.fragment_layout, container, false);       return mView; } 

and continu your work based on that mView, so to find a View by id, call mView.findViewById(..);


for the FragmentActivity part:

the xml part "must" have a FrameLayout in order to inflate a fragment in it

        <FrameLayout             android:id="@+id/content_frame"             android:layout_width="match_parent"             android:layout_height="match_parent"  >         </FrameLayout> 

as for the inflation part

getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();


begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site

Cell color changing in Excel using C#

For text:

[RangeObject].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

For cell background

[RangeObject].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

Get the year from specified date php

You wrote that format can change from YYYY-mm-dd to dd-mm-YYYY you can try to find year there

$parts = explode("-","2068-06-15");
for ($i = 0; $i < count($parts); $i++)
{
     if(strlen($parts[$i]) == 4)
     {
          $year = $parts[$i];
          break;
      }
  }

How to set dropdown arrow in spinner?

Set the Dropdown arrow image to spinner like this :

<Spinner
    android:id="@+id/Exam_Course"
    android:layout_width="320dp"
    android:background="@drawable/spinner_bg"
    android:layout_height="wrap_content"/>

Here android:background="@drawable/spinner_bg" the spinner_bg is the Dropdown arrow image.

How to run a single RSpec test?

In rails 5,

I used this way to run single test file(all the tests in one file)

rails test -n /TopicsControllerTest/ -v

Class name can be used to match to the desired file TopicsControllerTest

My class class TopicsControllerTest < ActionDispatch::IntegrationTest

Output :

enter image description here

If You want you can tweak the regex to match to single test method \TopicsControllerTest#test_Should_delete\

rails test -n /TopicsControllerTest#test_Should_delete/ -v

Node.js: how to consume SOAP XML web service

Adding to Kim .J's solution: you can add preserveWhitespace=true in order to avoid a Whitespace error. Like this:

soap.CreateClient(url,preserveWhitespace=true,function(...){

ALTER TABLE add constraint

alter table User 
    add constraint userProperties
    foreign key (properties)
    references Properties(ID)

Python how to write to a binary file?

This is exactly what bytearray is for:

newFileByteArray = bytearray(newFileBytes)
newFile.write(newFileByteArray)

If you're using Python 3.x, you can use bytes instead (and probably ought to, as it signals your intention better). But in Python 2.x, that won't work, because bytes is just an alias for str. As usual, showing with the interactive interpreter is easier than explaining with text, so let me just do that.

Python 3.x:

>>> bytearray(newFileBytes)
bytearray(b'{\x03\xff\x00d')
>>> bytes(newFileBytes)
b'{\x03\xff\x00d'

Python 2.x:

>>> bytearray(newFileBytes)
bytearray(b'{\x03\xff\x00d')
>>> bytes(newFileBytes)
'[123, 3, 255, 0, 100]'

React-router urls don't work when refreshing or writing manually

Adding more information to Joshua Dyck's answer.

If you are using Firebase and want to use both the root route and a sub-directory route you need to add the following code in your firebase.json:

{
  "hosting": {
    "rewrites": [
      {
        "source": "*",
        "destination": "/index.html"
      },
      {
        "source": "/subdirectory/**",
        "destination": "/subdirectory/index.html"
      }
    ]
  }
}

Example:

You are building a website for a client. You want the owner of the website to add information in https://your.domain.com/management while the users of the website will navigate to https://your.domain.com.

In this case your firebase.json file will look like that:

{
  "hosting": {
    "rewrites": [
      {
        "source": "*",
        "destination": "/index.html"
      },
      {
        "source": "/management/**",
        "destination": "/management/index.html"
      }
    ]
  }
}

How to save a PNG image server-side, from a base64 data string

based on drew010 example I made a working example for easy understanding.

imagesaver("data:image/jpeg;base64,/9j/4AAQSkZJ"); //use full base64 data 

function imagesaver($image_data){

    list($type, $data) = explode(';', $image_data); // exploding data for later checking and validating 

    if (preg_match('/^data:image\/(\w+);base64,/', $image_data, $type)) {
        $data = substr($data, strpos($data, ',') + 1);
        $type = strtolower($type[1]); // jpg, png, gif

        if (!in_array($type, [ 'jpg', 'jpeg', 'gif', 'png' ])) {
            throw new \Exception('invalid image type');
        }

        $data = base64_decode($data);

        if ($data === false) {
            throw new \Exception('base64_decode failed');
        }
    } else {
        throw new \Exception('did not match data URI with image data');
    }

    $fullname = time().$type;

    if(file_put_contents($fullname, $data)){
        $result = $fullname;
    }else{
        $result =  "error";
    }
    /* it will return image name if image is saved successfully 
    or it will return error on failing to save image. */
    return $result; 
}

jQuery AJAX form using mail() PHP script sends email, but POST data from HTML form is undefined

You are using the wrong parameters name, try:

if($_POST){
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['text'];

//send email
    mail("[email protected]", "51 Deep comment from" .$email, $message);
}

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 71 bytes)

I changed the memory limit from .htaccess and this problem got resolved.

I was trying to scan my website from one of the antivirus plugin and there I was getting this problem. I increased memory by pasting this in my .htaccess file in Wordpress folder:

php_value memory_limit 512M

After scan was over, I removed this line to make the size as it was before.

Opening A Specific File With A Batch File?

you are in a situation where you cannot set a certain program as the default program to use when opening a certain type of file, I've found using a .bat file handy. In my case, Textpad runs on my machine via Microsoft Application Virtualization ("AppV"). The path to Textpad is in an "AppV directory" so to speak. My Textpad AppV shortcut has this as a target...

%ALLUSERSPROFILE%\Microsoft\AppV\Client\Integration\
 12345ABC-A1BC-1A23-1A23-1234567E1234\Root\TextPad.exe

To associate the textpad.exe with 'txt' files via a 'bat' file:

1) In Explorer, create a new ('txt') file and save as opentextpad.bat in an "appropriate" location

2) In the opentextpad.bat file, type this line:

textpad.exe %1  

3) Save and Close

4) In explorer, perform windows file association by right-clicking on a 'txt' file (e.g. 'dummy.txt') and choose 'Open with > Choose default program...' from the menu. In the 'Open with' window, click 'Browse...', then navigate to and select your textpad.bat file. Click 'Open'. You'll return to the 'Open with' window. Make sure to check the 'Always use the selected program to open this type of file' checkbox. Click 'OK' and the window will close.

When you open a 'txt' file now, it will open the file with 'textpad.exe'.

Hope this is useful.

How to create multiple output paths in Webpack config

u can do lik

var config = {
    // TODO: Add common Configuration
    module: {},
};

var x= Object.assign({}, config, {
    name: "x",
    entry: "./public/x/js/x.js",
    output: {
       path: __dirname+"/public/x/jsbuild",
       filename: "xbundle.js"
    },
});
var y= Object.assign({}, config, {
    name: "y",
    entry: "./public/y/js/FBRscript.js",
    output: {
       path: __dirname+"/public/fbr/jsbuild",
       filename: "ybundle.js"
    },
});

let list=[x,y];

for(item of list){
    module.exports =item;
}

HTTPS connections over proxy servers

You can accomplish this using man-in-the-middle techniques with dynamic SSL generation. Take a look at mitmproxy - it's a Python based, SSL-capable MITM proxy.

How exactly does __attribute__((constructor)) work?

  1. It runs when a shared library is loaded, typically during program startup.
  2. That's how all GCC attributes are; presumably to distinguish them from function calls.
  3. GCC-specific syntax.
  4. Yes, this works in C and C++.
  5. No, the function does not need to be static.
  6. The destructor runs when the shared library is unloaded, typically at program exit.

So, the way the constructors and destructors work is that the shared object file contains special sections (.ctors and .dtors on ELF) which contain references to the functions marked with the constructor and destructor attributes, respectively. When the library is loaded/unloaded the dynamic loader program (ld.so or somesuch) checks whether such sections exist, and if so, calls the functions referenced therein.

Come to think of it, there is probably some similar magic in the normal static linker so that the same code is run on startup/shutdown regardless if the user chooses static or dynamic linking.

Why doesn't java.util.Set have get(int index)?

Actually this is a recurring question when writing JavaEE applications which use Object-Relational Mapping (for example with Hibernate); and from all the people who replied here, Andreas Petersson is the only one who understood the real issue and offered the correct answer to it: Java is missing a UniqueList! (or you can also call it OrderedSet, or IndexedSet).

Maxwing mentioned this use-case (in which you need ordered AND unique data) and he suggested the SortedSet, but this is not what Marty Pitt really needed.

This "IndexedSet" is NOT the same as a SortedSet - in a SortedSet the elements are sorted by using a Comparator (or using their "natural" ordering).

But instead it is closer to a LinkedHashSet (which others also suggested), or even more so to an (also inexistent) "ArrayListSet", because it guarantees that the elements are returned in the same order as they were inserted.

But the LinkedHashSet is an implementation, not an interface! What is needed is an IndexedSet (or ListSet, or OrderedSet, or UniqueList) interface! This will allow the programmer to specify that he needs a collection of elements that have a specific order and without duplicates, and then instantiate it with any implementation (for example an implementation provided by Hibernate).

Since JDK is open-source, maybe this interface will be finally included in Java 7...

adding onclick event to dynamically added button?

but.onclick = function() { yourjavascriptfunction();};

or

but.onclick = function() { functionwithparam(param);};

How to listen state changes in react.js?

The following lifecycle methods will be called when state changes. You can use the provided arguments and the current state to determine if something meaningful changed.

componentWillUpdate(object nextProps, object nextState)
componentDidUpdate(object prevProps, object prevState)

How can I split a text file using PowerShell?

I often need to do the same thing. The trick is getting the header repeated into each of the split chunks. I wrote the following cmdlet (PowerShell v2 CTP 3) and it does the trick.

##############################################################################
#.SYNOPSIS
# Breaks a text file into multiple text files in a destination, where each
# file contains a maximum number of lines.
#
#.DESCRIPTION
# When working with files that have a header, it is often desirable to have
# the header information repeated in all of the split files. Split-File
# supports this functionality with the -rc (RepeatCount) parameter.
#
#.PARAMETER Path
# Specifies the path to an item. Wildcards are permitted.
#
#.PARAMETER LiteralPath
# Specifies the path to an item. Unlike Path, the value of LiteralPath is
# used exactly as it is typed. No characters are interpreted as wildcards.
# If the path includes escape characters, enclose it in single quotation marks.
# Single quotation marks tell Windows PowerShell not to interpret any
# characters as escape sequences.
#
#.PARAMETER Destination
# (Or -d) The location in which to place the chunked output files.
#
#.PARAMETER Count
# (Or -c) The maximum number of lines in each file.
#
#.PARAMETER RepeatCount
# (Or -rc) Specifies the number of "header" lines from the input file that will
# be repeated in each output file. Typically this is 0 or 1 but it can be any
# number of lines.
#
#.EXAMPLE
# Split-File bigfile.csv 3000 -rc 1
#
#.LINK 
# Out-TempFile
##############################################################################
function Split-File {

    [CmdletBinding(DefaultParameterSetName='Path')]
    param(

        [Parameter(ParameterSetName='Path', Position=1, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
        [String[]]$Path,

        [Alias("PSPath")]
        [Parameter(ParameterSetName='LiteralPath', Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
        [String[]]$LiteralPath,

        [Alias('c')]
        [Parameter(Position=2,Mandatory=$true)]
        [Int32]$Count,

        [Alias('d')]
        [Parameter(Position=3)]
        [String]$Destination='.',

        [Alias('rc')]
        [Parameter()]
        [Int32]$RepeatCount

    )

    process {

        # yeah! the cmdlet supports wildcards
        if ($LiteralPath) { $ResolveArgs = @{LiteralPath=$LiteralPath} }
        elseif ($Path) { $ResolveArgs = @{Path=$Path} }

        Resolve-Path @ResolveArgs | %{

            $InputName = [IO.Path]::GetFileNameWithoutExtension($_)
            $InputExt  = [IO.Path]::GetExtension($_)

            if ($RepeatCount) { $Header = Get-Content $_ -TotalCount:$RepeatCount }

            # get the input file in manageable chunks

            $Part = 1
            Get-Content $_ -ReadCount:$Count | %{

                # make an output filename with a suffix
                $OutputFile = Join-Path $Destination ('{0}-{1:0000}{2}' -f ($InputName,$Part,$InputExt))

                # In the first iteration the header will be
                # copied to the output file as usual
                # on subsequent iterations we have to do it
                if ($RepeatCount -and $Part -gt 1) {
                    Set-Content $OutputFile $Header
                }

                # write this chunk to the output file
                Write-Host "Writing $OutputFile"
                Add-Content $OutputFile $_

                $Part += 1

            }

        }

    }

}

Granting DBA privileges to user in Oracle

You need only to write:

GRANT DBA TO NewDBA;

Because this already makes the user a DB Administrator

How to delete columns that contain ONLY NAs?

Here is a dplyr solution:

df %>% select_if(~sum(!is.na(.)) > 0)

Update: The summarise_if() function is superseded as of dplyr 1.0. Here are two other solutions that use the where() tidyselect function:

df %>% 
  select(
    where(
      ~sum(!is.na(.x)) > 0
    )
  )
df %>% 
  select(
    where(
      ~!all(is.na(.x))
    )
  )

How may I reference the script tag that loaded the currently-executing script?

I was inserting script tags dynamically with this usual alternative to eval and simply set a global property currentComponentScript right before adding to the DOM.

  const old = el.querySelector("script")[0];
  const replacement = document.createElement("script");
  replacement.setAttribute("type", "module");
  replacement.appendChild(document.createTextNode(old.innerHTML));
  window.currentComponentScript = replacement;
  old.replaceWith(replacement);

Doesn't work in a loop though. The DOM doesn't run the scripts until the next macrotask so a batch of them will only see the last value set. You'd have to setTimeout the whole paragraph, and then setTimeout the next one after the previous finishes. I.e. chain the setTimeouts, not just call setTimeout multiple times in a row from a loop.

How can building a heap be O(n) time complexity?

Your analysis is correct. However, it is not tight.

It is not really easy to explain why building a heap is a linear operation, you should better read it.

A great analysis of the algorithm can be seen here.


The main idea is that in the build_heap algorithm the actual heapify cost is not O(log n)for all elements.

When heapify is called, the running time depends on how far an element might move down in tree before the process terminates. In other words, it depends on the height of the element in the heap. In the worst case, the element might go down all the way to the leaf level.

Let us count the work done level by level.

At the bottommost level, there are 2^(h)nodes, but we do not call heapify on any of these, so the work is 0. At the next to level there are 2^(h - 1) nodes, and each might move down by 1 level. At the 3rd level from the bottom, there are 2^(h - 2) nodes, and each might move down by 2 levels.

As you can see not all heapify operations are O(log n), this is why you are getting O(n).

When to use dynamic vs. static libraries

I'd give a general rule of thumb that if you have a large codebase, all built on top of lower level libraries (eg a Utils or Gui framework), which you want to partition into more manageable libraries then make them static libraries. Dynamic libraries don't really buy you anything and there are fewer surprises -- there will only be one instance of singletons for instance.

If you have a library that is entirely separate to the rest of the codebase (eg a third party library) then consider making it a dll. If the library is LGPL you may need to use a dll anyway due to the licensing conditions.

How do I convert this list of dictionaries to a csv file?

import csv
toCSV = [{'name':'bob','age':25,'weight':200},
         {'name':'jim','age':31,'weight':180}]
keys = toCSV[0].keys()
with open('people.csv', 'w', newline='')  as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(toCSV)

EDIT: My prior solution doesn't handle the order. As noted by Wilduck, DictWriter is more appropriate here.

How to install an APK file on an Android phone?

outside device,we can use :

adb install file.apk

or adb install -r file.apk

  adb install [-l] [-r] [-s] [--algo <algorithm name> --key <hex-encoded key> --iv <hex-encoded iv>] <file>
                               - push this package file to the device and install it
                                 ('-l' means forward-lock the app)
                                 ('-r' means reinstall the app, keeping its data)
                                 ('-s' means install on SD card instead of internal storage)
                                 ('--algo', '--key', and '--iv' mean the file is encrypted already)

inside devices also, we can use:

pm install file.apk

or pm install -r file.apk

pm install: installs a package to the system.  Options:
    -l: install the package with FORWARD_LOCK.
    -r: reinstall an exisiting app, keeping its data.
    -t: allow test .apks to be installed.
    -i: specify the installer package name.
    -s: install package on sdcard.
    -f: install package on internal flash.
    -d: allow version code downgrade.

For more then one apk file on Linux we can use xargs and on windows we can use for loop.
Linux / Unix sample :

ls -1 *.apk | xargs -I xxx adb install -r xxx

Where are static variables stored in C and C++?

It depends on the platform and compiler that you're using. Some compilers store directly in the code segment. Static variables are always only accessible to the current translation unit and the names are not exported thus the reason name collisions never occur.

Call and receive output from Python script in Java?

I met the same problem before, also read the answers here, but doesn't found any satisfy solution can balance the compatibility, performance and well format output, the Jython can't work with extend C packages and slower than CPython. So finally I decided to invent the wheel myself, it took my 5 nights, I hope it can help you too: jpserve(https://github.com/johnhuang-cn/jpserve).

JPserve provides a simple way to call Python and exchange the result by well format JSON, few performance loss. The following is the sample code.

At first, start jpserve on Python side

>>> from jpserve.jpserve import JPServe
>>> serve = JPServe(("localhost", 8888))
>>> serve.start()

INFO:JPServe:JPServe starting...
INFO:JPServe:JPServe listening in localhost 8888

Then call Python from JAVA side:

PyServeContext.init("localhost", 8888);
PyExecutor executor = PyServeContext.getExecutor();
script = "a = 2\n"
    + "b = 3\n"
    + "_result_ = a * b";

PyResult rs = executor.exec(script);
System.out.println("Result: " + rs.getResult());

---
Result: 6

SQL Query to search schema of all tables

  select object_name(c.object_id) as table_name
    , schema_name(t.schema_id) as schema_name
    from sys.columns c
    join sys.tables t on c.object_id = t.object_id
     where c.name=N'CreatedDate';

It gets a little more complicated if you want alsoother table properties, but you'll refer to the object catalog views like sys.tables, sys.columns etc.

Calculating distance between two points (Latitude, Longitude)

As you're using SQL 2008 or later, I'd recommend checking out the GEOGRAPHY data type. SQL has built in support for geospatial queries.

e.g. you'd have a column in your table of type GEOGRAPHY which would be populated with a geospatial representation of the coordinates (check out the MSDN reference linked above for examples). This datatype then exposes methods allowing you to perform a whole host of geospatial queries (e.g. finding the distance between 2 points)

How can I check which version of Angular I'm using?

For AngularJS - Use angular.version

_x000D_
_x000D_
console.log(angular.version);
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>
_x000D_
_x000D_
_x000D_

For more information, see

How to build a 'release' APK in Android Studio?

Follow this steps:

-Build
-Generate Signed Apk
-Create new

Then fill up "New Key Store" form. If you wand to change .jnk file destination then chick on destination and give a name to get Ok button. After finishing it you will get "Key store password", "Key alias", "Key password" Press next and change your the destination folder. Then press finish, thats all. :)

enter image description here

enter image description here enter image description here

enter image description here enter image description here

What's the default password of mariadb on fedora?

The default password is empty. More accurately, you don't even NEED a password to login as root on the localhost. You just need to BE root. But if you need to set the password the first time (if you allow remote access to root), you need to use:

sudo mysql_secure_installation

Enter empty password, then follow the instructions.

The problem you are having is that you need to BE root when you try to login as root from the local machine.

On Linux: mariadb will accept a connection as root on the socket (localhost) ONLY IF THE USER ASKING IT IS ROOT. Which means that even if you try

mysql -u root -p

And have the correct password you will be refused access. Same goes for

mysql_secure_installation

Mariadb will always refuse the password because the current user is not root. So you need to call them with sudo (or as the root user on your machine) So locally you just want to use:

sudo mysql

and

sudo mysql_secure_installation

When moving from mysql to mariadb it took I will for me to figure this out.

Conditional Formatting using Excel VBA code

I think I just discovered a way to apply overlapping conditions in the expected way using VBA. After hours of trying out different approaches I found that what worked was changing the "Applies to" range for the conditional format rule, after every single one was created!

This is my working example:

Sub ResetFormatting()
' ----------------------------------------------------------------------------------------
' Written by..: Julius Getz Mørk
' Purpose.....: If conditional formatting ranges are broken it might cause a huge increase
'               in duplicated formatting rules that in turn will significantly slow down
'               the spreadsheet.
'               This macro is designed to reset all formatting rules to default.
' ---------------------------------------------------------------------------------------- 

On Error GoTo ErrHandler

' Make sure we are positioned in the correct sheet
WS_PROMO.Select

' Disable Events
Application.EnableEvents = False

' Delete all conditional formatting rules in sheet
Cells.FormatConditions.Delete

' CREATE ALL THE CONDITIONAL FORMATTING RULES:

' (1) Make negative values red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlLess, "=0")
    .Font.Color = -16776961
    .StopIfTrue = False
End With

' (2) Highlight defined good margin as green values
With Cells(1, 1).FormatConditions.add(xlCellValue, xlGreater, "=CP_HIGH_MARGIN_DEFINITION")
    .Font.Color = -16744448
    .StopIfTrue = False
End With

' (3) Make article strategy "D" red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""D""")
    .Font.Bold = True
    .Font.Color = -16776961
    .StopIfTrue = False
End With

' (4) Make article strategy "A" blue
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""A""")
    .Font.Bold = True
    .Font.Color = -10092544
    .StopIfTrue = False
End With

' (5) Make article strategy "W" green
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""W""")
    .Font.Bold = True
    .Font.Color = -16744448
    .StopIfTrue = False
End With

' (6) Show special cost in bold green font
With Cells(1, 1).FormatConditions.add(xlCellValue, xlNotEqual, "=0")
    .Font.Bold = True
    .Font.Color = -16744448
    .StopIfTrue = False
End With

' (7) Highlight duplicate heading names. There can be none.
With Cells(1, 1).FormatConditions.AddUniqueValues
    .DupeUnique = xlDuplicate
    .Font.Color = -16383844
    .Interior.Color = 13551615
    .StopIfTrue = False
End With

' (8) Make heading rows bold with yellow background
With Cells(1, 1).FormatConditions.add(Type:=xlExpression, Formula1:="=IF($B8=""H"";TRUE;FALSE)")
    .Font.Bold = True
    .Interior.Color = 13434879
    .StopIfTrue = False
End With

' Modify the "Applies To" ranges
Cells.FormatConditions(1).ModifyAppliesToRange Range("O8:P507")
Cells.FormatConditions(2).ModifyAppliesToRange Range("O8:O507")
Cells.FormatConditions(3).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(4).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(5).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(6).ModifyAppliesToRange Range("E8:E507")
Cells.FormatConditions(7).ModifyAppliesToRange Range("A7:AE7")
Cells.FormatConditions(8).ModifyAppliesToRange Range("B8:L507")


ErrHandler:
Application.EnableEvents = False

End Sub

How much should a function trust another function

That's where constructors come into play. If you have a default constructor (eg. with no parameters) that always creates a new Map, then you're sure that every instance of this class will always have an already instantiated Map.

Multiple rows to one comma-separated value in Sql Server

Test Data

DECLARE @Table1 TABLE(ID INT, Value INT)
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)

Query

SELECT  ID
       ,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
         FROM @Table1 
         WHERE ID = t.ID
         FOR XML PATH(''), TYPE)
        .value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t
GROUP BY ID

Result Set

+--------------------------+
¦ ID ¦     List_Output     ¦
¦----+---------------------¦
¦  1 ¦  100, 200, 300, 400 ¦
+--------------------------+

SQL Server 2017 and Later Versions

If you are working on SQL Server 2017 or later versions, you can use built-in SQL Server Function STRING_AGG to create the comma delimited list:

DECLARE @Table1 TABLE(ID INT, Value INT);
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400);


SELECT ID , STRING_AGG([Value], ', ') AS List_Output
FROM @Table1
GROUP BY ID;

Result Set

+--------------------------+
¦ ID ¦     List_Output     ¦
¦----+---------------------¦
¦  1 ¦  100, 200, 300, 400 ¦
+--------------------------+

One DbContext per web request... why?

There are two contradicting recommendations by microsoft and many people use DbContexts in a completely divergent manner.

  1. One recommendation is to "Dispose DbContexts as soon as posible" because having a DbContext Alive occupies valuable resources like db connections etc....
  2. The other states that One DbContext per request is highly reccomended

Those contradict to each other because if your Request is doing a lot of unrelated to the Db stuff , then your DbContext is kept for no reason. Thus it is waste to keep your DbContext alive while your request is just waiting for random stuff to get done...

So many people who follow rule 1 have their DbContexts inside their "Repository pattern" and create a new Instance per Database Query so X*DbContext per Request

They just get their data and dispose the context ASAP. This is considered by MANY people an acceptable practice. While this has the benefits of occupying your db resources for the minimum time it clearly sacrifices all the UnitOfWork and Caching candy EF has to offer.

Keeping alive a single multipurpose instance of DbContext maximizes the benefits of Caching but since DbContext is not thread safe and each Web request runs on it's own thread, a DbContext per Request is the longest you can keep it.

So EF's team recommendation about using 1 Db Context per request it's clearly based on the fact that in a Web Application a UnitOfWork most likely is going to be within one request and that request has one thread. So one DbContext per request is like the ideal benefit of UnitOfWork and Caching.

But in many cases this is not true. I consider Logging a separate UnitOfWork thus having a new DbContext for Post-Request Logging in async threads is completely acceptable

So Finally it turns down that a DbContext's lifetime is restricted to these two parameters. UnitOfWork and Thread

semaphore implementation

Vary the consumer-rate and the producer-rate (using sleep), to better understand the operation of code. The code below is the consumer-producer simulation (over a max-limit on container).

Code for your reference:

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>

sem_t semP, semC;
int stock_count = 0;
const int stock_max_limit=5;

void *producer(void *arg) {
    int i, sum=0;
    for (i = 0; i < 10; i++) {

        while(stock_max_limit == stock_count){
            printf("stock overflow, production on wait..\n");
            sem_wait(&semC);
            printf("production operation continues..\n");
        }

        sleep(1);   //production decided here
        stock_count++;
        printf("P::stock-count : %d\n",stock_count);
        sem_post(&semP);
        printf("P::post signal..\n");
    }
 }

void *consumer(void *arg) {
    int i, sum=0;
    for (i = 0; i < 10; i++) {

        while(0 == stock_count){
            printf("stock empty, consumer on wait..\n");
            sem_wait(&semP);
            printf("consumer operation continues..\n");
        }

        sleep(2);   //consumer rate decided here
        stock_count--;
        printf("C::stock-count : %d\n", stock_count);
        sem_post(&semC);
        printf("C::post signal..\n");
        }
}

int main(void) {

    pthread_t tid0,tid1;
    sem_init(&semP, 0, 0);
    sem_init(&semC, 0, 0);

        pthread_create(&tid0, NULL, consumer, NULL);
        pthread_create(&tid1, NULL, producer, NULL);
        pthread_join(tid0, NULL);
        pthread_join(tid1, NULL);

    sem_destroy(&semC);
    sem_destroy(&semP);

    return 0;
}

C# ASP.NET Single Sign-On Implementation

There are several Identity providers with SSO support out of the box, also third-party** products.

** The only problem with third party products is that they charge per user/month, and it can be quite expensive.

Some of the tools available and with APIs for .NET are:

If you decide to go with your own implementation, you could use the frameworks below categorized by programming language.

  • C#

    • IdentityServer3 (OAuth/OpenID protocols, OWIN/Katana)
    • IdentityServer4 (OAuth/OpenID protocols, ASP.NET Core)
    • OAuth 2.0 by Okta
  • Javascript

    • passport-openidconnect (node.js)
    • oidc-provider (node.js)
    • openid-client (node.js)
  • Python

    • pyoidc
    • Django OIDC Provider

I would go with IdentityServer4 and ASP.NET Core application, it's easy configurable and you can also add your own authentication provider. It uses OAuth/OpenID protocols which are newer than SAML 2.0 and WS-Federation.

this.getClass().getClassLoader().getResource("...") and NullPointerException

It should be getResource("/install.xml");

The resource names are relative to where the getClass() class resides, e.g. if your test is org/example/foo/MyTest.class then getResource("install.xml") will look in org/example/foo/install.xml.

If your install.xml is in src/test/resources, it's in the root of the classpath, hence you need to prepend the resource name with /.

Also, if it works only sometimes, then it might be because Eclipse has cleaned the output directory (e.g. target/test-classes) and the resource is simply missing from the runtime classpath. Verify that using the Navigator view of Eclipse instead of the Package explorer. If the files is missing, run the mvn package goal.

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

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

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

Saving to CSV in Excel loses regional date format

Change the date and time settings for your computer in the "short date" format under calendar settings. This will change the format for everything yyyy-mm-dd or however you want it to display; but remember it will look like that even for files saved on your computer.

At least it works.

Viewing full output of PS command

Evidence for truncation mentioned by others, (a personal example)

foo=$(ps -p 689 -o command); echo "$foo"

COMMAND
/opt/conda/bin/python -m ipykernel_launcher -f /root/.local/share/jupyter/runtime/kernel-5732db1a-d484-4a58-9d67-de6ef5ac721b.json

That ^^ captures that long output in a variable As opposed to

ps -p 689 -o command

COMMAND
/opt/conda/bin/python -m ipykernel_launcher -f /root/.local/share/jupyter/runtim

Since I was trying this from a Docker jupyter notebook, I needed to run this with the bang of course ..

!foo=$(ps -p 689 -o command); echo "$foo"

Surprisingly jupyter notebooks let you execute even that! But glad to help find the offending notebook taking up all my memory =D

Uninstall all installed gems, in OSX?

I did that not too long ago (same poster-child RVM switcher situation):

gem list | cut -d" " -f1 | sudo xargs gem uninstall -Iax

Takes the list of all gems (incl. version stuff), cuts it to keep only the gem name, then uninstalls all versions of such gems.

The sudo is only useful if you had gems installed system-wide, and should not be included unless necessary.

Get the selected value in a dropdown using jQuery.

Hello guys i am using this technique to get the values from the selected dropdown list and it is working like charm.

var methodvalue = $("#method option:selected").val(); 

Callback functions in Java

I found the idea of implementing using the reflect library interesting and came up with this which I think works quite well. The only down side is losing the compile time check that you are passing valid parameters.

public class CallBack {
    private String methodName;
    private Object scope;

    public CallBack(Object scope, String methodName) {
        this.methodName = methodName;
        this.scope = scope;
    }

    public Object invoke(Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        Method method = scope.getClass().getMethod(methodName, getParameterClasses(parameters));
        return method.invoke(scope, parameters);
    }

    private Class[] getParameterClasses(Object... parameters) {
        Class[] classes = new Class[parameters.length];
        for (int i=0; i < classes.length; i++) {
            classes[i] = parameters[i].getClass();
        }
        return classes;
    }
}

You use it like this

public class CallBackTest {
    @Test
    public void testCallBack() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        TestClass testClass = new TestClass();
        CallBack callBack = new CallBack(testClass, "hello");
        callBack.invoke();
        callBack.invoke("Fred");
    }

    public class TestClass {
        public void hello() {
            System.out.println("Hello World");
        }

        public void hello(String name) {
            System.out.println("Hello " + name);
        }
    }
}

Best way to get the max value in a Spark dataframe column

in pyspark you can do this:

max(df.select('ColumnName').rdd.flatMap(lambda x: x).collect())

How do I get the YouTube video ID from a URL?

Late to the game here, but I've mashed up two excellent responses from mantish and j-w. First, the modified regex:

const youtube_regex = /^.*(youtu\.be\/|vi?\/|u\/\w\/|embed\/|\?vi?=|\&vi?=)([^#\&\?]*).*/

Here's the test code (I've added mantish's original test cases to j-w's nastier ones):

 var urls = [
      'http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index',
      'http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o',
      'http://www.youtube.com/v/0zM3nApSvMg?fs=1&amp;hl=en_US&amp;rel=0',
      'http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s',
      'http://www.youtube.com/embed/0zM3nApSvMg?rel=0',
      'http://www.youtube.com/watch?v=0zM3nApSvMg',
      'http://youtu.be/0zM3nApSvMg',
      '//www.youtube-nocookie.com/embed/up_lNV-yoK4?rel=0',
      'http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo',
      'http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel',
      'http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub',
      'http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I',
      'http://www.youtube.com/user/SilkRoadTheatre#p/a/u/2/6dwqZw0j_jY',
      'http://youtu.be/6dwqZw0j_jY',
      'http://www.youtube.com/watch?v=6dwqZw0j_jY&feature=youtu.be',
      'http://youtu.be/afa-5HQHiAs',
      'http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo?rel=0',
      'http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel',
      'http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub',
      'http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I',
      'http://www.youtube.com/embed/nas1rJpm7wY?rel=0',
      'http://www.youtube.com/watch?v=peFZbP64dsU',
      'http://youtube.com/v/dQw4w9WgXcQ?feature=youtube_gdata_player',
      'http://youtube.com/vi/dQw4w9WgXcQ?feature=youtube_gdata_player',
      'http://youtube.com/?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
      'http://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
      'http://youtube.com/?vi=dQw4w9WgXcQ&feature=youtube_gdata_player',
      'http://youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
      'http://youtube.com/watch?vi=dQw4w9WgXcQ&feature=youtube_gdata_player',
      'http://youtu.be/dQw4w9WgXcQ?feature=youtube_gdata_player'
  ];

  var failures = 0;
  urls.forEach(url => {
    const parsed = url.match(youtube_regex);
    if (parsed && parsed[2]) {
      console.log(parsed[2]);
    } else {
      failures++;
      console.error(url, parsed);
    }
  });
  if (failures) {
    console.error(failures, 'failed');
  }

Experimental version to handle the m.youtube urls mentioned in comments:

const youtube_regex = /^.*((m\.)?youtu\.be\/|vi?\/|u\/\w\/|embed\/|\?vi?=|\&vi?=)([^#\&\?]*).*/

It requires parsed[2] to be changed to parsed[3] in two places in the tests (which it then passes with m.youtube urls added to the tests). Let me know if you see problems.

What is the cleanest way to get the progress of JQuery ajax request?

jQuery has an AjaxSetup() function that allows you to register global ajax handlers such as beforeSend and complete for all ajax calls as well as allow you to access the xhr object to do the progress that you are looking for

Laravel redirect back to original destination after login

Larvel 5.3 this actually worked for me by just updating LoginController.php

 use Illuminate\Support\Facades\Session;
 use Illuminate\Support\Facades\URL;


public function __construct()
{
    $this->middleware('guest', ['except' => 'logout']);
    Session::set('backUrl', URL::previous());
}


public function redirectTo()
{
    return Session::get('backUrl') ? Session::get('backUrl') :   $this->redirectTo;
}

ref: https://laracasts.com/discuss/channels/laravel/redirect-to-previous-page-after-login

set option "selected" attribute from dynamic created option

Make option defaultSelected

HTMLOptionElement.defaultSelected = true;     // JS
$('selector').prop({defaultSelected: true});  // jQuery  

HTMLOptionElement MDN

If the SELECT element is already added to the document (statically or dynamically), to set an option to Attribute-selected and to make it survive a HTMLFormElement.reset() - defaultSelected is used:

_x000D_
_x000D_
const EL_country = document.querySelector('#country');_x000D_
EL_country.value = 'ID';   // Set SELECT value to 'ID' ("Indonesia")_x000D_
EL_country.options[EL_country.selectedIndex].defaultSelected = true; // Add Attribute selected to Option Element_x000D_
_x000D_
document.forms[0].reset(); // "Indonesia" is still selected
_x000D_
<form>_x000D_
  <select name="country" id="country">_x000D_
    <option value="AF">Afghanistan</option>_x000D_
    <option value="AL">Albania</option>_x000D_
    <option value="HR">Croatia</option>_x000D_
    <option value="ID">Indonesia</option>_x000D_
    <option value="ZW">Zimbabwe</option>_x000D_
  </select>_x000D_
</form>
_x000D_
_x000D_
_x000D_

The above will also work if you build the options dynamically, and than (only afterwards) you want to set one option to be defaultSelected.

_x000D_
_x000D_
const countries = {_x000D_
  AF: 'Afghanistan',_x000D_
  AL: 'Albania',_x000D_
  HR: 'Croatia',_x000D_
  ID: 'Indonesia',_x000D_
  ZW: 'Zimbabwe',_x000D_
};_x000D_
_x000D_
const EL_country = document.querySelector('#country');_x000D_
_x000D_
// (Bad example. Ideally use .createDocumentFragment() and .appendChild() methods)_x000D_
EL_country.innerHTML = Object.keys(countries).reduce((str, key) => str += `<option value="${key}">${countries[key]}</option>`, ''); _x000D_
_x000D_
EL_country.value = 'ID';_x000D_
EL_country.options[EL_country.selectedIndex].defaultSelected = true;_x000D_
_x000D_
document.forms[0].reset(); // "Indonesia" is still selected
_x000D_
<form>_x000D_
  <select name="country" id="country"></select>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Option gets Attribute selected by using defaultSelected

Make option defaultSelected while dynamically creating options

To make an option selected while populating the SELECT Element, use the Option() constructor MDN

var optionElementReference = new Option(text, value, defaultSelected, selected);

_x000D_
_x000D_
const countries = {_x000D_
  AF: 'Afghanistan',_x000D_
  AL: 'Albania',_x000D_
  HR: 'Croatia',_x000D_
  ID: 'Indonesia',     // <<< make this one defaultSelected_x000D_
  ZW: 'Zimbabwe',_x000D_
};_x000D_
_x000D_
const EL_country = document.querySelector('#country');_x000D_
const DF_options = document.createDocumentFragment();_x000D_
_x000D_
Object.keys(countries).forEach(key => {_x000D_
  const isIndonesia = key === 'ID';  // Boolean_x000D_
  DF_options.appendChild(new Option(countries[key], key, isIndonesia, isIndonesia))_x000D_
});_x000D_
_x000D_
EL_country.appendChild(DF_options);_x000D_
_x000D_
document.forms[0].reset(); // "Indonesia" is still selected
_x000D_
<form>_x000D_
  <select name="country" id="country"></select>_x000D_
</form>
_x000D_
_x000D_
_x000D_

In the demo above Document.createDocumentFragment is used to prevent rendering elements inside the DOM in a loop. Instead, the fragment (containing all the Options) is appended to the Select only once.


SELECT.value vs. OPTION.setAttribute vs. OPTION.selected vs. OPTION.defaultSelected

Although some (older) browsers interpret the OPTION's selected attribute as a "string" state, the WHATWG HTML Specifications html.spec.whatwg.org state that it should represent a Boolean selectedness

The selectedness of an option element is a boolean state, initially false. Except where otherwise specified, when the element is created, its selectedness must be set to true if the element has a selected attribute.
html.spec.whatwg.org - Option selectedness

one can correctly deduce that just the name selected in <option value="foo" selected> is enough to set a truthy state.


Comparison test of the different methods

_x000D_
_x000D_
const EL_select = document.querySelector('#country');_x000D_
const TPL_options = `_x000D_
  <option value="AF">Afghanistan</option>_x000D_
  <option value="AL">Albania</option>_x000D_
  <option value="HR">Croatia</option>_x000D_
  <option value="ID">Indonesia</option>_x000D_
  <option value="ZW">Zimbabwe</option>_x000D_
`;_x000D_
_x000D_
// https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/MutationObserver_x000D_
const mutationCB = (mutationsList, observer) => {_x000D_
  mutationsList.forEach(mu => {_x000D_
    const EL = mu.target;_x000D_
    if (mu.type === 'attributes') {_x000D_
      return console.log(`* Attribute ${mu.attributeName} Mutation. ${EL.value}(${EL.text})`);_x000D_
    }_x000D_
  });_x000D_
};_x000D_
_x000D_
// (PREPARE SOME TEST FUNCTIONS)_x000D_
_x000D_
const testOptionsSelectedByProperty = () => {_x000D_
  const test = 'OPTION with Property selected:';_x000D_
  try {_x000D_
    const EL = [...EL_select.options].find(opt => opt.selected);_x000D_
    console.log(`${test} ${EL.value}(${EL.text}) PropSelectedValue: ${EL.selected}`);_x000D_
  } catch (e) {_x000D_
    console.log(`${test} NOT FOUND!`);_x000D_
  }_x000D_
} _x000D_
_x000D_
const testOptionsSelectedByAttribute = () => {_x000D_
  const test = 'OPTION with Attribute selected:'_x000D_
  try {_x000D_
    const EL = [...EL_select.options].find(opt => opt.hasAttribute('selected'));_x000D_
    console.log(`${test} ${EL.value}(${EL.text}) AttrSelectedValue: ${EL.getAttribute('selected')}`);_x000D_
  } catch (e) {_x000D_
    console.log(`${test} NOT FOUND!`);_x000D_
  }_x000D_
} _x000D_
_x000D_
const testSelect = () => {_x000D_
  console.log(`SELECT value:${EL_select.value} selectedIndex:${EL_select.selectedIndex}`);_x000D_
}_x000D_
_x000D_
const formReset = () => {_x000D_
  EL_select.value = '';_x000D_
  EL_select.innerHTML = TPL_options;_x000D_
  // Attach MutationObserver to every Option to track if Attribute will change_x000D_
  [...EL_select.options].forEach(EL_option => {_x000D_
    const observer = new MutationObserver(mutationCB);_x000D_
    observer.observe(EL_option, {attributes: true});_x000D_
  });_x000D_
}_x000D_
_x000D_
// -----------_x000D_
// LET'S TEST! _x000D_
_x000D_
console.log('\n1. Set SELECT value');_x000D_
formReset();_x000D_
EL_select.value = 'AL'; // Constatation: MutationObserver did NOT triggered!!!!_x000D_
testOptionsSelectedByProperty();_x000D_
testOptionsSelectedByAttribute();_x000D_
testSelect();_x000D_
_x000D_
console.log('\n2. Set HTMLElement.setAttribute()');_x000D_
formReset();_x000D_
EL_select.options[2].setAttribute('selected', true); // MutationObserver triggers_x000D_
testOptionsSelectedByProperty();_x000D_
testOptionsSelectedByAttribute();_x000D_
testSelect();_x000D_
_x000D_
console.log('\n3. Set HTMLOptionElement.defaultSelected');_x000D_
formReset();_x000D_
EL_select.options[3].defaultSelected = true; // MutationObserver triggers_x000D_
testOptionsSelectedByProperty();_x000D_
testOptionsSelectedByAttribute();_x000D_
testSelect();_x000D_
_x000D_
console.log('\n4. Set SELECT value and HTMLOptionElement.defaultSelected');_x000D_
formReset();_x000D_
EL_select.value = 'ZW'_x000D_
EL_select.options[EL_select.selectedIndex].defaultSelected = true; // MutationObserver triggers_x000D_
testOptionsSelectedByProperty();_x000D_
testOptionsSelectedByAttribute();_x000D_
testSelect();_x000D_
_x000D_
/* END */_x000D_
console.log('\n*. Getting MutationObservers out from call-stack...');
_x000D_
<form>_x000D_
  <select name="country" id="country"></select>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Although the test 2. using .setAttribute() seems at first the best solution since both the Element Property and Attribute are unison, it can lead to confusion, specially because .setAttribute expects two parameters:

EL_select.options[1].setAttribute('selected', false);
// <option value="AL" selected="false"> // But still selected!

will actually make the option selected

Should one use .removeAttribute() or perhaps .setAttribute('selected', ???) to another value? Or should one read the state by using .getAttribute('selected') or by using .hasAttribute('selected')?

Instead test 3. (and 4.) using defaultSelected gives the expected results:

  • Attribute selected as a named Selectedness state.
  • Property selected on the Element Object, with a Boolean value.

How to filter data in dataview

DataView view = new DataView();
view.Table = DataSet1.Tables["Suppliers"];
view.RowFilter = "City = 'Berlin'";
view.RowStateFilter = DataViewRowState.ModifiedCurrent;
view.Sort = "CompanyName DESC";

// Simple-bind to a TextBox control
Text1.DataBindings.Add("Text", view, "CompanyName");

Ref: http://www.csharp-examples.net/dataview-rowfilter/

http://msdn.microsoft.com/en-us/library/system.data.dataview.rowfilter.aspx

Ruby on Rails - Import Data from a CSV file

The better way is to include it in a rake task. Create import.rake file inside /lib/tasks/ and put this code to that file.

desc "Imports a CSV file into an ActiveRecord table"
task :csv_model_import, [:filename, :model] => [:environment] do |task,args|
  lines = File.new(args[:filename], "r:ISO-8859-1").readlines
  header = lines.shift.strip
  keys = header.split(',')
  lines.each do |line|
    values = line.strip.split(',')
    attributes = Hash[keys.zip values]
    Module.const_get(args[:model]).create(attributes)
  end
end

After that run this command in your terminal rake csv_model_import[file.csv,Name_of_the_Model]

Add User to Role ASP.NET Identity

While I agree with the other answers regarding the RoleManager, I would advice to examine the possibility to implement Authorization through Claims (Expressing Roles as Claims).

Starting with the .NET Framework 4.5, Windows Identity Foundation (WIF) has been fully integrated into the .NET Framework.

In claims-aware applications, the role is expressed by a role claim type that should be available in the token. When the IsInRole() method is called, there is a check made to see if the current user has that role.

The role claim type is expressed using the following URI: "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"

So instead of using the RoleManager, you can "add a user to a role" from the UserManager, doing something like this:

var um = new UserManager();
um.AddClaimAsync(1, new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", "administrator"));

With the above lines you have added a role claim with the value "administrator" to the user with the id "1"...

Claims authorization, as suggested by MSFT, can simplify and increase the performance of authentication and authorization processes eliminating some back-end queries every time authorization takes place.

Using Claims you may not need the RoleStore anymore. (AspNetRoles, AspNetUserRoles)

How do I hide an element on a click event anywhere outside of the element?

  $(document).on('click', function(e) { // Hides the div by clicking any where in the screen
        if ( $(e.target).closest('#suggest_input').length ) {
            $(".suggest_div").show();
        }else if ( ! $(e.target).closest('.suggest_container').length ) {
            $('.suggest_div').hide();
        }
    });

Here #suggest_input in is the name of textbox and .suggest_container is the ul class name and .suggest_div is the main div element for my auto-suggest.

this code is for hiding the div elements by clicking any where in the screen. Before doing every thing please understand the code and copy it...

Ubuntu says "bash: ./program Permission denied"

Try this:

sudo chmod +x program_name
./program_name 

Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)

For Wordpress

In my case i just missed the slash "/" after get_template_directory_uri() so resulted / generated path was wrong:

My Wrong code :

wp_enqueue_script( 'retina-js', get_template_directory_uri().'js/retina.min.js' ); 

My Corrected Code :

wp_enqueue_script( 'retina-js', get_template_directory_uri().'/js/retina.min.js' );

How can I post an array of string to ASP.NET MVC Controller without a form?

Thanks everyone for the answers. Another quick solution will be to use jQuery.param method with traditional parameter set to true to convert JSON object to string:

$.post("/your/url", $.param(yourJsonObject,true));

What is the shortest function for reading a cookie by name in JavaScript?

Here goes.. Cheers!

function getCookie(n) {
    let a = `; ${document.cookie}`.match(`;\\s*${n}=([^;]+)`);
    return a ? a[1] : '';
}

Note that I made use of ES6's template strings to compose the regex expression.

convert month from name to number

Maybe use a combination with strtotime() and date()?

nginx: how to create an alias url route?

server {
  server_name example.com;
  root /path/to/root;
  location / {
    # bla bla
  }
  location /demo {
    alias /path/to/root/production/folder/here;
  }
}

If you need to use try_files inside /demo you'll need to replace alias with a root and do a rewrite because of the bug explained here

Conditional Logic on Pandas DataFrame

Just compare the column with that value:

In [9]: df = pandas.DataFrame([1,2,3,4], columns=["data"])

In [10]: df
Out[10]: 
   data
0     1
1     2
2     3
3     4

In [11]: df["desired"] = df["data"] > 2.5
In [11]: df
Out[12]: 
   data desired
0     1   False
1     2   False
2     3    True
3     4    True

python pandas: Remove duplicates by columns A, keeping the row with the highest value in column B

Simplest solution:

To drop duplicates based on one column:

df = df.drop_duplicates('column_name', keep='last')

To drop duplicates based on multiple columns:

df = df.drop_duplicates(['col_name1','col_name2','col_name3'], keep='last')

How to run console application from Windows Service?

Starting from Windows Vista, a service cannot interact with the desktop. You will not be able to see any windows or console windows that are started from a service. See this MSDN forum thread.

On other OS, there is an option that is available in the service option called "Allow Service to interact with desktop". Technically, you should program for the future and should follow the Vista guideline even if you don't use it on Vista.

If you still want to run an application that never interact with the desktop, try specifying the process to not use the shell.

ProcessStartInfo info = new ProcessStartInfo(@"c:\myprogram.exe");
info.UseShellExecute = false;
info.RedirectStandardError = true;
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.CreateNoWindow = true;
info.ErrorDialog = false;
info.WindowStyle = ProcessWindowStyle.Hidden;

Process process = Process.Start(info);

See if this does the trick.

First you inform Windows that the program won't use the shell (which is inaccessible in Vista to service).

Secondly, you redirect all consoles interaction to internal stream (see process.StandardInput and process.StandardOutput.

How to increase time in web.config for executing sql query

I realise I'm a litle late to the game, but just spent over a day on trying to change the timeout of a webservice. It seemed to have a default timeout of 30 seconds. I after changing evry other timeout value I could find, including:

  • DB connection string Connect Timeout
  • httpRuntime executionTimeout
  • basicHttpBinding binding closeTimeout
  • basicHttpBinding binding sendTimeout
  • basicHttpBinding binding receiveTimeout
  • basicHttpBinding binding openTimeout

Finaley I found that it was the SqlCommand timeout that was defaulting to 30 seconds.

I decided to just duplicate the timeout of the connection string to the command. The connection string is configured in the web.config.

Some code:

namespace ROS.WebService.Common
{
  using System;
  using System.Configuration;
  using System.Data;
  using System.Data.SqlClient;

  public static class DataAccess
  {
    public static string ConnectionString { get; private set; }

    static DataAccess()
    {
      ConnectionString = ConfigurationManager.ConnectionStrings["ROSdb"].ConnectionString;
    }

    public static int ExecuteNonQuery(string cmdText, CommandType cmdType, params SqlParameter[] sqlParams)
    {
      using (SqlConnection conn = new SqlConnection(DataAccess.ConnectionString))
      {
        using (SqlCommand cmd = new SqlCommand(cmdText, conn) { CommandType = cmdType, CommandTimeout = conn.ConnectionTimeout })
        {
          foreach (var p in sqlParams) cmd.Parameters.Add(p);
          cmd.Connection.Open();
          return cmd.ExecuteNonQuery();
        }
      }
    }
  }
}

Change introduced to "duplicate" the timeout value from the connection string:CommandTimeout = conn.ConnectionTimeout

Div Size Automatically size of content

I faced the same issue and I resolved it by using: max-width: fit-content;

What's the difference between struct and class in .NET?

Instances of classes are stored on the managed heap. All variables 'containing' an instance are simply a reference to the instance on the heap. Passing an object to a method results in a copy of the reference being passed, not the object itself.

Structures (technically, value types) are stored wherever they are used, much like a primitive type. The contents may be copied by the runtime at any time and without invoking a customised copy-constructor. Passing a value type to a method involves copying the entire value, again without invoking any customisable code.

The distinction is made better by the C++/CLI names: "ref class" is a class as described first, "value class" is a class as described second. The keywords "class" and "struct" as used by C# are simply something that must be learned.

Android: View.setID(int id) programmatically - how to avoid ID conflicts?

Since API 17, the View class has a static method generateViewId() that will

generate a value suitable for use in setId(int)

What is compiler, linker, loader?

  • Compiler: A language translator that converts a complete program into machine language to produce a program that the computer can process in its entirety.
  • Linker: Utility program which takes one or more compiled object files and combines them into an executable file or another object file.
  • Loader: loads the executable code into memory ,creates the program and data stack , initializes the registers and starts the code running.

Detect if HTML5 Video element is playing

It seems to me like you could just check for !stream.paused.

How do I delete unpushed git commits?

For your reference, I believe you can "hard cut" commits out of your current branch not only with git reset --hard, but also with the following command:

git checkout -B <branch-name> <SHA>

In fact, if you don't care about checking out, you can set the branch to whatever you want with:

git branch -f <branch-name> <SHA>

This would be a programmatic way to remove commits from a branch, for instance, in order to copy new commits to it (using rebase).

Suppose you have a branch that is disconnected from master because you have taken sources from some other location and dumped it into the branch.

You now have a branch in which you have applied changes, let's call it "topic".

You will now create a duplicate of your topic branch and then rebase it onto the source code dump that is sitting in branch "dump":

git branch topic_duplicate topic
git rebase --onto dump master topic_duplicate

Now your changes are reapplied in branch topic_duplicate based on the starting point of "dump" but only the commits that have happened since "master". So your changes since master are now reapplied on top of "dump" but the result ends up in "topic_duplicate".

You could then replace "dump" with "topic_duplicate" by doing:

git branch -f dump topic_duplicate
git branch -D topic_duplicate

Or with

git branch -M topic_duplicate dump

Or just by discarding the dump

git branch -D dump

Perhaps you could also just cherry-pick after clearing the current "topic_duplicate".

What I am trying to say is that if you want to update the current "duplicate" branch based off of a different ancestor you must first delete the previously "cherrypicked" commits by doing a git reset --hard <last-commit-to-retain> or git branch -f topic_duplicate <last-commit-to-retain> and then copying the other commits over (from the main topic branch) by either rebasing or cherry-picking.

Rebasing only works on a branch that already has the commits, so you need to duplicate your topic branch each time you want to do that.

Cherrypicking is much easier:

git cherry-pick master..topic

So the entire sequence will come down to:

git reset --hard <latest-commit-to-keep>
git cherry-pick master..topic

When your topic-duplicate branch has been checked out. That would remove previously-cherry-picked commits from the current duplicate, and just re-apply all of the changes happening in "topic" on top of your current "dump" (different ancestor). It seems a reasonably convenient way to base your development on the "real" upstream master while using a different "downstream" master to check whether your local changes also still apply to that. Alternatively you could just generate a diff and then apply it outside of any Git source tree. But in this way you can keep an up-to-date modified (patched) version that is based on your distribution's version while your actual development is against the real upstream master.

So just to demonstrate:

  • reset will make your branch point to a different commit (--hard also checks out the previous commit, --soft keeps added files in the index (that would be committed if you commit again) and the default (--mixed) will not check out the previous commit (wiping your local changes) but it will clear the index (nothing has been added for commit yet)
  • you can just force a branch to point to a different commit
  • you can do so while immediately checking out that commit as well
  • rebasing works on commits present in your current branch
  • cherry-picking means to copy over from a different branch

Hope this helps someone. I was meaning to rewrite this, but I cannot manage now. Regards.

How to declare a local variable in Razor?

I think you were pretty close, try this:

@{bool isUserConnected = string.IsNullOrEmpty(Model.CreatorFullName);}
@if (isUserConnected)
{ // meaning that the viewing user has not been saved so continue
    <div>
        <div> click to join us </div>
        <a id="login" href="javascript:void(0);" style="display: inline; ">join here</a>
    </div>
}

Is it possible to center text in select box?

If you didn't find any solution, you can use this trick on angularjs or using js to map selected value with a text on the div, this solution is full css compliant on angular but need a mapping between select and div:

_x000D_
_x000D_
var myApp = angular.module('myApp', []);_x000D_
_x000D_
myApp.controller('selectCtrl', ['$scope',_x000D_
  function($scope) {_x000D_
    $scope.value = '';_x000D_
_x000D_
_x000D_
  }_x000D_
]);
_x000D_
.ghostSelect {_x000D_
  opacity: 0.1;_x000D_
  /* Should be 0 to avoid the select visibility but not visibility:hidden*/_x000D_
  display: block;_x000D_
  width: 200px;_x000D_
  position: absolute;_x000D_
}_x000D_
.select {_x000D_
  border: 1px solid black;_x000D_
  height: 20px;_x000D_
  width: 200px;_x000D_
  text-align: center;_x000D_
  border-radius: 5px;_x000D_
  display: block;_x000D_
}
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="UTF-8">_x000D_
  <title>Example - example-guide-concepts-1-production</title>_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
</head>_x000D_
<body ng-app="myApp">_x000D_
  <div ng-app ng-controller="selectCtrl">_x000D_
    <div class=select>_x000D_
      <select ng-model="value" class="ghostSelect">_x000D_
        <option value="Option 1">Option 1</option>_x000D_
        <option value="Option 2">Option 2</option>_x000D_
        <option value="Option 3">Option 3</option>_x000D_
      </select>_x000D_
      <div>{{value}}_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Hope this could be useful for someone as it took me one day to find this solution on phonegap.

Simulate low network connectivity for Android

Update for Android Studio v 1.5 or greater
As @LouMorda mentioned in a comment below that the Emulator tab mentioned in original post has been removed in Android Studio v 1.5.

Now They've placed these settings in Simulator Settings in AVD Manager.
To access these settings:

  1. Select Tools -> Android -> AVD Manager
  2. Click the Edit AVD button (pencil icon)
  3. The Network Settings can be accessed after clicking the Show Advanced Settings button

Here is a screenshot of how it may appear:
Network Speed and Latency Settings in Android Studio v 1.5

Original Post
For anyone using Android Studio IDE:

  1. Go to Run -> Edit Configurations
  2. Select Android Application -> [Your App]
  3. Select Emulator tab
  4. Here you can change different values for Network Speed(internet speed) and Network Latency (delay) to simulate different speeds and latencies etc

Alternatively, you can enter various arguments in Additional command line options text field as mentioned in @inazaruk's answer.

The screenshot below describes how this Run Configuration screen looks like:

Run Configurations Screen in Android Studio beta 0.8.6

I know its a bit late to answer to this question, but i hope this helps others facing similar issues!

Edit
For anyone using eclipse, see @Abhi's answer below.

How do I set the size of an HTML text box?

Try:

input[type="text"]{
padding:10px 0;}

This is way it remains independent of what textsize has been set for the textbox. You are increasing the height using padding instead

Generating a Random Number between 1 and 10 Java

This will work for generating a number 1 - 10. Make sure you import Random at the top of your code.

import java.util.Random;

If you want to test it out try something like this.

Random rn = new Random();

for(int i =0; i < 100; i++)
{
    int answer = rn.nextInt(10) + 1;
    System.out.println(answer);
}

Also if you change the number in parenthesis it will create a random number from 0 to that number -1 (unless you add one of course like you have then it will be from 1 to the number you've entered).

How to get a Static property with Reflection

Ok so the key for me was to use the .FlattenHierarchy BindingFlag. I don't really know why I just added it on a hunch and it started working. So the final solution that allows me to get Public Instance or Static Properties is:

obj.GetType.GetProperty(propName, Reflection.BindingFlags.Public _
  Or Reflection.BindingFlags.Static Or Reflection.BindingFlags.Instance Or _
  Reflection.BindingFlags.FlattenHierarchy)

How to delete all the rows in a table using Eloquent?

I've seen both methods been used in seed files.

// Uncomment the below to wipe the table clean before populating

DB::table('table_name')->truncate();

//or

DB::table('table_name')->delete();

Even though you can not use the first one if you want to set foreign keys.

Cannot truncate a table referenced in a foreign key constraint

So it might be a good idea to use the second one.

How to merge a Series and DataFrame

You can easily set a pandas.DataFrame column to a constant. This constant can be an int such as in your example. If the column you specify isn't in the df, then pandas will create a new column with the name you specify. So after your dataframe is constructed, (from your question):

df = pd.DataFrame({'a':[np.nan, 2, 3], 'b':[4, 5, 6]}, index=[3, 5, 6])

You can just run:

df['s1'], df['s2'] = 5, 6

You could write a loop or comprehension to make it do this for all the elements in a list of tuples, or keys and values in a dictionary depending on how you have your real data stored.

What is the scope of variables in JavaScript?

Just to add to the other answers, scope is a look-up list of all the declared identifiers (variables), and enforces a strict set of rules as to how these are accessible to currently executing code. This look-up may be for the purposes of assigning to the variable, which is an LHS (lefthand-side) reference, or it may be for the purposes of retrieving its value, which is an RHS (righthand-side) reference. These look-ups are what the JavaScript engine is doing internally when it's compiling and executing the code.

So from this perspective, I think that a picture would help that I found in the Scopes and Closures ebook by Kyle Simpson:

image

Quoting from his ebook:

The building represents our program’s nested scope ruleset. The first floor of the building represents your currently executing scope, wherever you are. The top level of the building is the global scope. You resolve LHS and RHS references by looking on your current floor, and if you don’t find it, taking the elevator to the next floor, looking there, then the next, and so on. Once you get to the top floor (the global scope), you either find what you’re looking for, or you don’t. But you have to stop regardless.

One thing of note that is worth mentioning, "Scope look-up stops once it finds the first match".

This idea of "scope levels" explains why "this" can be changed with a newly created scope, if it's being looked up in a nested function. Here is a link that goes into all these details, Everything you wanted to know about javascript scope

How to read the last row with SQL Server

select whatever,columns,you,want from mytable
 where mykey=(select max(mykey) from mytable);

Generate your own Error code in swift 3

Implement LocalizedError:

struct StringError : LocalizedError
{
    var errorDescription: String? { return mMsg }
    var failureReason: String? { return mMsg }
    var recoverySuggestion: String? { return "" }
    var helpAnchor: String? { return "" }

    private var mMsg : String

    init(_ description: String)
    {
        mMsg = description
    }
}

Note that simply implementing Error, for instance, as described in one of the answers, will fail (at least in Swift 3), and calling localizedDescription will result in the string "The operation could not be completed. (.StringError error 1.)"

Flexbox not working in Internet Explorer 11

See "Can I Use" for the full list of IE11 Flexbox bugs and more

There are numerous Flexbox bugs in IE11 and other browsers - see flexbox on Can I Use -> Known Issues, where the following are listed under IE11:

  • IE 11 requires a unit to be added to the third argument, the flex-basis property
  • In IE10 and IE11, containers with display: flex and flex-direction: column will not properly calculate their flexed childrens' sizes if the container has min-height but no explicit height property
  • IE 11 does not vertically align items correctly when min-height is used

Also see Philip Walton's Flexbugs list of issues and workarounds.

Strings as Primary Keys in SQL Database

Technically yes, but if a string makes sense to be the primary key then you should probably use it. This all depends on the size of the table you're making it for and the length of the string that is going to be the primary key (longer strings == harder to compare). I wouldn't necessarily use a string for a table that has millions of rows, but the amount of performance slowdown you'll get by using a string on smaller tables will be minuscule to the headaches that you can have by having an integer that doesn't mean anything in relation to the data.

Unicode (UTF-8) reading and writing to files in Python

I found the most simple approach by changing the default encoding of the whole script to be 'UTF-8':

import sys
reload(sys)
sys.setdefaultencoding('utf8')

any open, print or other statement will just use utf8.

Works at least for Python 2.7.9.

Thx goes to https://markhneedham.com/blog/2015/05/21/python-unicodeencodeerror-ascii-codec-cant-encode-character-uxfc-in-position-11-ordinal-not-in-range128/ (look at the end).

Applying Comic Sans Ms font style

You need to use quote marks.

font-family: "Comic Sans MS", cursive, sans-serif;

Although you really really shouldn't use comic sans. The font has massive stigma attached to it's use; it's not seen as professional at all.

jQuery .each() with input elements

To extract number :

var arrNumber = new Array();
$('input[type=number]').each(function(){
    arrNumber.push($(this).val());
})

To extract text:

var arrText= new Array();
$('input[type=text]').each(function(){
    arrText.push($(this).val());
})

Edit : .map implementation

var arrText= $('input[type=text]').map(function(){
    return this.value;
}).get();

Extract source code from .jar file

I believe this can be done very easily. You can always extract the source files (Java files) of a jar file into a zip.

Steps to get sources of a jar file as a zip :

  1. Download JAD from http://techieme.in/resources-needed/ and save it at any
    location on your system.
  2. Drag and drop the jar for which you want the sources on the JAD. 3 JAD UI will open with all the package structure in a tree format.
  3. Click on File menu and select save jar sources.
  4. It will save the sources as a zip with the same name as the jar.

Hope this helps.

The link is dead due to some reason so adding the link from where you can download the JDGUI

How to convert string to date to string in Swift iOS?

See answer from Gary Makin. And you need change the format or data. Because the data that you have do not fit under the chosen format. For example this code works correct:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let dateObj = dateFormatter.dateFromString("10 10 2001")
print("Dateobj: \(dateObj)")

Can I add color to bootstrap icons only using CSS?

You can change color globally as well

i.e.

 .glyphicon {
       color: #008cba; 
   }

MySQL selecting yesterday's date

Query for the last weeks:

SELECT *
FROM dual
WHERE search_date BETWEEN SUBDATE(CURDATE(), 7) AND CURDATE()

What is the most efficient way to get first and last line of a text file?

This is my solution, compatible also with Python3. It does also manage border cases, but it misses utf-16 support:

def tail(filepath):
    """
    @author Marco Sulla ([email protected])
    @date May 31, 2016
    """

    try:
        filepath.is_file
        fp = str(filepath)
    except AttributeError:
        fp = filepath

    with open(fp, "rb") as f:
        size = os.stat(fp).st_size
        start_pos = 0 if size - 1 < 0 else size - 1

        if start_pos != 0:
            f.seek(start_pos)
            char = f.read(1)

            if char == b"\n":
                start_pos -= 1
                f.seek(start_pos)

            if start_pos == 0:
                f.seek(start_pos)
            else:
                char = ""

                for pos in range(start_pos, -1, -1):
                    f.seek(pos)

                    char = f.read(1)

                    if char == b"\n":
                        break

        return f.readline()

It's ispired by Trasp's answer and AnotherParker's comment.

Does HTML5 <video> playback support the .avi format?

Short answer: No. Use WebM or Ogg instead.

This article covers just about everything you need to know about the <video> element, including which browsers support which container formats and codecs.

.Net System.Mail.Message adding multiple "To" addresses

Add multiple System.MailAdress object to get what you want.

HashMap get/put complexity

It has already been mentioned that hashmaps are O(n/m) in average, if n is the number of items and m is the size. It has also been mentioned that in principle the whole thing could collapse into a singly linked list with O(n) query time. (This all assumes that calculating the hash is constant time).

However what isn't often mentioned is, that with probability at least 1-1/n (so for 1000 items that's a 99.9% chance) the largest bucket won't be filled more than O(logn)! Hence matching the average complexity of binary search trees. (And the constant is good, a tighter bound is (log n)*(m/n) + O(1)).

All that's required for this theoretical bound is that you use a reasonably good hash function (see Wikipedia: Universal Hashing. It can be as simple as a*x>>m). And of course that the person giving you the values to hash doesn't know how you have chosen your random constants.

TL;DR: With Very High Probability the worst case get/put complexity of a hashmap is O(logn).

Open popup and refresh parent page on close popup

You can use the below code in the parent page.

<script>
    window.onunload = refreshParent;
    function refreshParent() {
      window.opener.location.reload();
    }
</script>

Changing all files' extensions in a folder with one command on Windows

An alternative way to rename files using the renamer npm package.

below is an example of renaming files extensions

renamer -d --path-element ext --find ts --replace js *

What is the difference between __dirname and ./ in node.js?

The gist

In Node.js, __dirname is always the directory in which the currently executing script resides (see this). So if you typed __dirname into /d1/d2/myscript.js, the value would be /d1/d2.

By contrast, . gives you the directory from which you ran the node command in your terminal window (i.e. your working directory) when you use libraries like path and fs. Technically, it starts out as your working directory but can be changed using process.chdir().

The exception is when you use . with require(). The path inside require is always relative to the file containing the call to require.

For example...

Let's say your directory structure is

/dir1
  /dir2
    pathtest.js

and pathtest.js contains

var path = require("path");
console.log(". = %s", path.resolve("."));
console.log("__dirname = %s", path.resolve(__dirname));

and you do

cd /dir1/dir2
node pathtest.js

you get

. = /dir1/dir2
__dirname = /dir1/dir2

Your working directory is /dir1/dir2 so that's what . resolves to. Since pathtest.js is located in /dir1/dir2 that's what __dirname resolves to as well.

However, if you run the script from /dir1

cd /dir1
node dir2/pathtest.js

you get

. = /dir1
__dirname = /dir1/dir2

In that case, your working directory was /dir1 so that's what . resolved to, but __dirname still resolves to /dir1/dir2.

Using . inside require...

If inside dir2/pathtest.js you have a require call into include a file inside dir1 you would always do

require('../thefile')

because the path inside require is always relative to the file in which you are calling it. It has nothing to do with your working directory.

Peak memory usage of a linux/unix process

Here's a one-liner that doesn't require any external scripts or utilities and doesn't require you to start the process via another program like Valgrind or time, so you can use it for any process that's already running:

grep VmPeak /proc/$PID/status

(replace $PID with the PID of the process you're interested in)

Populate nested array in mongoose

I struggled with this for a whole bloody day. None of the solutions above worked. The only thing that worked in my case for an example like the following:

{
  outerProp1: {
    nestedProp1: [
      { prop1: x, prop2: y, prop3: ObjectId("....")},
      ...
    ],
    nestedProp2: [
      { prop1: x, prop2: y, prop3: ObjectId("....")},
      ...
    ]
  },
  ...
}

is to do the following: (Assuming populating after fetch - but also works when calling populate from the Model class (followed by exec))

await doc.populate({
  path: 'outerProp1.nestedProp1.prop3'
}).execPopulate()

// doc is now populated

In other words, the outermost path property has to contain the full path. No partially complete path coupled with populate properties seemed to work (and the model property doesn't seem to be necessary; makes sense since it is included in the schema). Took me a whole damn day to figure this out! Not sure why the other examples don't work.

(Using Mongoose 5.5.32)

Get epoch for a specific date using Javascript

Some answers does not explain the side effects of variations in the timezone for JavaScript Date object. So you should consider this answer if this is a concern for you.

Method 1: Machine's timezone dependent

By default, JavaScript returns a Date considering the machine's timezone, so getTime() result varies from computer to computer. You can check this behavior running:

new Date(1970, 0, 1, 0, 0, 0, 0).getTime()
    // Since 1970-01-01 is Epoch, you may expect ZERO
    // but in fact the result varies based on computer's timezone

This is not a problem if you really want the time since Epoch considering your timezone. So if you want to get time since Epoch for the current Date or even a specified Date based on the computer's timezone, you're free to continue using this method.

// Seconds since Epoch (Unix timestamp format)

new Date().getTime() / 1000             // local Date/Time since Epoch in seconds
new Date(2020, 11, 1).getTime() / 1000  // time since Epoch to 2020-12-01 00:00 (local timezone) in seconds

// Milliseconds since Epoch (used by some systems, eg. JavaScript itself)

new Date().getTime()                    // local Date/Time since Epoch in milliseconds
new Date(2020,  0, 2).getTime()         // time since Epoch to 2020-01-02 00:00 (local timezone) in milliseconds

// **Warning**: notice that MONTHS in JavaScript Dates starts in zero (0 = January, 11 = December)

Method 2: Machine's timezone independent

However, if you want to get ride of variations in timezone and get time since Epoch for a specified Date in UTC (that is, timezone independent), you need to use Date.UTC method or shift the date from your timezone to UTC:

Date.UTC(1970,  0, 1)
    // should be ZERO in any computer, since it is ZERO the difference from Epoch

    // Alternatively (if, for some reason, you do not want Date.UTC)
    const timezone_diff = new Date(1970, 0, 1).getTime()  // difference in milliseconds between your timezone and UTC
    (new Date(1970,  0, 1).getTime() - timezone_diff)
    // should be ZERO in any computer, since it is ZERO the difference from Epoch

So, using this method (or, alternatively, subtracting the difference), the result should be:

// Seconds since Epoch (Unix timestamp format)

Date.UTC(2020,  0, 1) / 1000  // time since Epoch to 2020-01-01 00:00 UTC in seconds

    // Alternatively (if, for some reason, you do not want Date.UTC)
    const timezone_diff = new Date(1970, 0, 1).getTime()
    (new Date(2020,  0, 1).getTime() - timezone_diff) / 1000  // time since Epoch to 2020-01-01 00:00 UTC in seconds
    (new Date(2020, 11, 1).getTime() - timezone_diff) / 1000  // time since Epoch to 2020-12-01 00:00 UTC in seconds

// Milliseconds since Epoch (used by some systems, eg. JavaScript itself)

Date.UTC(2020,  0, 2)   // time since Epoch to 2020-01-02 00:00 UTC in milliseconds

    // Alternatively (if, for some reason, you do not want Date.UTC)
    const timezone_diff = new Date(1970, 0, 1).getTime()
    (new Date(2020,  0, 2).getTime() - timezone_diff)         // time since Epoch to 2020-01-02 00:00 UTC in milliseconds

// **Warning**: notice that MONTHS in JavaScript Dates starts in zero (0 = January, 11 = December)

IMO, unless you know what you're doing (see note above), you should prefer Method 2, since it is machine independent.


End note

Although the recomendations in this answer, and since Date.UTC does not work without a specified date/time, you may be inclined in using the alternative approach and doing something like this:

const timezone_diff = new Date(1970, 0, 1).getTime()
(new Date().getTime() - timezone_diff)  // <-- !!! new Date() without arguments
    // means "local Date/Time subtracted by timezone since Epoch" (?)

This does not make any sense and it is probably WRONG (you are modifying the date). Be aware of not doing this. If you want to get time since Epoch from the current date AND TIME, you are most probably OK using Method 1.

How to get xdebug var_dump to show full object/array

I know this is late but it might be of some use:

echo "<pre>";
print_r($array);
echo "</pre>";

VBA Copy Sheet to End of Workbook (with Hidden Worksheets)

Make the source sheet visible before copying. Then copy the sheet so that the copy also stays visible. The copy will then be the active sheet. If you want, hide the source sheet again.

is there any alternative for ng-disabled in angular2?

Here is a solution am using with anular 6.

[readonly]="DateRelatedObject.bool_DatesEdit ? true : false"

plus above given answer

[attr.disabled]="valid == true ? true : null"

did't work for me plus be aware of using null cause it's expecting bool.

Add item to Listview control

The ListView control uses the Items collection to add items to listview in the control and is able to customize items.

How to add Android Support Repository to Android Studio?

I used to get similar issues. Even after installing the support repository, the build used to fail.

Basically the issues is due to the way the version number of the jar files are specified in the gradle files are specified properly.

For example, in my case i had set it as "compile 'com.android.support:support-v4:21.0.3+'"

On removing "+" the build was sucessful!!

DropDownList's SelectedIndexChanged event not firing

try setting AutoPostBack="True" on the DropDownList.

Can I get Unix's pthread.h to compile in Windows?

Just pick up the TDM-GCC 64x package. (It constains both the 32 and 64 bit versions of the MinGW toolchain and comes within a neat installer.) More importantly, it contains something called the "winpthread" library.

It comprises of the pthread.h header, libwinpthread.a, libwinpthread.dll.a static libraries for both 32-bit and 64-bit and the required .dlls libwinpthread-1.dll and libwinpthread_64-1.dll(this, as of 01-06-2016).

You'll need to link to the libwinpthread.a library during build. Other than that, your code can be the same as for native Pthread code on Linux. I've so far successfully used it to compile a few basic Pthread programs in 64-bit on windows.

Alternatively, you can use the following library which wraps the windows threading API into the pthreads API: pthreads-win32.

The above two seem to be the most well known ways for this.

Hope this helps.

How to kill a thread instantly in C#?

thread will be killed when it finish it's work, so if you are using loops or something else you should pass variable to the thread to stop the loop after that the thread will be finished.

Code not running in IE 11, works fine in Chrome

Follow this method if problem comes when working with angular2+ projects

I was looking for a solution when i got this error, and it got me here. But this question seems to be specific but the error is not, its a generic error. This is a common error for angular developers dealing with Internet Explorer.

I had the same issue while working with angular 2+, and it got resolved just by few simple steps.

In Angular latest versions, there are come commented codes in the polyfills.ts shows all the polyfills required for the smooth running in Internet Explorer versions IE09,IE10 and IE11

/** IE9, IE10 and IE11 requires all of the following polyfills. **/
//import 'core-js/es6/symbol';
//import 'core-js/es6/object';
//import 'core-js/es6/function';
//import 'core-js/es6/parse-int';
//import 'core-js/es6/parse-float';
//import 'core-js/es6/number';
//import 'core-js/es6/math';
//import 'core-js/es6/string';
//import 'core-js/es6/date';
//import 'core-js/es6/array';
//import 'core-js/es6/regexp';
//import 'core-js/es6/map';
//import 'core-js/es6/weak-map';
//import 'core-js/es6/set';

Uncomment the codes and it would work perfectly in IE browsers

/** IE9, IE10 and IE11 requires all of the following polyfills. **/
import 'core-js/es6/symbol';
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
import 'core-js/es6/set';

But you might see a performance drop in IE browsers compared to others :(

Laravel Migration table already exists, but I want to add new not the older

  1. Drop all tables manually at the phpmyadmin.

  2. Go to each migration file at database/migrations. Find and remove these 2 codes :

    a) ->index() (found at 2014_10_12_100000_create_password_resets_table.php at line 17)

    b) ->unique() (found at 2014_10_12_000000_create_users_table.php at line 19)

  3. Run php artisan migrate

  4. Done.

I think this happens because the latest laravel class (at 12th February 2018) has removed the function of ->index() and ->unique()

How to unzip files programmatically in Android?

The Kotlin way

//FileExt.kt

data class ZipIO (val entry: ZipEntry, val output: File)

fun File.unzip(unzipLocationRoot: File? = null) {

    val rootFolder = unzipLocationRoot ?: File(parentFile.absolutePath + File.separator + nameWithoutExtension)
    if (!rootFolder.exists()) {
       rootFolder.mkdirs()
    }

    ZipFile(this).use { zip ->
        zip
        .entries()
        .asSequence()
        .map {
            val outputFile = File(rootFolder.absolutePath + File.separator + it.name)
            ZipIO(it, outputFile)
        }
        .map {
            it.output.parentFile?.run{
                if (!exists()) mkdirs()
            }
            it
        }
        .filter { !it.entry.isDirectory }
        .forEach { (entry, output) ->
            zip.getInputStream(entry).use { input ->
                output.outputStream().use { output ->
                    input.copyTo(output)
                }
            }
        }
    }

}

Usage

val zipFile = File("path_to_your_zip_file")
file.unzip()

Math.random() versus Random.nextInt(int)

According to this example Random.nextInt(n) has less predictable output then Math.random() * n. According to [sorted array faster than an unsorted array][1] I think we can say Random.nextInt(n) is hard to predict.

usingRandomClass : time:328 milesecond.

usingMathsRandom : time:187 milesecond.

package javaFuction;
import java.util.Random;
public class RandomFuction 
{
    static int array[] = new int[9999];
    static long sum = 0;
    public static void usingMathsRandom() {
        for (int i = 0; i < 9999; i++) {
         array[i] = (int) (Math.random() * 256);
       }

        for (int i = 0; i < 9999; i++) {
            for (int j = 0; j < 9999; j++) {
                if (array[j] >= 128) {
                    sum += array[j];
                }
            }
        }
    }

    public static void usingRandomClass() {
        Random random = new Random();
        for (int i = 0; i < 9999; i++) {
            array[i] = random.nextInt(256);
        }

        for (int i = 0; i < 9999; i++) {
            for (int j = 0; j < 9999; j++) {
                if (array[j] >= 128) {
                    sum += array[j];
                }
            }

        }

    }

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        usingRandomClass();
        long end = System.currentTimeMillis();
        System.out.println("usingRandomClass " + (end - start));
        start = System.currentTimeMillis();
        usingMathsRandom();
        end = System.currentTimeMillis();
        System.out.println("usingMathsRandom " + (end - start));

    }

}

How to convert POJO to JSON and vice versa?

Take a look at https://www.json.org

[edited] Imagine that you have a simple Java class like this:

public class Person {

    private String name;
    private Integer age;

    public String getName() { return this.name; }
    public void setName( String name ) { this.name = name; }

    public Integer getAge() { return this.age; }
    public void setAge( Integer age ) { this.age = age; }

}

So, to transform it to a JSon object, it's very simple. Like this:

import org.json.JSONObject;

public class JsonTest {

    public static void main( String[] args ) {
        Person person = new Person();
        person.setName( "Person Name" );
        person.setAge( 333 );

        JSONObject jsonObj = new JSONObject( person );
        System.out.println( jsonObj );
    }

}

Hope it helps.

[edited] Here there is other example, in this case using Jackson: https://brunozambiazi.wordpress.com/2015/08/15/working-with-json-in-java/

Maven:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.6.1</version>
</dependency>

And a link (below) to find the latest/greatest version:

https://search.maven.org/classic/#search%7Cga%7C1%7Cg%3A%22com.fasterxml.jackson.core%22%20AND%20a%3A%22jackson-databind%22

Elasticsearch query to return all records

http://localhost:9200/foo/_search/?size=1000&pretty=1

you will need to specify size query parameter as the default is 10

Get device token for push notification

Using description as many of these answers suggest is the wrong approach - even if you get it to work, it will break in iOS 13+.

Instead you should ensure you use the actual binary data, not simply a description of it. Andrey Gagan addressed the Objective C solution quite well, but fortunately it's much simpler in swift:

Swift 4.2 works in iOS 13+

// credit to NSHipster (see link above)
// format specifier produces a zero-padded, 2-digit hexadecimal representation
let deviceTokenString = deviceToken.map { String(format: "%02x", $0) }.joined()

How do I disable text selection with CSS or JavaScript?

Try this CSS code for cross-browser compatibility.

-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;

Secure hash and salt for PHP passwords

I would not store the password hashed in two different ways, because then the system is at least as weak as the weakest of the hash algorithms in use.

How to return a part of an array in Ruby?

I like ranges for this:

def first_half(list)
  list[0...(list.length / 2)]
end

def last_half(list)
  list[(list.length / 2)..list.length]
end

However, be very careful about whether the endpoint is included in your range. This becomes critical on an odd-length list where you need to choose where you're going to break the middle. Otherwise you'll end up double-counting the middle element.

The above example will consistently put the middle element in the last half.

How to clear File Input

This works to

 $("#yourINPUTfile").val("");

Printing chars and their ASCII-code in C

Chars within single quote ('XXXXXX'), when printed as decimal should output its ASCII value.

int main(){

    printf("D\n");
    printf("The ASCII of D is %d\n",'D');

    return 0;

}

Output:

% ./a.out
>> D
>> The ASCII of D is 68

How to check that a string is parseable to a double?

The common approach would be to check it with a regular expression like it's also suggested inside the Double.valueOf(String) documentation.

The regexp provided there (or included below) should cover all valid floating point cases, so you don't need to fiddle with it, since you will eventually miss out on some of the finer points.

If you don't want to do that, try catch is still an option.

The regexp suggested by the JavaDoc is included below:

final String Digits     = "(\\p{Digit}+)";
final String HexDigits  = "(\\p{XDigit}+)";
// an exponent is 'e' or 'E' followed by an optionally 
// signed decimal integer.
final String Exp        = "[eE][+-]?"+Digits;
final String fpRegex    =
    ("[\\x00-\\x20]*"+ // Optional leading "whitespace"
    "[+-]?(" +         // Optional sign character
    "NaN|" +           // "NaN" string
    "Infinity|" +      // "Infinity" string

    // A decimal floating-point string representing a finite positive
    // number without a leading sign has at most five basic pieces:
    // Digits . Digits ExponentPart FloatTypeSuffix
    // 
    // Since this method allows integer-only strings as input
    // in addition to strings of floating-point literals, the
    // two sub-patterns below are simplifications of the grammar
    // productions from the Java Language Specification, 2nd 
    // edition, section 3.10.2.

    // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt
    "((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+

    // . Digits ExponentPart_opt FloatTypeSuffix_opt
    "(\\.("+Digits+")("+Exp+")?)|"+

    // Hexadecimal strings
    "((" +
    // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt
    "(0[xX]" + HexDigits + "(\\.)?)|" +

    // 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt
    "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" +

    ")[pP][+-]?" + Digits + "))" +
    "[fFdD]?))" +
    "[\\x00-\\x20]*");// Optional trailing "whitespace"

if (Pattern.matches(fpRegex, myString)){
    Double.valueOf(myString); // Will not throw NumberFormatException
} else {
    // Perform suitable alternative action
}

How to do SVN Update on my project using the command line

svn update /path/to/working/copy

If subversion is not in your PATH, then of course

/path/to/subversion/svn update /path/to/working/copy

or if you are in the current root directory of your svn repo (it contains a .svn subfolder), it's as simple as

svn update

Using port number in Windows host file

Using netsh with connectaddress=127.0.0.1 did not work for me.

Despite looking everywhere on the internet I could not find the solution which solved this for me, which was to use connectaddress=127.x.x.x (i.e. any 127. ipv4 address, just not 127.0.0.1) as this appears to link back to localhost just the same but without the restriction, so that the loopback works in netsh.

What is the keyguard in Android?

Yes, I also found it here: http://developer.android.com/tools/testing/activity_testing.html It's seems a key-input protection mechanism which includes the screen-lock, but not only includes it. According to this webpage, it also defines some key-input restriction for auto-test framework in Android.

How to use multiprocessing queue in Python?

Here's a dead simple usage of multiprocessing.Queue and multiprocessing.Process that allows callers to send an "event" plus arguments to a separate process that dispatches the event to a "do_" method on the process. (Python 3.4+)

import multiprocessing as mp
import collections

Msg = collections.namedtuple('Msg', ['event', 'args'])

class BaseProcess(mp.Process):
    """A process backed by an internal queue for simple one-way message passing.
    """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.queue = mp.Queue()

    def send(self, event, *args):
        """Puts the event and args as a `Msg` on the queue
        """
       msg = Msg(event, args)
       self.queue.put(msg)

    def dispatch(self, msg):
        event, args = msg

        handler = getattr(self, "do_%s" % event, None)
        if not handler:
            raise NotImplementedError("Process has no handler for [%s]" % event)

        handler(*args)

    def run(self):
        while True:
            msg = self.queue.get()
            self.dispatch(msg)

Usage:

class MyProcess(BaseProcess):
    def do_helloworld(self, arg1, arg2):
        print(arg1, arg2)

if __name__ == "__main__":
    process = MyProcess()
    process.start()
    process.send('helloworld', 'hello', 'world')

The send happens in the parent process, the do_* happens in the child process.

I left out any exception handling that would obviously interrupt the run loop and exit the child process. You can also customize it by overriding run to control blocking or whatever else.

This is really only useful in situations where you have a single worker process, but I think it's a relevant answer to this question to demonstrate a common scenario with a little more object-orientation.

Two constructors

The first line of a constructor is always an invocation to another constructor. You can choose between calling a constructor from the same class with "this(...)" or a constructor from the parent clas with "super(...)". If you don't include either, the compiler includes this line for you: super();

Getting the Username from the HKEY_USERS values

By searching for my userid in the registry, I found

HKEY_CURRENT_USER\Volatile Environment\Username

How to add color to Github's README.md file

I'm inclined to agree with Qwertman that it's not currently possible to specify color for text in GitHub markdown, at least not through HTML.

GitHub does allow some HTML elements and attributes, but only certain ones (see their documentation about their HTML sanitization). They do allow p and div tags, as well as color attribute. However, when I tried using them in a markdown document on GitHub, it didn't work. I tried the following (among other variations), and they didn't work:

  • <p style='color:red'>This is some red text.</p>
  • <font color="red">This is some text!</font>
  • These are <b style='color:red'>red words</b>.

As Qwertman suggested, if you really must use color you could do it in a README.html and refer them to it.

Create array of regex matches

        Set<String> keyList = new HashSet();
        Pattern regex = Pattern.compile("#\\{(.*?)\\}");
        Matcher matcher = regex.matcher("Content goes here");
        while(matcher.find()) {
            keyList.add(matcher.group(1)); 
        }
        return keyList;

What is an AssertionError? In which case should I throw it from my own code?

AssertionError is an Unchecked Exception which rises explicitly by programmer or by API Developer to indicate that assert statement fails.

assert(x>10);

Output:

AssertionError

If x is not greater than 10 then you will get runtime exception saying AssertionError.

Library not loaded: libmysqlclient.16.dylib error when trying to run 'rails server' on OS X 10.6 with mysql2 gem

For me this was just because I had upgraded mysql but hadn't updated the mysql2 gem - a reinstall of the gem will fix it...

gem pristine mysql2

jQuery to loop through elements with the same class

With a simple for loop:

var testimonials= $('.testimonial');
for (var i = 0; i < testimonials.length; i++) {
  // Using $() to re-wrap the element.
  $(testimonials[i]).text('a');
}

Count number of occurences for each unique value

You can try also a tidyverse

library(tidyverse) 
dummyData %>% 
    as.tibble() %>% 
    count(value)
# A tibble: 2 x 2
  value     n
  <dbl> <int>
1     1    25
2     2    75

Apk location in New Android Studio

There is really no reason to dig through paths; the IDE hands it to you (at least with version 1.5.1).

In the Build menu, select Build APK:

Android Studio Build Menu

A dialog will appear:

Android Studio APK Generated Dialog

If you are using a newer version of Android Studio, it might look like this:

prompt to locate your APK file

Clicking the Show in Explorer or locate link, you will be presented with a file explorer positioned somewhere near wherever Android Studio put the APK file:

File explorer after clicking the link in the APK Generated dialog

But in AS 3, when you click locate, it puts you at the app level. You need to go into the release folder to get your APK file.

folder structure in AS 3

folder contents after a build

Can't use modulus on doubles?

You can implement your own modulus function to do that for you:

double dmod(double x, double y) {
    return x - (int)(x/y) * y;
}

Then you can simply use dmod(6.3, 2) to get the remainder, 0.3.

How to dynamically insert a <script> tag via jQuery after page load?

There is one workaround that sounds more like a hack and I agree it's not the most elegant way of doing it, but works 100%:

Say your AJAX response is something like

<b>some html</b>
<script>alert("and some javscript")

Note that I've skipped the closing tag on purpose. Then in the script that loads the above, do the following:

$.ajax({
    url: "path/to/return/the-above-js+html.php",
    success: function(newhtml){
        newhtml += "<";
        newhtml += "/script>";
        $("head").append(newhtml);
    }
});

Just don't ask me why :-) This is one of those things I've come to as a result of desperate almost random trials and fails.

I have no complete suggestions on how it works, but interestingly enough, it will NOT work if you append the closing tag in one line.

In times like these, I feel like I've successfully divided by zero.

How to enable ASP classic in IIS7.5

So it turns out that if I add the Handler Mappings on the Website and Application level, everything works beautifully. I was only adding them on the server level, thus IIS did not know to map the asp pages to the IsapiModule.

So to resolve this issue, go to the website you want to add your application to, then double click on Handler Mappings. Click "Add Script Map" and enter in the following information:

RequestPath: *.asp
Executable: C:\Windows\System32\inetsrv\asp.dll
Name: Classic ASP (this can be anything you want it to be

Apache POI error loading XSSFWorkbook class

commons-collections4-x.x.jar definitely solve this problem but Apache has removed the Interface ListValuedMap from commons-Collections4-4.0.jar so use updated version 4.1 it has the required classes and Interfaces.

Refer here if you want to read Excel (2003 or 2007+) using java code.

http://www.codejava.net/coding/how-to-read-excel-files-in-java-using-apache-poi

Detect click outside React component

This already has many answers but they don't address e.stopPropagation() and preventing clicking on react links outside of the element you wish to close.

Due to the fact that React has it's own artificial event handler you aren't able to use document as the base for event listeners. You need to e.stopPropagation() before this as React uses document itself. If you use for example document.querySelector('body') instead. You are able to prevent the click from the React link. Following is an example of how I implement click outside and close.
This uses ES6 and React 16.3.

import React, { Component } from 'react';

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      isOpen: false,
    };

    this.insideContainer = React.createRef();
  }

  componentWillMount() {
    document.querySelector('body').addEventListener("click", this.handleClick, false);
  }

  componentWillUnmount() {
    document.querySelector('body').removeEventListener("click", this.handleClick, false);
  }

  handleClick(e) {
    /* Check that we've clicked outside of the container and that it is open */
    if (!this.insideContainer.current.contains(e.target) && this.state.isOpen === true) {
      e.preventDefault();
      e.stopPropagation();
      this.setState({
        isOpen: false,
      })
    }
  };

  togggleOpenHandler(e) {
    e.preventDefault();

    this.setState({
      isOpen: !this.state.isOpen,
    })
  }

  render(){
    return(
      <div>
        <span ref={this.insideContainer}>
          <a href="#open-container" onClick={(e) => this.togggleOpenHandler(e)}>Open me</a>
        </span>
        <a href="/" onClick({/* clickHandler */})>
          Will not trigger a click when inside is open.
        </a>
      </div>
    );
  }
}

export default App;

how to set radio option checked onload with jQuery

Native JS solution:

 document.querySelector('input[name=gender][value=Female]').checked = true;

http://jsfiddle.net/jzQvH/75/

HTML:

<input type='radio' name='gender' value='Male'> Male
<input type='radio' name='gender' value='Female'>Female

php return 500 error but no error log

Be sure your file permissions are correct. If apache doesn't have permission to read the file then it can't write to the log.

IndentationError: unexpected unindent WHY?

This error could actually be in the code preceding where the error is reported. See the For example, if you have a syntax error as below, you'll get the indentation error. The syntax error is actually next to the "except" because it should contain a ":" right after it.

try:
    #do something
except
    print 'error/exception'


def printError(e):
    print e

If you change "except" above to "except:", the error will go away.

Good luck.