Programs & Examples On #Jconsole

A Java debugging aid that redirects any System.{out,err} to a console window.

Remote JMX connection

I have the same issue and I change any hostname that matches the local host name to 0.0.0.0, it seems to work after I do that.

How to activate JMX on my JVM for access with jconsole?

Note, Java 6 in the latest incarnation allows for jconsole to attach itself to a running process even after it has been started without JMX incantations.

If that is available to you, also consider jvisualvm as it provides a wealth of information on running processes, including a profiler.

Has anyone ever got a remote JMX JConsole to work?

Getting JMX through the firewall isn't that hard at all. There is one small catch. You have to forward both your JMX configured port ie. 9010 and one of dynamic ports its listens to on my machine it was > 30000

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

I found the same issue with Node 12.19.0 and yarn 1.22.5 on Windows 10. I fixed the problem by installing latest stable python 64-bit with adding the path to Environment Variables during python installation. After python installation, I restarted my machine for env vars.

Importing large sql file to MySql via command line

Guys regarding time taken for importing huge files most importantly it takes more time is because default setting of mysql is "autocommit = true", you must set that off before importing your file and then check how import works like a gem...

First open MySQL:

mysql -u root -p

Then, You just need to do following :

mysql>use your_db

mysql>SET autocommit=0 ; source the_sql_file.sql ; COMMIT ;

Copy mysql database from remote server to local computer

Please check this gist.

https://gist.github.com/ecdundar/789660d830d6d40b6c90

#!/bin/bash

# copymysql.sh

# GENERATED WITH USING ARTUR BODERA S SCRIPT
# Source script at: https://gist.github.com/2215200

MYSQLDUMP="/usr/bin/mysqldump"
MYSQL="/usr/bin/mysql"

REMOTESERVERIP=""
REMOTESERVERUSER=""
REMOTESERVERPASSWORD=""
REMOTECONNECTIONSTR="-h ${REMOTESERVERIP} -u ${REMOTESERVERUSER} --password=${REMOTESERVERPASSWORD} "

LOCALSERVERIP=""
LOCALSERVERUSER=""
LOCALSERVERPASSWORD=""
LOCALCONNECTION="-h ${LOCALSERVERIP} -u ${LOCALSERVERUSER} --password=${LOCALSERVERPASSWORD} "

IGNOREVIEWS=""
MYVIEWS=""
IGNOREDATABASES="select schema_name from information_schema.SCHEMATA where schema_name != 'information_schema' and schema_name != 'mysql' and schema_name != 'performance_schema'  ;"

# GET A LIST OF DATABASES
databases=`$MYSQL $REMOTECONNECTIONSTR -e "${IGNOREDATABASES}" | tr -d "| " | grep -v schema_name`

# COPY ALL TABLES
for db in $databases; do
    # GET LIST OF ITEMS
    views=`$MYSQL $REMOTECONNECTIONSTR --batch -N -e "select table_name from information_schema.tables where table_type='VIEW' and table_schema='$db';"
    IGNOREVIEWS=""
    for view in $views; do
        IGNOREVIEWS=${IGNOREVIEWS}" --ignore-table=$db.$view " 
    done
    echo "TABLES "$db
    $MYSQL $LOCALCONNECTION --batch -N -e "create database $db; "
    $MYSQLDUMP $REMOTECONNECTIONSTR $IGNOREVIEWS --compress --quick --extended-insert  --skip-add-locks --skip-comments --skip-disable-keys --default-character-set=latin1 --skip-triggers --single-transaction  $db | mysql $LOCALCONNECTION  $db 
done

# COPY ALL PROCEDURES
for db in $databases; do
    echo "PROCEDURES "$db
    #PROCEDURES
    $MYSQLDUMP $REMOTECONNECTIONSTR --compress --quick --routines --no-create-info --no-data --no-create-db --skip-opt --skip-triggers $db | \
    sed -r 's/DEFINER=`[^`]+`@`[^`]+`/DEFINER=CURRENT_USER/g' | mysql $LOCALCONNECTION  $db 
done

# COPY ALL TRIGGERS
for db in $databases; do
    echo "TRIGGERS "$db
    #TRIGGERS
    $MYSQLDUMP $REMOTECONNECTIONSTR  --compress --quick --no-create-info --no-data --no-create-db --skip-opt --triggers $db | \
    sed -r 's/DEFINER=`[^`]+`@`[^`]+`/DEFINER=CURRENT_USER/g' | mysql $LOCALCONNECTION  $db 
done

# COPY ALL VIEWS
for db in $databases; do
    # GET LIST OF ITEMS
    views=`$MYSQL $REMOTECONNECTIONSTR --batch -N -e "select table_name from information_schema.tables where table_type='VIEW' and table_schema='$db';"`
    MYVIEWS=""
    for view in $views; do
        MYVIEWS=${MYVIEWS}" "$view" " 
    done
    echo "VIEWS "$db    
    if [ -n "$MYVIEWS" ]; then
      #VIEWS
      $MYSQLDUMP $REMOTECONNECTIONSTR --compress --quick -Q -f --no-data --skip-comments --skip-triggers --skip-opt --no-create-db --complete-insert --add-drop-table $db $MYVIEWS | \
      sed -r 's/DEFINER=`[^`]+`@`[^`]+`/DEFINER=CURRENT_USER/g'  | mysql $LOCALCONNECTION  $db  
    fi    
done

echo   "OK!"

How to convert Java String to JSON Object

@Nishit, JSONObject does not natively understand how to parse through a StringBuilder; instead you appear to be using the JSONObject(java.lang.Object bean) constructor to create the JSONObject, however passing it a StringBuilder.

See this link for more information on that particular constructor.

http://www.json.org/javadoc/org/json/JSONObject.html#JSONObject%28java.lang.Object%29

When a constructor calls for a java.lang.Object class, more than likely it's really telling you that you're expected to create your own class (since all Classes ultimately extend java.lang.Object) and that it will interface with that class in a specific way, albeit normally it will call for an interface instead (hence the name) OR it can accept any class and interface with it "abstractly" such as calling .toString() on it. Bottom line, you typically can't just pass it any class and expect it to work.

At any rate, this particular constructor is explained as such:

Construct a JSONObject from an Object using bean getters. It reflects on all of the public methods of the object. For each of the methods with no parameters and a name starting with "get" or "is" followed by an uppercase letter, the method is invoked, and a key and the value returned from the getter method are put into the new JSONObject. The key is formed by removing the "get" or "is" prefix. If the second remaining character is not upper case, then the first character is converted to lower case. For example, if an object has a method named "getName", and if the result of calling object.getName() is "Larry Fine", then the JSONObject will contain "name": "Larry Fine".

So, what this means is that it's expecting you to create your own class that implements get or is methods (i.e.

public String getName() {...}

or

public boolean isValid() {...}

So, to solve your problem, if you really want that higher level of control and want to do some manipulation (e.g. modify some values, etc.) but still use StringBuilder to dynamically generate the code, you can create a class that extends the StringBuilder class so that you can use the append feature, but implement get/is methods to allow JSONObject to pull the data out of it, however this is likely not what you want/need and depending on the JSON, you might spend a lot of time and energy creating the private fields and get/is methods (or use an IDE to do it for you) or it might be all for naught if you don't necessarily know the breakdown of the JSON string.

So, you can very simply call toString() on the StringBuilder which will provide a String representation of the StringBuilder instance and passing that to the JSONObject constructor, such as below:

...
StringBuilder jsonString = new StringBuilder();
while((readAPIResponse = br.readLine()) != null){
    jsonString.append(readAPIResponse);
}
JSONObject jsonObj = new JSONObject(jsonString.toString());
...

Angular error: "Can't bind to 'ngModel' since it isn't a known property of 'input'"

Your ngModel is not working because it's not a part of your NgModule yet.

You have to tell the NgModule that you have authority to use ngModel throughout your app, You can do it by adding FormsModule into your app.module.ts -> imports-> [].

import { FormsModule } from '@angular/forms';

@NgModule({

   imports: [ FormsModule ],       // HERE

   declarations: [ AppComponent ],
   bootstrap: [ AppComponent ]
 })

enum Values to NSString (iOS)

  1. a macro:

    #define stringWithLiteral(literal) @#literal
    
  2. an enum:

    typedef NS_ENUM(NSInteger, EnumType) {
        EnumType0,
        EnumType1,
        EnumType2
    };
    
  3. an array:

    static NSString * const EnumTypeNames[] = {
        stringWithLiteral(EnumType0),
        stringWithLiteral(EnumType1),
        stringWithLiteral(EnumType2)
    };
    
  4. using:

    EnumType enumType = ...;
    NSString *enumName = EnumTypeNames[enumType];
    

==== EDIT ====

Copy the following code to your project and run.

#define stringWithLiteral(literal) @#literal

typedef NS_ENUM(NSInteger, EnumType) {
    EnumType0,
    EnumType1,
    EnumType2
};

static NSString * const EnumTypeNames[] = {
    stringWithLiteral(EnumType0),
    stringWithLiteral(EnumType1),
    stringWithLiteral(EnumType2)
};

- (void)test {
    EnumType enumType = EnumType1;
    NSString *enumName = EnumTypeNames[enumType];
    NSLog(@"enumName: %@", enumName);
}

How can I print variable and string on same line in Python?

I copied and pasted your script into a .py file. I ran it as-is with Python 2.7.10 and received the same syntax error. I also tried the script in Python 3.5 and received the following output:

File "print_strings_on_same_line.py", line 16
print fiveYears
              ^
SyntaxError: Missing parentheses in call to 'print'

Then, I modified the last line where it prints the number of births as follows:

currentPop = 312032486
oneYear = 365
hours = 24
minutes = 60
seconds = 60

# seconds in a single day
secondsInDay = hours * minutes * seconds

# seconds in a year
secondsInYear = secondsInDay * oneYear

fiveYears = secondsInYear * 5

#Seconds in 5 years
print fiveYears

# fiveYears in seconds, divided by 7 seconds
births = fiveYears // 7

print "If there was a birth every 7 seconds, there would be: " + str(births) + " births"

The output was (Python 2.7.10):

157680000
If there was a birth every 7 seconds, there would be: 22525714 births

I hope this helps.

Babel command not found

I ran into the very same problem, tried out really everything that I could think of. Not being a fan of installing anything globally, but eventually had to run npm install -g babel-cli, which solved my problem. Maybe not the answer, but definitely a possible solution...

Make body have 100% of the browser height

I style the div container - usually the sole child of the body with the following css

.body-container {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
}

How can I list the contents of a directory in Python?

os.walk can be used if you need recursion:

import os
start_path = '.' # current directory
for path,dirs,files in os.walk(start_path):
    for filename in files:
        print os.path.join(path,filename)

XML Schema Validation : Cannot find the declaration of element

cvc-elt.1: Cannot find the declaration of element 'Root'. [7]

Your schemaLocation attribute on the root element should be xsi:schemaLocation, and you need to fix it to use the right namespace.

You should probably change the targetNamespace of the schema and the xmlns of the document to http://myNameSpace.com (since namespaces are supposed to be valid URIs, which Test.Namespace isn't, though urn:Test.Namespace would be ok). Once you do that it should find the schema. The point is that all three of the schema's target namespace, the document's namespace, and the namespace for which you're giving the schema location must be the same.

(though it still won't validate as your <element2> contains an <element3> in the document where the schema expects item)

Could not resolve this reference. Could not locate the assembly

This confused me for a while until I worked out that the dependencies of the various projects in the solution had been messed up. Get that straight and naturally your assembly appears in the right place.

Insert at first position of a list in Python

From the documentation:

list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a),x) is equivalent to a.append(x)

http://docs.python.org/2/tutorial/datastructures.html#more-on-lists

Extract elements of list at odd positions

I like List comprehensions because of their Math (Set) syntax. So how about this:

L = [1, 2, 3, 4, 5, 6, 7]
odd_numbers = [y for x,y in enumerate(L) if x%2 != 0]
even_numbers = [y for x,y in enumerate(L) if x%2 == 0]

Basically, if you enumerate over a list, you'll get the index x and the value y. What I'm doing here is putting the value y into the output list (even or odd) and using the index x to find out if that point is odd (x%2 != 0).

How to extract extension from filename string in Javascript?

Use the lastIndexOf method to find the last period in the string, and get the part of the string after that:

var ext = fileName.substr(fileName.lastIndexOf('.') + 1);

How to make an app's background image repeat

Expanding on plowman's answer, here is the non-deprecated version of changing the background image with java.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bitmap bmp = BitmapFactory.decodeResource(getResources(),
            R.drawable.texture);
    BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(),bmp);
    bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT,
            Shader.TileMode.REPEAT);
    setBackground(bitmapDrawable);
}

Why GDB jumps unpredictably between lines and prints variables as "<value optimized out>"?

When debugging optimized programs (which may be necessary if the bug doesn't show up in debug builds), you often have to understand assembly compiler generated.

In your particular case, return value of cpnd_find_exact_ckptinfo will be stored in the register which is used on your platform for return values. On ix86, that would be %eax. On x86_64: %rax, etc. You may need to google for '[your processor] procedure calling convention' if it's none of the above.

You can examine that register in GDB and you can set it. E.g. on ix86:

(gdb) p $eax
(gdb) set $eax = 0 

Responsive Google Map?

Add this to your initialize function:

<script type="text/javascript">

function initialize() {

  var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

  // Resize stuff...
  google.maps.event.addDomListener(window, "resize", function() {
    var center = map.getCenter();
    google.maps.event.trigger(map, "resize");
    map.setCenter(center); 
  });

}

</script>

How can you make a custom keyboard in Android?

I came across this post recently when I was trying to decide what method to use to create my own custom keyboard. I found the Android system API to be very limited, so I decided to make my own in-app keyboard. Using Suragch's answer as the basis for my research, I went on to design my own keyboard component. It's posted on GitHub with an MIT license. Hopefully this will save somebody else a lot of time and headache.

The architecture is pretty flexible. There is one main view (CustomKeyboardView) that you can inject with whatever keyboard layout and controller you want.

You just have to declare the CustomKeyboardView in you activity xml (you can do it programmatically as well):

    <com.donbrody.customkeyboard.components.keyboard.CustomKeyboardView
    android:id="@+id/customKeyboardView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true" />

Then register your EditText's with it and tell it what type of keyboard they should use:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val numberField: EditText = findViewById(R.id.testNumberField)
    val numberDecimalField: EditText = findViewById(R.id.testNumberDecimalField)
    val qwertyField: EditText = findViewById(R.id.testQwertyField)

    keyboard = findViewById(R.id.customKeyboardView)
    keyboard.registerEditText(CustomKeyboardView.KeyboardType.NUMBER, numberField)
    keyboard.registerEditText(CustomKeyboardView.KeyboardType.NUMBER_DECIMAL, numberDecimalField)
    keyboard.registerEditText(CustomKeyboardView.KeyboardType.QWERTY, qwertyField)
}

The CustomKeyboardView handles the rest!

I've got the ball rolling with a Number, NumberDecimal, and QWERTY keyboard. Feel free to download it and create your own layouts and controllers. It looks like this:

android custom keyboard gif landscape

enter image description here

Even if this is not the architecture you decide to go with, hopefully it'll be helpful to see the source code for a working in-app keyboard.

Again, here's the link to the project: Custom In-App Keyboard

EDIT: I'm no longer an Android developer, and I no longer maintain this GitHub project. There are probably more modern approaches and architectures at this point, but please feel free to reference the GitHub project if you'd like and fork it.

Remove rows not .isin('X')

All you have to do is create a subset of your dataframe where the isin method evaluates to False:

df = df[df['Column Name'].isin(['Value']) == False]

Get Last Part of URL PHP

One liner: $page_path = end(explode('/', trim($_SERVER['REQUEST_URI'], '/')));

Get URI, trim slashes, convert to array, grab last part

Python 3 print without parenthesis

Although you need a pair of parentheses to print in Python 3, you no longer need a space after print, because it's a function. So that's only a single extra character.

If you still find typing a single pair of parentheses to be "unnecessarily time-consuming," you can do p = print and save a few characters that way. Because you can bind new references to functions but not to keywords, you can only do this print shortcut in Python 3.

Python 2:

>>> p = print
  File "<stdin>", line 1
    p = print
            ^
SyntaxError: invalid syntax

Python 3:

>>> p = print
>>> p('hello')
hello

It'll make your code less readable, but you'll save those few characters every time you print something.

Optional query string parameters in ASP.NET Web API

It's possible to pass multiple parameters as a single model as vijay suggested. This works for GET when you use the FromUri parameter attribute. This tells WebAPI to fill the model from the query parameters.

The result is a cleaner controller action with just a single parameter. For more information see: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

public class BooksController : ApiController
  {
    // GET /api/books?author=tolk&title=lord&isbn=91&somethingelse=ABC&date=1970-01-01
    public string GetFindBooks([FromUri]BookQuery query)
    {
      // ...
    }
  }

  public class BookQuery
  {
    public string Author { get; set; }
    public string Title { get; set; }
    public string ISBN { get; set; }
    public string SomethingElse { get; set; }
    public DateTime? Date { get; set; }
  }

It even supports multiple parameters, as long as the properties don't conflict.

// GET /api/books?author=tolk&title=lord&isbn=91&somethingelse=ABC&date=1970-01-01
public string GetFindBooks([FromUri]BookQuery query, [FromUri]Paging paging)
{
  // ...
}

public class Paging
{
  public string Sort { get; set; }
  public int Skip { get; set; }
  public int Take { get; set; }
}

Update:
In order to ensure the values are optional make sure to use reference types or nullables (ex. int?) for the models properties.

How to return HTTP 500 from ASP.NET Core RC2 Web Api?

If you need a body in your response, you can call

return StatusCode(StatusCodes.Status500InternalServerError, responseObject);

This will return a 500 with the response object...

Better way to right align text in HTML Table

If it's always the third column, you can use this (assuming table class of "products"). It's kinda hacky though, and not robust if you add a new column.

table.products td+td+td {
  text-align: right;
}
table.products td,
table.products td+td+td+td {
  text-align: left;
}

But honestly, the best idea is to use a class on each cell. You can use the col element to set the width, border, background or visibility of a column, but not any other properties. Reasons discussed here.

Reading text files using read.table

From ?read.table: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.

So, perhaps your data file isn't clean. Being more specific will help the data import:

d = read.table("foobar.txt", 
               sep="\t", 
               col.names=c("id", "name"), 
               fill=FALSE, 
               strip.white=TRUE)

will specify exact columns and fill=FALSE will force a two column data frame.

Change value of input placeholder via model?

You can bind with a variable in the controller:

<input type="text" ng-model="inputText" placeholder="{{somePlaceholder}}" />

In the controller:

$scope.somePlaceholder = 'abc';

How do I change the background color of the ActionBar of an ActionBarActivity using XML?

Try this

ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable("COLOR"));

Convert laravel object to array

foreach($yourArrayName as $object)
{
    $arrays[] = $object->toArray();
}
// Dump array with object-arrays
dd($arrays);

Or when toArray() fails because it's a stdClass

foreach($yourArrayName as $object)
{
    $arrays[] =  (array) $object;
}
// Dump array with object-arrays
dd($arrays);

Not working? Maybe you can find your answer here:

Convert PHP object to associative array

#1214 - The used table type doesn't support FULLTEXT indexes

*************Resolved - #1214 - The used table type doesn't support FULLTEXT indexes***************

Its Very Simple to resolve this issue. People are answering here in very difficult words which are not easily understandable by the people who are not technical.

So i am mentioning here steps in very simple words will resolve your issue.

1.) Open your .sql file with Notepad by right clicking on file>Edit Or Simply open a Notepad file and drag and drop the file on Notepad and the file will be opened. (Note: Please don't change the extention .sql of file as its still your sql database. Also to keep a copy of your sql file to save yourself from any mishappening)

2.) Click on Notepad Menu Edit > Replace (A Window will be pop us with Find What & Replace With Fields)

3.) In Find What Field Enter ENGINE=InnoDB & In Replace With Field Enter ENGINE=MyISAM

4.) Now Click on Replace All Button

5.) Click CTRL+S or File>Save

6.) Now Upload This File and I am Sure your issue will be resolved....

C split a char array into different variables

You could simply replace the separator characters by NULL characters, and store the address after the newly created NULL character in a new char* pointer:

char* input = "asdf|qwer"
char* parts[10];
int partcount = 0;

parts[partcount++] = input;

char* ptr = input;
while(*ptr) { //check if the string is over
    if(*ptr == '|') {
        *ptr = 0;
        parts[partcount++] = ptr + 1;
    }
    ptr++;
}

Note that this code will of course not work if the input string contains more than 9 separator characters.

Java 8 Lambda function that throws exception?

By default, Java 8 Function does not allow to throw exception and as suggested in multiple answers there are many ways to achieve it, one way is:

@FunctionalInterface
public interface FunctionWithException<T, R, E extends Exception> {
    R apply(T t) throws E;
}

Define as:

private FunctionWithException<String, Integer, IOException> myMethod = (str) -> {
    if ("abc".equals(str)) {
        throw new IOException();
    }
  return 1;
};

And add throws or try/catch the same exception in caller method.

How to write palindrome in JavaScript

function palindrome(s) {
  var re = /[\W_]/g;
  var lowRegStr = s.toLowerCase().replace(re, '');
  var reverseStr = lowRegStr.split('').reverse().join(''); 
  return reverseStr === lowRegStr;
}

Find files in created between a date range

List files between 2 dates

find . -type f -newermt "2019-01-01" ! -newermt "2019-05-01"

or

find path -type f -newermt "2019-01-01" ! -newermt "2019-05-01"

Warning message: In `...` : invalid factor level, NA generated

The warning message is because your "Type" variable was made a factor and "lunch" was not a defined level. Use the stringsAsFactors = FALSE flag when making your data frame to force "Type" to be a character.

> fixed <- data.frame("Type" = character(3), "Amount" = numeric(3))
> str(fixed)
'data.frame':   3 obs. of  2 variables:
 $ Type  : Factor w/ 1 level "": NA 1 1
 $ Amount: chr  "100" "0" "0"
> 
> fixed <- data.frame("Type" = character(3), "Amount" = numeric(3),stringsAsFactors=FALSE)
> fixed[1, ] <- c("lunch", 100)
> str(fixed)
'data.frame':   3 obs. of  2 variables:
 $ Type  : chr  "lunch" "" ""
 $ Amount: chr  "100" "0" "0"

Professional jQuery based Combobox control?

Unfortunately, the best thing I have seen is the jquery.combobox, but it doesn't really look like something I'd really want to use in my web applications. I think there are some usability issues with this control, but as a user I don't think I'd know to start typing for the dropdownlist to turn into a textbox.

I much prefer the Combo Dropdown Box, but it still has some features that I'd want and it's still in alpha. The only think I don't like about this other than its being alpha... is that once I type in the combobox, the original dropdownlist items disappear. However, maybe there is a setting for this... or maybe it could be added fairly easily.

Those are the only two options that I know of. Good luck in your search. I'd love to hear if you find one or if the second option works out for you.

Android camera intent

I found a pretty simple way to do this. Use a button to open it using an on click listener to start the function openc(), like this:

String fileloc;
private void openc()
{
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File f = null;
    try 
    {
        f = File.createTempFile("temppic",".jpg",getApplicationContext().getCacheDir());
        if (takePictureIntent.resolveActivity(getPackageManager()) != null)
        {               
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,FileProvider.getUriForFile(profile.this, BuildConfig.APPLICATION_ID+".provider",f));
            fileloc = Uri.fromFile(f)+"";
            Log.d("texts", "openc: "+fileloc);
            startActivityForResult(takePictureIntent, 3);
        }
    } 
    catch (IOException e) 
    {
        e.printStackTrace();
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == 3 && resultCode == RESULT_OK) {
        Log.d("texts", "onActivityResult: "+fileloc);
        // fileloc is the uri of the file so do whatever with it
    }
}

You can do whatever you want with the uri location string. For instance, I send it to an image cropper to crop the image.

The requested URL /about was not found on this server

It worked for me like this:

Go to Wordpress Admin Dashboard > “Settings” > “Permalinks” > “Common settings”, set the radio button to “Custom Structure” and paste into the text box:

/index.php/%year%/%monthnum%/%day%/%postname%/

and click the Save button.

How to read an external local JSON file in JavaScript?

Using the Fetch API is the easiest solution:

fetch("test.json")
  .then(response => response.json())
  .then(json => console.log(json));

It works perfect in Firefox, but in Chrome you have to customize security setting.

Visual Studio Code - Convert spaces to tabs

{
  "editor.insertSpaces": true
}

True works for me.

How can I execute PHP code from the command line?

If you're using Laravel, you can use php artisan tinker to get an amazing interactive shell to interact with your Laravel app. However, Tinker works with "Psysh" under the hood which is a popular PHP REPL and you can use it even if you're not using Laravel (bare PHP):

// Bare PHP:
>>> preg_match("/hell/", "hello");
=> 1

// Laravel Stuff:
>>> Str::slug("How to get the job done?!!?!", "_");
=> "how_to_get_the_job_done"

One great feature I really like about Psysh is that it provides a quick way for directly looking up the PHP docs from the command line. To get it to work, you only have to take the following simple steps:

apt install php-sqlite3

And then get the required PHP documentation database and move it to the proper location:

wget http://psysh.org/manual/en/php_manual.sqlite
mkdir -p /usr/local/share/psysh/ && mv php_manual.sqlite /usr/local/share/psysh/

Now for instance:

Enter image description here

How can I send and receive WebSocket messages on the server side?

C# Implementation

Browser -> Server

    private String DecodeMessage(Byte[] bytes)
    {
        String incomingData = String.Empty;
        Byte secondByte = bytes[1];
        Int32 dataLength = secondByte & 127;
        Int32 indexFirstMask = 2;
        if (dataLength == 126)
            indexFirstMask = 4;
        else if (dataLength == 127)
            indexFirstMask = 10;

        IEnumerable<Byte> keys = bytes.Skip(indexFirstMask).Take(4);
        Int32 indexFirstDataByte = indexFirstMask + 4;

        Byte[] decoded = new Byte[bytes.Length - indexFirstDataByte];
        for (Int32 i = indexFirstDataByte, j = 0; i < bytes.Length; i++, j++)
        {
            decoded[j] = (Byte)(bytes[i] ^ keys.ElementAt(j % 4));
        }

        return incomingData = Encoding.UTF8.GetString(decoded, 0, decoded.Length);
    }

Server -> Browser

    private static Byte[] EncodeMessageToSend(String message)
    {
        Byte[] response;
        Byte[] bytesRaw = Encoding.UTF8.GetBytes(message);
        Byte[] frame = new Byte[10];

        Int32 indexStartRawData = -1;
        Int32 length = bytesRaw.Length;

        frame[0] = (Byte)129;
        if (length <= 125)
        {
            frame[1] = (Byte)length;
            indexStartRawData = 2;
        }
        else if (length >= 126 && length <= 65535)
        {
            frame[1] = (Byte)126;
            frame[2] = (Byte)((length >> 8) & 255);
            frame[3] = (Byte)(length & 255);
            indexStartRawData = 4;
        }
        else
        {
            frame[1] = (Byte)127;
            frame[2] = (Byte)((length >> 56) & 255);
            frame[3] = (Byte)((length >> 48) & 255);
            frame[4] = (Byte)((length >> 40) & 255);
            frame[5] = (Byte)((length >> 32) & 255);
            frame[6] = (Byte)((length >> 24) & 255);
            frame[7] = (Byte)((length >> 16) & 255);
            frame[8] = (Byte)((length >> 8) & 255);
            frame[9] = (Byte)(length & 255);

            indexStartRawData = 10;
        }

        response = new Byte[indexStartRawData + length];

        Int32 i, reponseIdx = 0;

        //Add the frame bytes to the reponse
        for (i = 0; i < indexStartRawData; i++)
        {
            response[reponseIdx] = frame[i];
            reponseIdx++;
        }

        //Add the data bytes to the response
        for (i = 0; i < length; i++)
        {
            response[reponseIdx] = bytesRaw[i];
            reponseIdx++;
        }

        return response;
    }

Add querystring parameters to link_to

If you want to keep existing params and not expose yourself to XSS attacks, be sure to clean the params hash, leaving only the params that your app can be sending:

# inline
<%= link_to 'Link', params.slice(:sort).merge(per_page: 20) %>

 

If you use it in multiple places, clean the params in the controller:

# your_controller.rb
@params = params.slice(:sort, :per_page)

# view
<%= link_to 'Link', @params.merge(per_page: 20) %>

Force flushing of output to a file while bash script is still running

How just spotted here the problem is that you have to wait that the programs that you run from your script finish their jobs.
If in your script you run program in background you can try something more.

In general a call to sync before you exit allows to flush file system buffers and can help a little.

If in the script you start some programs in background (&), you can wait that they finish before you exit from the script. To have an idea about how it can function you can see below

#!/bin/bash
#... some stuffs ...
program_1 &          # here you start a program 1 in background
PID_PROGRAM_1=${!}   # here you remember its PID
#... some other stuffs ... 
program_2 &          # here you start a program 2 in background
wait ${!}            # You wait it finish not really useful here
#... some other stuffs ... 
daemon_1 &           # We will not wait it will finish
program_3 &          # here you start a program 1 in background
PID_PROGRAM_3=${!}   # here you remember its PID
#... last other stuffs ... 
sync
wait $PID_PROGRAM_1
wait $PID_PROGRAM_3  # program 2 is just ended
# ...

Since wait works with jobs as well as with PID numbers a lazy solution should be to put at the end of the script

for job in `jobs -p`
do
   wait $job 
done

More difficult is the situation if you run something that run something else in background because you have to search and wait (if it is the case) the end of all the child process: for example if you run a daemon probably it is not the case to wait it finishes :-).

Note:

  • wait ${!} means "wait till the last background process is completed" where $! is the PID of the last background process. So to put wait ${!} just after program_2 & is equivalent to execute directly program_2 without sending it in background with &

  • From the help of wait:

    Syntax    
        wait [n ...]
    Key  
        n A process ID or a job specification
    

How to make a promise from setTimeout

This is not an answer to the original question. But, as an original question is not a real-world problem it should not be a problem. I tried to explain to a friend what are promises in JavaScript and the difference between promise and callback.

Code below serves as an explanation:

//very basic callback example using setTimeout
//function a is asynchronous function
//function b used as a callback
function a (callback){
    setTimeout (function(){
       console.log ('using callback:'); 
       let mockResponseData = '{"data": "something for callback"}'; 
       if (callback){
          callback (mockResponseData);
       }
    }, 2000);

} 

function b (dataJson) {
   let dataObject = JSON.parse (dataJson);
   console.log (dataObject.data);   
}

a (b);

//rewriting above code using Promise
//function c is asynchronous function
function c () {
   return new Promise(function (resolve, reject) {
     setTimeout (function(){
       console.log ('using promise:'); 
       let mockResponseData = '{"data": "something for promise"}'; 
       resolve(mockResponseData); 
    }, 2000);      
   }); 

}

c().then (b);

JsFiddle

Reloading submodules in IPython

http://shawnleezx.github.io/blog/2015/08/03/some-notes-on-ipython-startup-script/

To avoid typing those magic function again and again, they could be put in the ipython startup script(Name it with .py suffix under .ipython/profile_default/startup. All python scripts under that folder will be loaded according to lexical order), which looks like the following:

from IPython import get_ipython
ipython = get_ipython()

ipython.magic("pylab")
ipython.magic("load_ext autoreload")
ipython.magic("autoreload 2")

How to save data in an android app

OP is asking for a "save" function, which is more than just preserving data across executions of the program (which you must do for the app to be worth anything.)

I recommend saving the data in a file on the sdcard which allows you to not only recall it later, but allows the user to mount the device as an external drive on their own computer and grab the data for use in other places.

So you really need a multi-point system:

1) Implement onSaveInstanceState(). In this method, you're passed a Bundle, which is basically like a dictionary. Store as much information in the bundle as would be needed to restart the app exactly where it left off. In your onCreate() method, check for the passed-in bundle to be non-null, and if so, restore the state from the bundle.

2) Implement onPause(). In this method, create a SharedPreferences editor and use it to save whatever state you need to start the app up next time. This mainly consists of the users' preferences (hence the name), but anything else relavent to the app's start-up state should go here as well. I would not store scores here, just the stuff you need to restart the app. Then, in onCreate(), whenever there's no bundle object, use the SharedPreferences interface to recall those settings.

3a) As for things like scores, you could follow Mathias's advice above and store the scores in the directory returned in getFilesDir(), using openFileOutput(), etc. I think this directory is private to the app and lives in main storage, meaning that other apps and the user would not be able to access the data. If that's ok with you, then this is probably the way to go.

3b) If you do want other apps or the user to have direct access to the data, or if the data is going to be very large, then the sdcard is the way to go. Pick a directory name like com/user1446371/basketballapp/ to avoid collisions with other applications (unless you're sure that your app name is reasonably unique) and create that directory on the sdcard. As Mathias pointed out, you should first confirm that the sdcard is mounted.

File sdcard = Environment.getExternalStorageDirectory();
if( sdcard == null || !sdcard.isDirectory()) {
    fail("sdcard not available");
}
File datadir = new File(sdcard, "com/user1446371/basketballapp/");
if( !datadir.exists() && !datadir.mkdirs() ) {
    fail("unable to create data directory");
}
if( !datadir.isDirectory() ) {
    fail("exists, but is not a directory");
}
// Now use regular java I/O to read and write files to data directory

I recommend simple CSV files for your data, so that other applications can read them easily.

Obviously, you'll have to write activities that allow "save" and "open" dialogs. I generally just make calls to the openintents file manager and let it do the work. This requires that your users install the openintents file manager to make use of these features, however.

How to join components of a path when you are constructing a URL in Python

I know this is a bit more than the OP asked for, However I had the pieces to the following url, and was looking for a simple way to join them:

>>> url = 'https://api.foo.com/orders/bartag?spamStatus=awaiting_spam&page=1&pageSize=250'

Doing some looking around:

>>> split = urlparse.urlsplit(url)
>>> split
SplitResult(scheme='https', netloc='api.foo.com', path='/orders/bartag', query='spamStatus=awaiting_spam&page=1&pageSize=250', fragment='')
>>> type(split)
<class 'urlparse.SplitResult'>
>>> dir(split)
['__add__', '__class__', '__contains__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__getstate__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__weakref__', '_asdict', '_fields', '_make', '_replace', 'count', 'fragment', 'geturl', 'hostname', 'index', 'netloc', 'password', 'path', 'port', 'query', 'scheme', 'username']
>>> split[0]
'https'
>>> split = (split[:])
>>> type(split)
<type 'tuple'>

So in addition to the path joining which has already been answered in the other answers, To get what I was looking for I did the following:

>>> split
('https', 'api.foo.com', '/orders/bartag', 'spamStatus=awaiting_spam&page=1&pageSize=250', '')
>>> unsplit = urlparse.urlunsplit(split)
>>> unsplit
'https://api.foo.com/orders/bartag?spamStatus=awaiting_spam&page=1&pageSize=250'

According to the documentation it takes EXACTLY a 5 part tuple.

With the following tuple format:

scheme 0 URL scheme specifier empty string

netloc 1 Network location part empty string

path 2 Hierarchical path empty string

query 3 Query component empty string

fragment 4 Fragment identifier empty string

How to convert a char array back to a string?

String output = new String(charArray);

Where charArray is the character array and output is your character array converted to the string.

How to run a PowerShell script from a batch file

You need the -ExecutionPolicy parameter:

Powershell.exe -executionpolicy remotesigned -File  C:\Users\SE\Desktop\ps.ps1

Otherwise PowerShell considers the arguments a line to execute and while Set-ExecutionPolicy is a cmdlet, it has no -File parameter.

How can I add "href" attribute to a link dynamically using JavaScript?

First, try changing <a>Link</a> to <span id=test><a>Link</a></span>.

Then, add something like this in the javascript function that you're calling:

var abc = 'somelink';
document.getElementById('test').innerHTML = '<a href="' + abc + '">Link</a>';

This way the link will look like this:

<a href="somelink">Link</a>

How can I display a list view in an Android Alert Dialog?

In Kotlin:

fun showListDialog(context: Context){
    // setup alert builder
    val builder = AlertDialog.Builder(context)
    builder.setTitle("Choose an Item")

    // add list items
    val listItems = arrayOf("Item 0","Item 1","Item 2")
    builder.setItems(listItems) { dialog, which ->
        when (which) {
            0 ->{
                Toast.makeText(context,"You Clicked Item 0",Toast.LENGTH_LONG).show()
                dialog.dismiss()
            }
            1->{
                Toast.makeText(context,"You Clicked Item 1",Toast.LENGTH_LONG).show()
                dialog.dismiss()
            }
            2->{
                Toast.makeText(context,"You Clicked Item 2",Toast.LENGTH_LONG).show()
                dialog.dismiss()
            }
        }
    }

    // create & show alert dialog
    val dialog = builder.create()
    dialog.show()
}

Add button to a layout programmatically

If you just have included a layout file at the beginning of onCreate() inside setContentView and want to get this layout to add new elements programmatically try this:

ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayoutID);

then you can create a new Button for example and just add it:

Button bt = new Button(this);
bt.setText("A Button");
bt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 
                                    LayoutParams.WRAP_CONTENT));
linerLayout.addView(bt);

Xampp localhost/dashboard

Try this solution:

Go to->

  1. xammp ->htdocs-> then open index.php from the htdocs folder
  2. you can modify the dashboard
  3. restart the server

Example Code index.php :

    <?php
    if (!empty($_SERVER['HTTPS']) && ('on' == $_SERVER['HTTPS'])) {
        $uri = 'https://';
    } else {
        $uri = 'http://';
    }
    $uri .= $_SERVER['HTTP_HOST'];
    header('Location: '.$uri.'/dashboard/');
    exit;
   ?>

Is there a way to add a gif to a Markdown file?

Upload from local:

  1. Add your .gif file to the root of Github repository and push the change.
  2. Go to README.md
  3. Add this ![Alt text](name-of-gif-file.gif) / ![](name-of-gif-file.gif)
  4. Commit and gif should be seen.

Show the gif using url:

  1. Go to README.md
  2. Add in this format ![Alt text](https://sample/url/name-of-gif-file.gif)
  3. Commit and gif should be seen.

Hope this helps.

How to get the number of days of difference between two dates on mysql?

Get days between Current date to destination Date

 SELECT DATEDIFF('2019-04-12', CURDATE()) AS days;

output

days

 335

Java 8 lambda Void argument

That is not possible. A function that has a non-void return type (even if it's Void) has to return a value. However you could add static methods to Action that allows you to "create" a Action:

interface Action<T, U> {
   U execute(T t);

   public static Action<Void, Void> create(Runnable r) {
       return (t) -> {r.run(); return null;};
   }

   public static <T, U> Action<T, U> create(Action<T, U> action) {
       return action;
   } 
}

That would allow you to write the following:

// create action from Runnable
Action.create(()-> System.out.println("Hello World")).execute(null);
// create normal action
System.out.println(Action.create((Integer i) -> "number: " + i).execute(100));

How to get the position of a character in Python?

string.find(character)  
string.index(character)  

Perhaps you'd like to have a look at the documentation to find out what the difference between the two is.

What is the easiest way to get the current day of the week in Android?

Using both method you find easy if you wont last seven days you use (currentdaynumber+7-1)%7,(currentdaynumber+7-2)%7.....upto 6

public static String getDayName(int day){
    switch(day){
        case 0:
            return "Sunday";
        case 1:
            return "Monday";
        case 2:
            return "Tuesday";
        case 3:
            return "Wednesday";
        case 4:
            return "Thursday";
        case 5:
            return  "Friday";
        case 6:
            return "Saturday";
    }

    return "Worng Day";
}
public static String getCurrentDay(){
    SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE", Locale.US);
    Calendar calendar = Calendar.getInstance();
    return dayFormat.format(calendar.getTime());

}

Converting Long to Date in Java returns 1970

The Date constructor (click the link!) accepts the time as long in milliseconds, not seconds. You need to multiply it by 1000 and make sure that you supply it as long.

Date d = new Date(1220227200L * 1000);

This shows here

Sun Aug 31 20:00:00 GMT-04:00 2008

jQuery DataTables: control table width

This works fine.

#report_container {
   float: right;
   position: relative;
   width: 100%;
}

How to trigger event when a variable's value is changed?

A simple method involves using the get and set functions on the variable


    using System;
    public string Name{
    get{
     return name;
    }
    
    set{
     name= value;
     OnVarChange?.Invoke();
    }
    }
    private string name;
    
    public event System.Action OnVarChange;

Accept function as parameter in PHP

PHP VERSION >= 5.3.0

Example 1: basic

function test($test_param, $my_function) {
    return $my_function($test_param);
}

test("param", function($param) {
    echo $param;
}); //will echo "param"

Example 2: std object

$obj = new stdClass();
$obj->test = function ($test_param, $my_function) {
    return $my_function($test_param);
};

$test = $obj->test;
$test("param", function($param) {
    echo $param;
});

Example 3: non static class call

class obj{
    public function test($test_param, $my_function) {
        return $my_function($test_param);
    }
}

$obj = new obj();
$obj->test("param", function($param) {
    echo $param;
});

Example 4: static class call

class obj {
    public static function test($test_param, $my_function) {
        return $my_function($test_param);
    }
}

obj::test("param", function($param) {
    echo $param;
});

Android Split string

     String s = "having Community Portal|Help Desk|Local Embassy|Reference Desk|Site News";
     StringTokenizer st = new StringTokenizer(s, "|");
        String community = st.nextToken();
        String helpDesk = st.nextToken(); 
        String localEmbassy = st.nextToken();
        String referenceDesk = st.nextToken();
        String siteNews = st.nextToken();

How to increase font size in the Xcode editor?

You can use the following:

  1. Press xcode->preferences
  2. select fonts and colors
  3. select ANY font in the list and press cmd+a (select all fonts)
  4. select font size for all editor fonts at the bottom of the window

Getting attributes of a class

My solution to get all attributes (not methods) of a class (if the class has a properly written docstring that has the attributes clearly spelled out):

def get_class_attrs(cls):
    return re.findall(r'\w+(?=[,\)])', cls.__dict__['__doc__'])

This piece cls.__dict__['__doc__'] extracts the docstring of the class.

How can I avoid Java code in JSP files, using JSP 2?

In order to avoid Java code in JSP files, Java now provides tag libraries, like JSTL.

Also, Java has come up with JSF into which you can write all programming structures in the form of tags.

Convert char* to string C++

Use the string's constructor

basic_string(const charT* s,size_type n, const Allocator& a = Allocator());

EDIT:

OK, then if the C string length is not given explicitly, use the ctor:

basic_string(const charT* s, const Allocator& a = Allocator());

Including external HTML file to another HTML file

You can use jquery load for that.

<script type="text/javascript">
$(document).ready(function(e) {
    $('#header').load('name.html',function(){alert('loaded')});
});
</script>

Don't forget to include jquery library befor above code.

how to check which version of nltk, scikit learn installed?

You can find NLTK version simply by doing:

In [1]: import nltk

In [2]: nltk.__version__
Out[2]: '3.2.5'

And similarly for scikit-learn,

In [3]: import sklearn

In [4]: sklearn.__version__
Out[4]: '0.19.0'

I'm using python3 here.

How to check if a variable is NULL, then set it with a MySQL stored procedure?

@last_run_time is a 9.4. User-Defined Variables and last_run_time datetime one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.

Try: SELECT last_run_time;

UPDATE

Example:

/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$

CREATE PROCEDURE `sp_test`()
BEGIN
    DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
    DECLARE last_run_time DATETIME DEFAULT NULL;
    DECLARE current_run_time DATETIME DEFAULT NOW();

    -- Define the last run time
    SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);

    -- if there is no last run time found then use yesterday as starting point
    IF(last_run_time IS NULL) THEN
        SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
    END IF;

    SELECT last_run_time;

    -- Insert variables in table2
    INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$

DELIMITER ;

What are the -Xms and -Xmx parameters when starting JVM?

-Xms initial heap size for the startup, however, during the working process the heap size can be less than -Xms due to users' inactivity or GC iterations. This is not a minimal required heap size.

-Xmx maximal heap size

Split Strings into words with multiple word boundary delimiters

Another way, without regex

import string
punc = string.punctuation
thestring = "Hey, you - what are you doing here!?"
s = list(thestring)
''.join([o for o in s if not o in punc]).split()

A field initializer cannot reference the nonstatic field, method, or property

You need to put that code into the constructor of your class:

private Reminders reminder = new Reminders();
private dynamic defaultReminder;

public YourClass()
{
    defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)];
}

The reason is that you can't use one instance variable to initialize another one using a field initializer.

Check that Field Exists with MongoDB

Use $ne (for "not equal")

db.collection.find({ "fieldToCheck": { $exists: true, $ne: null } })

How to retry image pull in a kubernetes Pods?

$ kubectl replace --force -f <resource-file>

if all goes well, you should see something like:

<resource-type> <resource-name> deleted
<resource-type> <resource-name> replaced

details of this can be found in the Kubernetes documentation, "manage-deployment" and kubectl-cheatsheet pages at the time of writing.

How to "EXPIRE" the "HSET" child key in redis?

You can expire Redis hashes in ease, Eg using python

import redis
conn = redis.Redis('localhost')
conn.hmset("hashed_user", {'name': 'robert', 'age': 32})
conn.expire("hashed_user", 10)

This will expire all child keys in hash hashed_user after 10 seconds

same from redis-cli,

127.0.0.1:6379> HMSET testt username wlc password P1pp0 age 34
OK
127.0.0.1:6379> hgetall testt
1) "username"
2) "wlc"
3) "password"
4) "P1pp0"
5) "age"
6) "34"
127.0.0.1:6379> expire testt 10
(integer) 1
127.0.0.1:6379> hgetall testt
1) "username"
2) "wlc"
3) "password"
4) "P1pp0"
5) "age"
6) "34"

after 10 seconds

127.0.0.1:6379> hgetall testt
(empty list or set)

Declaring and initializing a string array in VB.NET

I believe you need to specify "Option Infer On" for this to work.

Option Infer allows the compiler to make a guess at what is being represented by your code, thus it will guess that {"stuff"} is an array of strings. With "Option Infer Off", {"stuff"} won't have any type assigned to it, ever, and so it will always fail, without a type specifier.

Option Infer is, I think On by default in new projects, but Off by default when you migrate from earlier frameworks up to 3.5.

Opinion incoming:

Also, you mention that you've got "Option Explicit Off". Please don't do this.

Setting "Option Explicit Off" means that you don't ever have to declare variables. This means that the following code will silently and invisibly create the variable "Y":

Dim X as Integer
Y = 3

This is horrible, mad, and wrong. It creates variables when you make typos. I keep hoping that they'll remove it from the language.

How to import Angular Material in project?

If you want to import all Material modules, create your own module i.e. material.module.ts and do something like the following:

_x000D_
_x000D_
import { NgModule } from '@angular/core';_x000D_
import * as MATERIAL_MODULES from '@angular/material';_x000D_
_x000D_
export function mapMaterialModules() {_x000D_
  return Object.keys(MATERIAL_MODULES).filter((k) => {_x000D_
    let asset = MATERIAL_MODULES[k];_x000D_
    return typeof asset == 'function'_x000D_
      && asset.name.startsWith('Mat')_x000D_
      && asset.name.includes('Module');_x000D_
  }).map((k) => MATERIAL_MODULES[k]);_x000D_
}_x000D_
const modules = mapMaterialModules();_x000D_
_x000D_
@NgModule({_x000D_
    imports: modules,_x000D_
    exports: modules_x000D_
})_x000D_
export class MaterialModule { }
_x000D_
_x000D_
_x000D_

Then import the module into your app.module.ts

Origin http://localhost is not allowed by Access-Control-Allow-Origin

By localhost you have to use the null origin. I recommend you to create a list of allowed hosts and check the request's Host header. If it is contained by the list, then by localhost send back an

res.header('Access-Control-Allow-Origin', "null");

by any other domain an

res.header('Access-Control-Allow-Origin', hostSentByTheRequestHeader);

If it is not contained by the list, then send back the servers host name, so the browser will hide the response by those requests.

This is much more secure, because by allow origin * and allow credentials everybody will be capable of for example stealing profile data of a logged in user, etc...

So to summarize something like this:

if (reqHost in allowedHosts)
    if (reqHost == "http://localhost")
        res.header('Access-Control-Allow-Origin', "null");
    else
        res.header('Access-Control-Allow-Origin', reqHost);
else
    res.header('Access-Control-Allow-Origin', serverHost);

is the most secure solution if you want to allow multiple other domains to access your page. (I guess you can figure out how the get the host request header and the server host by node.js.)

Import / Export database with SQL Server Server Management Studio

I tried the answers above but the generated script file was very large and I was having problems while importing the data. I ended up Detaching the database, then copying .mdf to my new machine, then Attaching it to my new version of SQL Server Management Studio.

I found instructions for how to do this on the Microsoft Website:
https://msdn.microsoft.com/en-us/library/ms187858.aspx

NOTE: After Detaching the database I found the .mdf file within this directory:
C:\Program Files\Microsoft SQL Server\

Understanding esModuleInterop in tsconfig file

esModuleInterop generates the helpers outlined in the docs. Looking at the generated code, we can see exactly what these do:

//ts 
import React from 'react'
//js 
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = __importDefault(require("react"));

__importDefault: If the module is not an es module then what is returned by require becomes the default. This means that if you use default import on a commonjs module, the whole module is actually the default.

__importStar is best described in this PR:

TypeScript treats a namespace import (i.e. import * as foo from "foo") as equivalent to const foo = require("foo"). Things are simple here, but they don't work out if the primary object being imported is a primitive or a value with call/construct signatures. ECMAScript basically says a namespace record is a plain object.

Babel first requires in the module, and checks for a property named __esModule. If __esModule is set to true, then the behavior is the same as that of TypeScript, but otherwise, it synthesizes a namespace record where:

  1. All properties are plucked off of the require'd module and made available as named imports.
  2. The originally require'd module is made available as a default import.

So we get this:

// ts
import * as React from 'react'

// emitted js
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var React = __importStar(require("react"));

allowSyntheticDefaultImports is the companion to all of this, setting this to false will not change the emitted helpers (both of them will still look the same). But it will raise a typescript error if you are using default import for a commonjs module. So this import React from 'react' will raise the error Module '".../node_modules/@types/react/index"' has no default export. if allowSyntheticDefaultImports is false.

How to use global variables in React Native?

Set up a flux container

simple example

import alt from './../../alt.js';

    class PostActions {
        constructor(){
        this.generateActions('setMessages');
        }

        setMessages(indexArray){
            this.actions.setMessages(indexArray);
        }
    }


export default alt.createActions(PostActions);

store looks like this

class PostStore{

    constructor(){

       this.messages = [];

       this.bindActions(MessageActions);
    }




    setMessages(messages){
        this.messages = messages;
    }
}

export default alt.createStore(PostStore);

Then every component that listens to the store can share this variable In your constructor is where you should grab it

constructor(props){
    super(props);

   //here is your data you get from the store, do what you want with it 
    var messageStore = MessageStore.getState();

}


    componentDidMount() {
      MessageStore.listen(this.onMessageChange.bind(this));
    }

    componentWillUnmount() {
      MessageStore.unlisten(this.onMessageChange.bind(this));
    }

    onMessageChange(state){ 
        //if the data ever changes each component listining will be notified and can do the proper processing. 
   }

This way, you can share you data across the app without every component having to communicate with each other.

Remove all occurrences of char from string

Try using the overload that takes CharSequence arguments (eg, String) rather than char:

str = str.replace("X", "");

Produce a random number in a range using C#

Here is updated version from Darrelk answer. It is implemented using C# extension methods. It does not allocate memory (new Random()) every time this method is called.

public static class RandomExtensionMethods
{
    public static double NextDoubleRange(this System.Random random, double minNumber, double maxNumber)
    {
        return random.NextDouble() * (maxNumber - minNumber) + minNumber;
    }
}

Usage (make sure to import the namespace that contain the RandomExtensionMethods class):

var random = new System.Random();
double rx = random.NextDoubleRange(0.0, 1.0);
double ry = random.NextDoubleRange(0.0f, 1.0f);
double vx = random.NextDoubleRange(-0.005f, 0.005f);
double vy = random.NextDoubleRange(-0.005f, 0.005f);

How to find cube root using Python?

The best way is to use simple math

>>> a = 8
>>> a**(1./3.)
2.0

EDIT

For Negative numbers

>>> a = -8
>>> -(-a)**(1./3.)
-2.0

Complete Program for all the requirements as specified

x = int(input("Enter an integer: "))
if x>0:
    ans = x**(1./3.)
    if ans ** 3 != abs(x):
        print x, 'is not a perfect cube!'
else:
    ans = -((-x)**(1./3.))
    if ans ** 3 != -abs(x):
        print x, 'is not a perfect cube!'

print 'Cube root of ' + str(x) + ' is ' + str(ans)

How can I get client information such as OS and browser

You cannot reliably get this information. The basis of several answers provided here is to examine the User-Agent header of the HTTP request. However, there is no way to know if the information in the User-Agent header is truthful. The client sending the request can write anything in that header. So its content can be spoofed, or not sent at all.

PHP CURL DELETE request

My own class request with wsse authentication

class Request {

    protected $_url;
    protected $_username;
    protected $_apiKey;

    public function __construct($url, $username, $apiUserKey) {
        $this->_url = $url;     
        $this->_username = $username;
        $this->_apiKey = $apiUserKey;
    }

    public function getHeader() {
        $nonce = uniqid();
        $created = date('c');
        $digest = base64_encode(sha1(base64_decode($nonce) . $created . $this->_apiKey, true));

        $wsseHeader = "Authorization: WSSE profile=\"UsernameToken\"\n";
        $wsseHeader .= sprintf(
            'X-WSSE: UsernameToken Username="%s", PasswordDigest="%s", Nonce="%s", Created="%s"', $this->_username, $digest, $nonce, $created
        );

        return $wsseHeader;
    }

    public function curl_req($path, $verb=NULL, $data=array()) {                    

        $wsseHeader[] = "Accept: application/vnd.api+json";
        $wsseHeader[] = $this->getHeader();

        $options = array(
            CURLOPT_URL => $this->_url . $path,
            CURLOPT_HTTPHEADER => $wsseHeader,
            CURLOPT_RETURNTRANSFER => true, 
            CURLOPT_HEADER => false             
        );                  

        if( !empty($data) ) {
            $options += array(
                CURLOPT_POSTFIELDS => $data,
                CURLOPT_SAFE_UPLOAD => true
            );                          
        }

        if( isset($verb) ) {
            $options += array(CURLOPT_CUSTOMREQUEST => $verb);                          
        }

        $ch = curl_init();
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);                   

        if(false === $result ) {
            echo curl_error($ch);
        }
        curl_close($ch);

        return $result; 
    }
}

finished with non zero exit value

For anyone who is trying to use the NDK for the first time, install the NDK via Android Studio's SDK Manager. After I did that the error went away.

Previously I had been following other tutorials/posts that just said to download the NDK yourself, but no one said where to put it. Letting Android Studio handle it fixed the error and allowed my app to launch.

Using an integer as a key in an associative array in JavaScript

If the use case is storing data in a collection then ECMAScript 6 provides the Map type.

It's only heavier to initialize.

Here is an example:

const map = new Map();
map.set(1, "One");
map.set(2, "Two");
map.set(3, "Three");

console.log("=== With Map ===");

for (const [key, value] of map) {
    console.log(`${key}: ${value} (${typeof(key)})`);
}

console.log("=== With Object ===");

const fakeMap = {
    1: "One",
    2: "Two",
    3: "Three"
};

for (const key in fakeMap) {
    console.log(`${key}: ${fakeMap[key]} (${typeof(key)})`);
}

Result:

=== With Map ===
1: One (number)
2: Two (number)
3: Three (number)
=== With Object ===
1: One (string)
2: Two (string)
3: Three (string)

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

Converting to upper and lower case in Java

WordUtils.capitalizeFully(str) from apache commons-lang has the exact semantics as required.

Convert string (without any separator) to list

You can use the re module:

import re
re.sub(r'\D', '', '+123-456-7890')

This will replace all non-digits with ''.

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

Try this one.

Sample Code

String str = " hello     there   ";
System.out.println(str.replaceAll("( +)"," ").trim());

OUTPUT

hello there

First it will replace all the spaces with single space. Than we have to supposed to do trim String because Starting of the String and End of the String it will replace the all space with single space if String has spaces at Starting of the String and End of the String So we need to trim them. Than you get your desired String.

os.walk without digging into directories below

create a list of excludes, use fnmatch to skip the directory structure and do the process

excludes= ['a\*\b', 'c\d\e']
for root, directories, files in os.walk('Start_Folder'):
    if not any(fnmatch.fnmatch(nf_root, pattern) for pattern in excludes):
        for root, directories, files in os.walk(nf_root):
            ....
            do the process
            ....

same as for 'includes':

if **any**(fnmatch.fnmatch(nf_root, pattern) for pattern in **includes**):

Javascript reduce() on Object

You can use a generator expression (supported in all browsers for years now, and in Node) to get the key-value pairs in a list you can reduce on:

>>> a = {"b": 3}
Object { b=3}

>>> [[i, a[i]] for (i in a) if (a.hasOwnProperty(i))]
[["b", 3]]

Git Bash is extremely slow on Windows 7 x64

In my case, it actually was Avast antivirus leading to Git Bash and even PowerShell becoming really slow.

I first tried disabling Avast for 10 minutes to see if it improved the speed and it did. Afterwards, I added the entire Git Bash installation directory as an exception in Avast, for Read, Write and Execute. In my case that was C:\Program Files\Git\*.

using "if" and "else" Stored Procedures MySQL

I think that this construct: if exists (select... is specific for MS SQL. In MySQL EXISTS predicate tells you whether the subquery finds any rows and it's used like this: SELECT column1 FROM t1 WHERE EXISTS (SELECT * FROM t2);

You can rewrite the above lines of code like this:

DELIMITER $$

CREATE PROCEDURE `checando`(in nombrecillo varchar(30), in contrilla varchar(30), out resultado int)

BEGIN
    DECLARE count_prim INT;
    DECLARE count_sec INT;

    SELECT COUNT(*) INTO count_prim FROM compas WHERE nombre = nombrecillo AND contrasenia = contrilla;
    SELECT COUNT(*) INTO count_sec FROM FROM compas WHERE nombre = nombrecillo;

    if (count_prim > 0) then
        set resultado = 0;
    elseif (count_sec > 0) then
        set resultado = -1;
    else 
        set resultado = -2;
    end if;
    SELECT resultado;
END

Cannot get OpenCV to compile because of undefined references?

This is a linker issue. Try:

g++ -o test_1 test_1.cpp `pkg-config opencv --cflags --libs`

This should work to compile the source. However, if you recently compiled OpenCV from source, you will meet linking issue in run-time, the library will not be found. In most cases, after compiling libraries from source, you need to do finally:

sudo ldconfig

What is the Oracle equivalent of SQL Server's IsNull() function?

Also use NVL2 as below if you want to return other value from the field_to_check:

NVL2( field_to_check, value_if_NOT_null, value_if_null )

Usage: ORACLE/PLSQL: NVL2 FUNCTION

Null or empty check for a string variable

Use This way is Better

if LEN(ISNULL(@Value,''))=0              

This check the field is empty or NULL

How to set the locale inside a Debian/Ubuntu Docker container?

Put in your Dockerfile something adapted from

# Set the locale
RUN sed -i '/en_US.UTF-8/s/^# //g' /etc/locale.gen && \
    locale-gen
ENV LANG en_US.UTF-8  
ENV LANGUAGE en_US:en  
ENV LC_ALL en_US.UTF-8     

If you run Debian or Ubuntu, you also need to install locales to have locale-gen with

apt-get -y install locales

this is extracted from the very good post on that subject, from

http://jaredmarkell.com/docker-and-locales/

Why is `input` in Python 3 throwing NameError: name... is not defined

You're running your Python 3 code with a Python 2 interpreter. If you weren't, your print statement would throw up a SyntaxError before it ever prompted you for input.

The result is that you're using Python 2's input, which tries to eval your input (presumably sdas), finds that it's invalid Python, and dies.

"Conversion to Dalvik format failed with error 1" on external JAR

This error was being caused for me due to several files I had excluded from the build path being deleted, but not removed from the exclusion list.

Project -> Properites -> Java Build Path -> Source tab -> project/src folder -> double click on Excluded -> Remove any files that no longer exist in the project.

httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName

Turns out that I had this problem and it was because I used "tabs" to indent lines instead of spaces. Just posting, in case it helps anyone.

How do I execute cmd commands through a batch file?

cmd /k cd c:\ is the right answer

Check if string contains only whitespace

I used following:

if str and not str.isspace():
  print('not null and not empty nor whitespace')
else:
  print('null or empty or whitespace')

How do you properly return multiple values from a Promise?

Simply make an object and extract arguments from that object.

let checkIfNumbersAddToTen = function (a, b) {
return new Promise(function (resolve, reject) {
 let c = parseInt(a)+parseInt(b);
 let promiseResolution = {
     c:c,
     d : c+c,
     x : 'RandomString'
 };
 if(c===10){
     resolve(promiseResolution);
 }else {
     reject('Not 10');
 }
});
};

Pull arguments from promiseResolution.

checkIfNumbersAddToTen(5,5).then(function (arguments) {
console.log('c:'+arguments.c);
console.log('d:'+arguments.d);
console.log('x:'+arguments.x);
},function (failure) {
console.log(failure);
});

AngularJS : Clear $watch

If you have too much watchers and you need to clear all of them, you can push them into an array and destroy every $watch in a loop.

var watchers = [];
watchers.push( $scope.$watch('watch-xxx', function(newVal){
   //do something
}));    

for(var i = 0; i < watchers.length; ++i){
    if(typeof watchers[i] === 'function'){
        watchers[i]();
    }
}

watchers = [];

Android: checkbox listener

Try this:

satView = (CheckBox) findViewById(R.id.sateliteCheckBox);

satView.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    @Override 
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
          if (buttonView.isChecked()) { 
                // checked
          } 
          else 
          {
                // not checked
          }
    }

});

Hope this helps.

Is it safe to shallow clone with --depth 1, create commits, and pull updates again?

Note that Git 1.9/2.0 (Q1 2014) has removed that limitation.
See commit 82fba2b, from Nguy?n Thái Ng?c Duy (pclouds):

Now that git supports data transfer from or to a shallow clone, these limitations are not true anymore.

The documentation now reads:

--depth <depth>::

Create a 'shallow' clone with a history truncated to the specified number of revisions.

That stems from commits like 0d7d285, f2c681c, and c29a7b8 which support clone, send-pack /receive-pack with/from shallow clones.
smart-http now supports shallow fetch/clone too.

All the details are in "shallow.c: the 8 steps to select new commits for .git/shallow".

Update June 2015: Git 2.5 will even allow for fetching a single commit!
(Ultimate shallow case)


Update January 2016: Git 2.8 (Mach 2016) now documents officially the practice of getting a minimal history.
See commit 99487cf, commit 9cfde9e (30 Dec 2015), commit 9cfde9e (30 Dec 2015), commit bac5874 (29 Dec 2015), and commit 1de2e44 (28 Dec 2015) by Stephen P. Smith (``).
(Merged by Junio C Hamano -- gitster -- in commit 7e3e80a, 20 Jan 2016)

This is "Documentation/user-manual.txt"

A <<def_shallow_clone,shallow clone>> is created by specifying the git-clone --depth switch.
The depth can later be changed with the git-fetch --depth switch, or full history restored with --unshallow.

Merging inside a <<def_shallow_clone,shallow clone>> will work as long as a merge base is in the recent history.
Otherwise, it will be like merging unrelated histories and may have to result in huge conflicts.
This limitation may make such a repository unsuitable to be used in merge based workflows.

Update 2020:

  • git 2.11.1 introduced option git fetch --shallow-exclude= to prevent fetching all history
  • git 2.11.1 introduced option git fetch --shallow-since= to prevent fetching old commits.

For more on the shallow clone update process, see "How to update a git shallow clone?".


As commented by Richard Michael:

to backfill history: git pull --unshallow

And Olle Härstedt adds in the comments:

To backfill part of the history: git fetch --depth=100.

How can I add a username and password to Jenkins?

If installed as an admin, use:-

uname - admin
pw - the passkey that was generated during installation

How to create a DateTime equal to 15 minutes ago?

 datetime.datetime.now() - datetime.timedelta(minutes=15)

jquery variable syntax

$self has little to do with $, which is an alias for jQuery in this case. Some people prefer to put a dollar sign together with the variable to make a distinction between regular vars and jQuery objects.

example:

var self = 'some string';
var $self = 'another string';

These are declared as two different variables. It's like putting underscore before private variables.

A somewhat popular pattern is:

var foo = 'some string';
var $foo = $('.foo');

That way, you know $foo is a cached jQuery object later on in the code.

Where does PostgreSQL store the database?

Everyone already answered but just for the latest updates. If you want to know where all the configuration files reside then run this command in the shell

SELECT name, setting FROM pg_settings WHERE category = 'File Locations';

ORA-12514 TNS:listener does not currently know of service requested in connect descriptor

I have implemented below workaround to resolve this issue.

  1. I have set the ORACLE_HOME using command prompt (right click cmd.exe and Run as System administrator).

  2. Used below command

    set oracle_home="path to the oracle home"

  3. Go to All programs --> Oracle -ora home1 --> Configuration migration tools --> Net Manager --> Listener

  4. Select Database Services from dropdown. Both Global database name and SID are set to the same (ORCL in my case). Set Oracle Home Directory.

Oracle Net Manager window example from oracle documentation: Oracle Net Manager example

  1. Click on File and save network configuration.

Get epoch for a specific date using Javascript

Take a look at http://www.w3schools.com/jsref/jsref_obj_date.asp

There is a function UTC() that returns the milliseconds from the unix epoch.

Bridged networking not working in Virtualbox under Windows 10

I solved it with similar way to @Khalil's but I attched to 'Bridged Adapter' instead of 'Host-only Adapter'. Here is more detail with screenshots.

In Android EditText, how to force writing uppercase?

For me it worked by adding android:textAllCaps="true" and android:inputType="textCapCharacters"

<android.support.design.widget.TextInputEditText
                    android:layout_width="fill_parent"
                    android:layout_height="@dimen/edit_text_height"
                    android:textAllCaps="true"
                    android:inputType="textCapCharacters"
                    />

Change drawable color programmatically

Syntax

"your image name".setColorFilter("your context".getResources().getColor("color name"));

Example

myImage.setColorFilter(mContext.getResources().getColor(R.color.deep_blue_new));

How to append new data onto a new line

All answers seem to work fine. If you need to do this many times, be aware that writing

hs.write(name + "\n")

constructs a new string in memory and appends that to the file.

More efficient would be

hs.write(name)
hs.write("\n")

which does not create a new string, just appends to the file.

iptables v1.4.14: can't initialize iptables table `nat': Table does not exist (do you need to insmod?)

iptalbes tool relies on a kernel module interacting with netfilter to control network traffic.

This error happens while iptalbes cannot found that module in kernel, so iptables suggest you to upgrade it :)

Perhaps iptables or your kernel needs to be upgraded.

However in most cases it's just the module not added to kernel or being banned, try this command to check whether be banned:

cd /etc/modprobe.d/ && grep -nr iptable_nat

if the command shows any rule matched, such as blacklist iptable_nat or install iptable_nat /bin/true, delete it. Since iptalbes will cost some performance, it's not strange to ban it while not necessary.

If nothing found in blacklist, try add iptable-nat to the kernal manual:

modprobe iptable-nat

If all of above not works, you can consider really upgrade your kernal...

Is JavaScript's "new" keyword considered harmful?

Javascript being dynamic language there a zillion ways to mess up where another language would stop you.

Avoiding a fundamental language feature such as new on the basis that you might mess up is a bit like removing your shiny new shoes before walking through a minefield just in case you might get your shoes muddy.

I use a convention where function names begin with a lower case letter and 'functions' that are actually class definitions begin with a upper case letter. The result is a really quite compelling visual clue that the 'syntax' is wrong:-

var o = MyClass();  // this is clearly wrong.

On top of this good naming habits help. After all functions do things and therefore there should be a verb in its name whereas classes represent objects and are nouns and adjectives with no verb.

var o = chair() // Executing chair is daft.
var o = createChair() // makes sense.

Its interesting how SO's syntax colouring has interpretted the code above.

Read and write into a file using VBScript

Find more about the FileSystemObject object at http://msdn.microsoft.com/en-us/library/aa242706(v=vs.60).aspx. For good VBScript, I recommend:

  • Option Explicit to help detect typos in variables.
  • Function and Sub to improve readilbity and reuse
  • Const so that well known constants are given names

Here's some code to read and write text to a text file:

Option Explicit

Const fsoForReading = 1
Const fsoForWriting = 2

Function LoadStringFromFile(filename)
    Dim fso, f
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set f = fso.OpenTextFile(filename, fsoForReading)
    LoadStringFromFile = f.ReadAll
    f.Close
End Function

Sub SaveStringToFile(filename, text)
    Dim fso, f
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set f = fso.OpenTextFile(filename, fsoForWriting)
    f.Write text
    f.Close
End Sub

SaveStringToFile "f.txt", "Hello World" & vbCrLf
MsgBox LoadStringFromFile("f.txt")

Selenium WebDriver and DropDown Boxes

Try the following:

import org.openqa.selenium.support.ui.Select;

Select droplist = new Select(driver.findElement(By.Id("selection")));   
droplist.selectByVisibleText("Germany");

Resolving tree conflict

What you can do to resolve your conflict is

svn resolve --accept working -R <path>

where <path> is where you have your conflict (can be the root of your repo).

Explanations:

  • resolve asks svn to resolve the conflict
  • accept working specifies to keep your working files
  • -R stands for recursive

Hope this helps.

EDIT:

To sum up what was said in the comments below:

  • <path> should be the directory in conflict (C:\DevBranch\ in the case of the OP)
  • it's likely that the origin of the conflict is
    • either the use of the svn switch command
    • or having checked the Switch working copy to new branch/tag option at branch creation
  • more information about conflicts can be found in the dedicated section of Tortoise's documentation.
  • to be able to run the command, you should have the CLI tools installed together with Tortoise:

Command line client tools

How to do a for loop in windows command line?

The commandline interpreter does indeed have a FOR construct that you can use from the command prompt or from within a batch file.

For your purpose, you probably want something like:

FOR %i IN (*.ext) DO my-function %i

Which will result in the name of each file with extension *.ext in the current directory being passed to my-function (which could, for example, be another .bat file).

The (*.ext) part is the "filespec", and is pretty flexible with how you specify sets of files. For example, you could do:

FOR %i IN (C:\Some\Other\Dir\*.ext) DO my-function %i

To perform an operation in a different directory.

There are scores of options for the filespec and FOR in general. See

HELP FOR

from the command prompt for more information.

Python 2.7 getting user input and manipulating as string without quotations

We can use the raw_input() function in Python 2 and the input() function in Python 3. By default the input function takes an input in string format. For other data type you have to cast the user input.

In Python 2 we use the raw_input() function. It waits for the user to type some input and press return and we need to store the value in a variable by casting as our desire data type. Be careful when using type casting

x = raw_input("Enter a number: ") #String input

x = int(raw_input("Enter a number: ")) #integer input

x = float(raw_input("Enter a float number: ")) #float input

x = eval(raw_input("Enter a float number: ")) #eval input

In Python 3 we use the input() function which returns a user input value.

x = input("Enter a number: ") #String input

If you enter a string, int, float, eval it will take as string input

x = int(input("Enter a number: ")) #integer input

If you enter a string for int cast ValueError: invalid literal for int() with base 10:

x = float(input("Enter a float number: ")) #float input

If you enter a string for float cast ValueError: could not convert string to float

x = eval(input("Enter a float number: ")) #eval input

If you enter a string for eval cast NameError: name ' ' is not defined Those error also applicable for Python 2.

Installing Python library from WHL file

From How do I install a Python package with a .whl file? [sic], How do I install a Python package USING a .whl file ?

For all Windows platforms:

1) Download the .WHL package install file.

2) Make Sure path [C:\Progra~1\Python27\Scripts] is in the system PATH string. This is for using both [pip.exe] and [easy-install.exe].

3) Make sure the latest version of pip.EXE is now installed. At this time of posting:

pip.EXE --version

  pip 9.0.1 from C:\PROGRA~1\Python27\lib\site-packages (python 2.7)

4) Run pip.EXE in an Admin command shell.

 - Open an Admin privileged command shell.

 > easy_install.EXE --upgrade  pip

 - Check the pip.EXE version:
 > pip.EXE --version

 pip 9.0.1 from C:\PROGRA~1\Python27\lib\site-packages (python 2.7)

 > pip.EXE install --use-wheel --no-index 
     --find-links="X:\path to wheel file\DownloadedWheelFile.whl"

Be sure to double-quote paths or path\filenames with embedded spaces in them ! Alternatively, use the MSW 'short' paths and filenames.

Why does pycharm propose to change method to static

PyCharm "thinks" that you might have wanted to have a static method, but you forgot to declare it to be static (using the @staticmethod decorator).

PyCharm proposes this because the method does not use self in its body and hence does not actually change the class instance. Hence the method could be static, i.e. callable without passing a class instance or without even having created a class instance.

Split string in JavaScript and detect line break

In case you need to split a string from your JSON, the string has the \n special character replaced with \\n.

Split string by newline:

Result.split('\n');

Split string received in JSON, where special character \n was replaced with \\n during JSON.stringify(in javascript) or json.json_encode(in PHP). So, if you have your string in a AJAX response, it was processed for transportation. and if it is not decoded, it will sill have the \n replaced with \\n** and you need to use:

Result.split('\\n');

Note that the debugger tools from your browser might not show this aspect as you was expecting, but you can see that splitting by \\n resulted in 2 entries as I need in my case: enter image description here

How to read PDF files using Java?

PDFBox is the best library I've found for this purpose, it's comprehensive and really quite easy to use if you're just doing basic text extraction. Examples can be found here.

It explains it on the page, but one thing to watch out for is that the start and end indexes when using setStartPage() and setEndPage() are both inclusive. I skipped over that explanation first time round and then it took me a while to realise why I was getting more than one page back with each call!

Itext is another alternative that also works with C#, though I've personally never used it. It's more low level than PDFBox, so less suited to the job if all you need is basic text extraction.

Stop embedded youtube iframe?

You may want to review through the Youtube JavaScript API Reference docs.

When you embed your video(s) on the page, you will need to pass this parameter:

http://www.youtube.com/v/VIDEO_ID?version=3&enablejsapi=1

If you want a stop all videos button, you can setup a javascript routine to loop through your videos and stop them:

player.stopVideo()

This does involve keeping track of all the page IDs for each video on the page. Even simpler might be to make a class and then use jQuery.each.

$('#myStopClickButton').click(function(){
  $('.myVideoClass').each(function(){
    $(this).stopVideo();
  });
});

MongoDB: Is it possible to make a case-insensitive query?

If you need to create the regexp from a variable, this is a much better way to do it: https://stackoverflow.com/a/10728069/309514

You can then do something like:

var string = "SomeStringToFind";
var regex = new RegExp(["^", string, "$"].join(""), "i");
// Creates a regex of: /^SomeStringToFind$/i
db.stuff.find( { foo: regex } );

This has the benefit be being more programmatic or you can get a performance boost by compiling it ahead of time if you're reusing it a lot.

Pretty printing XML with javascript

If you are looking for a JavaScript solution just take the code from the Pretty Diff tool at http://prettydiff.com/?m=beautify

You can also send files to the tool using the s parameter, such as: http://prettydiff.com/?m=beautify&s=https://stackoverflow.com/

Running code in main thread from another thread

public void mainWork() {
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            //Add Your Code Here
        }
    });
}

This can also work in a service class with no issue.

Using a Glyphicon as an LI bullet point (Bootstrap 3)

I'm using a simplyfied version (just using position relative) based on @SimonEast answer:

li:before {
    content: "\e080";
    font-family: 'Glyphicons Halflings';
    font-size: 9px;
    position: relative;
    margin-right: 10px;
    top: 3px;
    color: #ccc;
}

Remove the last line from a file in Bash

awk 'NR>1{print buf}{buf = $0}'

Essentially, this code says the following:

For each line after the first, print the buffered line

for each line, reset the buffer

The buffer is lagged by one line, hence you end up printing lines 1 to n-1

Recommended method for escaping HTML in Java

Be careful with this. There are a number of different 'contexts' within an HTML document: Inside an element, quoted attribute value, unquoted attribute value, URL attribute, javascript, CSS, etc... You'll need to use a different encoding method for each of these to prevent Cross-Site Scripting (XSS). Check the OWASP XSS Prevention Cheat Sheet for details on each of these contexts. You can find escaping methods for each of these contexts in the OWASP ESAPI library -- https://github.com/ESAPI/esapi-java-legacy.

How can I create a unique constraint on my column (SQL Server 2008 R2)?

One thing not clearly covered is that microsoft sql is creating in the background an unique index for the added constraint

create table Customer ( id int primary key identity (1,1) , name nvarchar(128) ) 

--Commands completed successfully.

sp_help Customer

---> index
--index_name    index_description   index_keys
--PK__Customer__3213E83FCC4A1DFA    clustered, unique, primary key located on PRIMARY   id

---> constraint
--constraint_type   constraint_name delete_action   update_action   status_enabled  status_for_replication  constraint_keys
--PRIMARY KEY (clustered)   PK__Customer__3213E83FCC4A1DFA  (n/a)   (n/a)   (n/a)   (n/a)   id


---- now adding the unique constraint

ALTER TABLE Customer ADD CONSTRAINT U_Name UNIQUE(Name)

-- Commands completed successfully.

sp_help Customer

---> index
---index_name   index_description   index_keys
---PK__Customer__3213E83FCC4A1DFA   clustered, unique, primary key located on PRIMARY   id
---U_Name   nonclustered, unique, unique key located on PRIMARY name

---> constraint
---constraint_type  constraint_name delete_action   update_action   status_enabled  status_for_replication  constraint_keys
---PRIMARY KEY (clustered)  PK__Customer__3213E83FCC4A1DFA  (n/a)   (n/a)   (n/a)   (n/a)   id
---UNIQUE (non-clustered)   U_Name  (n/a)   (n/a)   (n/a)   (n/a)   name

as you can see , there is a new constraint and a new index U_Name

Generate JSON string from NSDictionary in iOS

To convert a NSDictionary to a NSString:

NSError * err;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:myDictionary options:0 error:&err]; 
NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

How to create a DataFrame of random integers with Pandas?

The recommended way to create random integers with NumPy these days is to use numpy.random.Generator.integers. (documentation)

import numpy as np
import pandas as pd

rng = np.random.default_rng()
df = pd.DataFrame(rng.integers(0, 100, size=(100, 4)), columns=list('ABCD'))
df
----------------------
      A    B    C    D
 0   58   96   82   24
 1   21    3   35   36
 2   67   79   22   78
 3   81   65   77   94
 4   73    6   70   96
... ...  ...  ...  ...
95   76   32   28   51
96   33   68   54   77
97   76   43   57   43
98   34   64   12   57
99   81   77   32   50
100 rows × 4 columns

Cast Object to Generic Type for returning

I stumble upon this question and it grabbed my interest. The accepted answer is completely correct, but I thought I do provide my findings at JVM byte code level to explain why the OP encounter the ClassCastException.

I have the code which is pretty much the same as OP's code:

public static <T> T convertInstanceOfObject(Object o) {
    try {
       return (T) o;
    } catch (ClassCastException e) {
        return null;
    }
}

public static void main(String[] args) {
    String k = convertInstanceOfObject(345435.34);
    System.out.println(k);
}

and the corresponding byte code is:

public static <T> T convertInstanceOfObject(java.lang.Object);
    Code:
       0: aload_0
       1: areturn
       2: astore_1
       3: aconst_null
       4: areturn
    Exception table:
       from    to  target type
           0     1     2   Class java/lang/ClassCastException

  public static void main(java.lang.String[]);
    Code:
       0: ldc2_w        #3                  // double 345435.34d
       3: invokestatic  #5                  // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
       6: invokestatic  #6                  // Method convertInstanceOfObject:(Ljava/lang/Object;)Ljava/lang/Object;
       9: checkcast     #7                  // class java/lang/String
      12: astore_1
      13: getstatic     #8                  // Field java/lang/System.out:Ljava/io/PrintStream;
      16: aload_1
      17: invokevirtual #9                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      20: return

Notice that checkcast byte code instruction happens in the main method not the convertInstanceOfObject and convertInstanceOfObject method does not have any instruction that can throw ClassCastException. Because the main method does not catch the ClassCastException hence when you execute the main method you will get a ClassCastException and not the expectation of printing null.

Now I modify the code to the accepted answer:

public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
        try {
            return clazz.cast(o);
        } catch (ClassCastException e) {
            return null;
        }
    }
    public static void main(String[] args) {
        String k = convertInstanceOfObject(345435.34, String.class);
        System.out.println(k);
    }

The corresponding byte code is:

public static <T> T convertInstanceOfObject(java.lang.Object, java.lang.Class<T>);
    Code:
       0: aload_1
       1: aload_0
       2: invokevirtual #2                  // Method java/lang/Class.cast:(Ljava/lang/Object;)Ljava/lang/Object;
       5: areturn
       6: astore_2
       7: aconst_null
       8: areturn
    Exception table:
       from    to  target type
           0     5     6   Class java/lang/ClassCastException

  public static void main(java.lang.String[]);
    Code:
       0: ldc2_w        #4                  // double 345435.34d
       3: invokestatic  #6                  // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
       6: ldc           #7                  // class java/lang/String
       8: invokestatic  #8                  // Method convertInstanceOfObject:(Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Object;
      11: checkcast     #7                  // class java/lang/String
      14: astore_1
      15: getstatic     #9                  // Field java/lang/System.out:Ljava/io/PrintStream;
      18: aload_1
      19: invokevirtual #10                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      22: return

Notice that there is an invokevirtual instruction in the convertInstanceOfObject method that calls Class.cast() method which throws ClassCastException which will be catch by the catch(ClassCastException e) bock and return null; hence, "null" is printed to console without any exception.

Convert list of ASCII codes to string (byte array) in Python

I much prefer the array module to the struct module for this kind of tasks (ones involving sequences of homogeneous values):

>>> import array
>>> array.array('B', [17, 24, 121, 1, 12, 222, 34, 76]).tostring()
'\x11\x18y\x01\x0c\xde"L'

no len call, no string manipulation needed, etc -- fast, simple, direct, why prefer any other approach?!

Capture iframe load complete event

There is another consistent way (only for IE9+) in vanilla JavaScript for this:

const iframe = document.getElementById('iframe');
const handleLoad = () => console.log('loaded');

iframe.addEventListener('load', handleLoad, true)

And if you're interested in Observables this does the trick:

return Observable.fromEventPattern(
  handler => iframe.addEventListener('load', handler, true),
  handler => iframe.removeEventListener('load', handler)
);

How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue?

I was sending console log data from one tab to another and did not really needed the first console. However the error message did bug me so I right clicked and selected "don't show messages from x website". Maybe this is the easiest fix:)

Spark RDD to DataFrame python

See,

There are two ways to convert an RDD to DF in Spark.

toDF() and createDataFrame(rdd, schema)

I will show you how you can do that dynamically.

toDF()

The toDF() command gives you the way to convert an RDD[Row] to a Dataframe. The point is, the object Row() can receive a **kwargs argument. So, there is an easy way to do that.

from pyspark.sql.types import Row

#here you are going to create a function
def f(x):
    d = {}
    for i in range(len(x)):
        d[str(i)] = x[i]
    return d

#Now populate that
df = rdd.map(lambda x: Row(**f(x))).toDF()

This way you are going to be able to create a dataframe dynamically.

createDataFrame(rdd, schema)

Other way to do that is creating a dynamic schema. How?

This way:

from pyspark.sql.types import StructType
from pyspark.sql.types import StructField
from pyspark.sql.types import StringType

schema = StructType([StructField(str(i), StringType(), True) for i in range(32)])

df = sqlContext.createDataFrame(rdd, schema)

This second way is cleaner to do that...

So this is how you can create dataframes dynamically.

How do I get a string format of the current date time, in python?

>>> import datetime
>>> now = datetime.datetime.now()
>>> now.strftime("%B %d, %Y")
'July 23, 2010'

Implements vs extends: When to use? What's the difference?

Both keywords are used when creating your own new class in the Java language.

Difference: implements means you are using the elements of a Java Interface in your class. extends means that you are creating a subclass of the base class you are extending. You can only extend one class in your child class, but you can implement as many interfaces as you would like.

Refer to oracle documentation page on interface for more details.

This can help to clarify what an interface is, and the conventions around using them.

Uncaught TypeError: Cannot read property 'split' of undefined

ogdate is itself a string, why are you trying to access it's value property that it doesn't have ?

console.log(og_date.split('-'));

JSFiddle

Define global variable with webpack

There are several way to approach globals:

  1. Put your variables in a module.

Webpack evaluates modules only once, so your instance remains global and carries changes through from module to module. So if you create something like a globals.js and export an object of all your globals then you can import './globals' and read/write to these globals. You can import into one module, make changes to the object from a function and import into another module and read those changes in a function. Also remember the order things happen. Webpack will first take all the imports and load them up in order starting in your entry.js. Then it will execute entry.js. So where you read/write to globals is important. Is it from the root scope of a module or in a function called later?

config.js

export default {
    FOO: 'bar'
}

somefile.js

import CONFIG from './config.js'
console.log(`FOO: ${CONFIG.FOO}`)

Note: If you want the instance to be new each time, then use an ES6 class. Traditionally in JS you would capitalize classes (as opposed to the lowercase for objects) like
import FooBar from './foo-bar' // <-- Usage: myFooBar = new FooBar()

  1. Webpack's ProvidePlugin

Here's how you can do it using Webpack's ProvidePlugin (which makes a module available as a variable in every module and only those modules where you actually use it). This is useful when you don't want to keep typing import Bar from 'foo' again and again. Or you can bring in a package like jQuery or lodash as global here (although you might take a look at Webpack's Externals).

Step 1) Create any module. For example, a global set of utilities would be handy:

utils.js

export function sayHello () {
  console.log('hello')
}

Step 2) Alias the module and add to ProvidePlugin:

webpack.config.js

var webpack = require("webpack");
var path = require("path");

// ...

module.exports = {

  // ...

  resolve: {
    extensions: ['', '.js'],
    alias: {
      'utils': path.resolve(__dirname, './utils')  // <-- When you build or restart dev-server, you'll get an error if the path to your utils.js file is incorrect.
    }
  },

  plugins: [

    // ...

    new webpack.ProvidePlugin({
      'utils': 'utils'
    })
  ]  

}

Now just call utils.sayHello() in any js file and it should work. Make sure you restart your dev-server if you are using that with Webpack.

Note: Don't forget to tell your linter about the global, so it won't complain. For example, see my answer for ESLint here.

  1. Use Webpack's DefinePlugin

If you just want to use const with string values for your globals, then you can add this plugin to your list of Webpack plugins:

new webpack.DefinePlugin({
  PRODUCTION: JSON.stringify(true),
  VERSION: JSON.stringify("5fa3b9"),
  BROWSER_SUPPORTS_HTML5: true,
  TWO: "1+1",
  "typeof window": JSON.stringify("object")
})

Use it like:

console.log("Running App version " + VERSION);
if(!BROWSER_SUPPORTS_HTML5) require("html5shiv");
  1. Use the global window object (or Node's global)

window.foo = 'bar'  // For SPA's, browser environment.
global.foo = 'bar'  // Webpack will automatically convert this to window if your project is targeted for web (default), read more here: https://webpack.js.org/configuration/node/

You'll see this commonly used for polyfills, for example: window.Promise = Bluebird

  1. Use a package like dotenv

(For server side projects) The dotenv package will take a local configuration file (which you could add to your .gitignore if there are any keys/credentials) and adds your configuration variables to Node's process.env object.

// As early as possible in your application, require and configure dotenv.    
require('dotenv').config()

Create a .env file in the root directory of your project. Add environment-specific variables on new lines in the form of NAME=VALUE. For example:

DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3

That's it.

process.env now has the keys and values you defined in your .env file.

var db = require('db')
db.connect({
  host: process.env.DB_HOST,
  username: process.env.DB_USER,
  password: process.env.DB_PASS
})

Notes:

Regarding Webpack's Externals, use it if you want to exclude some modules from being included in your built bundle. Webpack will make the module globally available but won't put it in your bundle. This is handy for big libraries like jQuery (because tree shaking external packages doesn't work in Webpack) where you have these loaded on your page already in separate script tags (perhaps from a CDN).

Explain ExtJS 4 event handling

Just two more things I found helpful to know, even if they are not part of the question, really.

You can use the relayEvents method to tell a component to listen for certain events of another component and then fire them again as if they originate from the first component. The API docs give the example of a grid relaying the store load event. It is quite handy when writing custom components that encapsulate several sub-components.

The other way around, i.e. passing on events received by an encapsulating component mycmp to one of its sub-components subcmp, can be done like this

mycmp.on('show' function (mycmp, eOpts)
{
   mycmp.subcmp.fireEvent('show', mycmp.subcmp, eOpts);
});

How to give credentials in a batch script that copies files to a network location?

Try using the net use command in your script to map the share first, because you can provide it credentials. Then, your copy command should use those credentials.

net use \\<network-location>\<some-share> password /USER:username

Don't leave a trailing \ at the end of the

How to apply `git diff` patch without Git installed?

git diff > patchfile

and

patch -p1 < patchfile

work but as many people noticed in comments and other answers patch does not understand adds, deletes and renames. There is no option but git apply patchfile if you need handle file adds, deletes and renames.


EDIT December 2015

Latest versions of patch command (2.7, released in September 2012) support most features of the "diff --git" format, including renames and copies, permission changes, and symlink diffs (but not yet binary diffs) (release announcement).

So provided one uses current/latest version of patch there is no need to use git to be able to apply its diff as a patch.

What does DIM stand for in Visual Basic and BASIC?

It's short for Dimension, as it was originally used in BASIC to specify the size of arrays.

DIM — (short for dimension) define the size of arrays

Ref: http://en.wikipedia.org/wiki/Dartmouth_BASIC

A part of the original BASIC compiler source code, where it would jump when finding a DIM command, in which you can clearly see the original intention for the keyword:

DIM    LDA XR01             BACK OFF OBJECT POINTER
       SUB N3
       STA RX01
       LDA L        2       GET VARIABLE TO BE DIMENSIONED
       STA 3
       LDA S        3
       CAB N36              CHECK FOR $ ARRAY
       BRU *+7              NOT $
       ...

Ref: http://dtss.dartmouth.edu/scans/BASIC/BASIC%20Compiler.pdf

Later on it came to be used to declare all kinds of variables, when the possibility to specify the type for variables was added in more recent implementations.

Warning: Cannot modify header information - headers already sent by ERROR

Check something with echo, print() or printr() in the include file, header.php.

It might be that this is the problem OR if any MVC file, then check the number of spaces after ?>. This could also make a problem.

Eclipse - "Workspace in use or cannot be created, chose a different one."

for windows users: In case of you can't remove .lock file and it gives you the following:

enter image description here

And you know that eclipse is already closed, just open Task Manager then processes then end precess for all eclipse.exe occurrences in the processes list.

How can I hide/show a div when a button is clicked?

You can do this entirely with html and css and i have.


HTML First you give the div you wish to hide an ID to target like #view_element and a class to target like #hide_element. You can if you wish make both of these classes but i don't know if you can make them both IDs. Then have your Show button target your show id and your Hide button target your hide class. That is it for the html the hiding and showing is done in the CSS.

CSS The css to show and hide this should look something like this

#hide_element:target {
    display:none;
}

.show_element:target{
    display:block;
}

This should allow you to hide and show elements at will. This should work nicely on spans and divs.

how to get the selected index of a drop down

$("select[name='CCards'] option:selected") should do the trick

See jQuery documentation for more detail: http://api.jquery.com/selected-selector/

UPDATE: if you need the index of the selected option, you need to use the .index() jquery method:

$("select[name='CCards'] option:selected").index()

How to overcome "datetime.datetime not JSON serializable"?

I got the same error message while writing the serialize decorator inside a Class with sqlalchemy. So instead of :

Class Puppy(Base):
    ...
    @property
    def serialize(self):
        return { 'id':self.id,
                 'date_birth':self.date_birth,
                  ...
                }

I simply borrowed jgbarah's idea of using isoformat() and appended the original value with isoformat(), so that it now looks like:

                  ...
                 'date_birth':self.date_birth.isoformat(),
                  ...

C/C++ macro string concatenation

Hint: The STRINGIZE macro above is cool, but if you make a mistake and its argument isn't a macro - you had a typo in the name, or forgot to #include the header file - then the compiler will happily put the purported macro name into the string with no error.

If you intend that the argument to STRINGIZE is always a macro with a normal C value, then

#define STRINGIZE(A) ((A),STRINGIZE_NX(A))

will expand it once and check it for validity, discard that, and then expand it again into a string.

It took me a while to figure out why STRINGIZE(ENOENT) was ending up as "ENOENT" instead of "2"... I hadn't included errno.h.

Enable binary mode while restoring a Database from an SQL dump

May be your dump.sql is having garbage character in beginning of your file or there is a blank line in beginning.

Easy way to turn JavaScript array into comma-separated list?

const arr = [1, 2, 3];
console.log(`${arr}`)

CodeIgniter: How to get Controller, Action, URL information

$this->router->fetch_class(); 

// fecth class the class in controller $this->router->fetch_method();

// method

'dict' object has no attribute 'has_key'

In python3, has_key(key) is replaced by __contains__(key)

Tested in python3.7:

a = {'a':1, 'b':2, 'c':3}
print(a.__contains__('a'))

Docker: "no matching manifest for windows/amd64 in the manifest list entries"

For me, it is because of access denied to C:\ProgramData\Docker\config\daemon.json After I fixed it now it works. You can try to switch to Linux containers and switch back. If there is no problem with the switching, then it works with the access permission.

How to get directory size in PHP

PHP get directory size (with FTP access)

After hard work, this code works great!!!! and I want to share with the community (by MundialSYS)

function dirFTPSize($ftpStream, $dir) {
    $size = 0;
    $files = ftp_nlist($ftpStream, $dir);

    foreach ($files as $remoteFile) {
        if(preg_match('/.*\/\.\.$/', $remoteFile) || preg_match('/.*\/\.$/', $remoteFile)){
            continue;
        }
        $sizeTemp = ftp_size($ftpStream, $remoteFile);
        if ($sizeTemp > 0) {
            $size += $sizeTemp;
        }elseif($sizeTemp == -1){//directorio
            $size += dirFTPSize($ftpStream, $remoteFile);
        }
    }

    return $size;
}

$hostname = '127.0.0.1'; // or 'ftp.domain.com'
$username = 'username';
$password = 'password';
$startdir = '/public_html'; // absolute path
$files = array();
$ftpStream = ftp_connect($hostname);
$login = ftp_login($ftpStream, $username, $password);
if (!$ftpStream) {
    echo 'Wrong server!';
    exit;
} else if (!$login) {
    echo 'Wrong username/password!';
    exit;
} else {
    $size = dirFTPSize($ftpStream, $startdir);
}

echo number_format(($size / 1024 / 1024), 2, '.', '') . ' MB';

ftp_close($ftpStream);

Good code! Fernando

Jest spyOn function called

You're almost there. Although I agree with @Alex Young answer about using props for that, you simply need a reference to the instance before trying to spy on the method.

describe('my sweet test', () => {
 it('clicks it', () => {
    const app = shallow(<App />)
    const instance = app.instance()
    const spy = jest.spyOn(instance, 'myClickFunc')

    instance.forceUpdate();    

    const p = app.find('.App-intro')
    p.simulate('click')
    expect(spy).toHaveBeenCalled()
 })
})

Docs: http://airbnb.io/enzyme/docs/api/ShallowWrapper/instance.html

css display table cell requires percentage width

Note also that vertical-align:top; is often necessary for correct table cell appearance.

css table-cell, contents have unnecessary top margin

Import CSV to SQLite

How to import csv file to sqlite3

  1. Create database

    sqlite3 NYC.db
    
  2. Set the mode & tablename

    .mode csv tripdata
    
  3. Import the csv file data to sqlite3

    .import yellow_tripdata_2017-01.csv tripdata
    
  4. Find tables

    .tables
    
  5. Find your table schema

    .schema tripdata
    
  6. Find table data

    select * from tripdata limit 10;
    
  7. Count the number of rows in the table

    select count (*) from tripdata;
    

Checking if a variable is initialized

By default, no you can't know if a variable (or pointer) has or hasn't been initialized. However, since everyone else is telling you the "easy" or "normal" approach, I'll give you something else to think about. Here's how you could keep track of something like that (no, I personally would never do this, but perhaps you have different needs than me).

class MyVeryCoolInteger
{
public:
    MyVeryCoolInteger() : m_initialized(false) {}

    MyVeryCoolInteger& operator=(const int integer)
    {
        m_initialized = true;
        m_int = integer;
        return *this;
    }

    int value()
    {
        return m_int;
    }

    bool isInitialized()
    {
        return m_initialized;
    }

private:
    int m_int;
    bool m_initialized;
};

When to use the JavaScript MIME type application/javascript instead of text/javascript?

The problem with Javascript's MIME type is that there hasn't been a standard for years. Now we've got application/javascript as an official MIME type.

But actually, the MIME type doesn't matter at all, as the browser can determine the type itself. That's why the HTML5 specs state that the type="text/javascript" is no longer required.

Mocking HttpClient in unit tests

As also mentioned in the comments you need to abstract away the HttpClient so as not to be coupled to it. I've done something similar in the past. I'll try to adapt what I did with what you are trying to do.

First look at the HttpClient class and decided on what functionality it provided that would be needed.

Here is a possibility:

public interface IHttpClient {
    System.Threading.Tasks.Task<T> DeleteAsync<T>(string uri) where T : class;
    System.Threading.Tasks.Task<T> DeleteAsync<T>(Uri uri) where T : class;
    System.Threading.Tasks.Task<T> GetAsync<T>(string uri) where T : class;
    System.Threading.Tasks.Task<T> GetAsync<T>(Uri uri) where T : class;
    System.Threading.Tasks.Task<T> PostAsync<T>(string uri, object package);
    System.Threading.Tasks.Task<T> PostAsync<T>(Uri uri, object package);
    System.Threading.Tasks.Task<T> PutAsync<T>(string uri, object package);
    System.Threading.Tasks.Task<T> PutAsync<T>(Uri uri, object package);
}

Again as stated before this was for particular purposes. I completely abstracted away most dependencies to anything dealing with HttpClient and focused on what I wanted returned. You should evaluate how you want to abstract the HttpClient to provide only the necessary functionality you want.

This will now allow you to mock only what is needed to be tested.

I would even recommend doing away with IHttpHandler completely and use the HttpClient abstraction IHttpClient. But I'm just not picking as you can replace the body of your handler interface with the members of the abstracted client.

An implementation of the IHttpClient can then be used to wrapp/adapt a real/concrete HttpClient or any other object for that matter, that can be used to make HTTP requests as what you really wanted was a service that provided that functionality as apposed to HttpClient specifically. Using the abstraction is a clean (My opinion) and SOLID approach and can make your code more maintainable if you need to switch out the underlying client for something else as the framework changes.

Here is a snippet of how an implementation could be done.

/// <summary>
/// HTTP Client adaptor wraps a <see cref="System.Net.Http.HttpClient"/> 
/// that contains a reference to <see cref="ConfigurableMessageHandler"/>
/// </summary>
public sealed class HttpClientAdaptor : IHttpClient {
    HttpClient httpClient;

    public HttpClientAdaptor(IHttpClientFactory httpClientFactory) {
        httpClient = httpClientFactory.CreateHttpClient(**Custom configurations**);
    }

    //...other code

     /// <summary>
    ///  Send a GET request to the specified Uri as an asynchronous operation.
    /// </summary>
    /// <typeparam name="T">Response type</typeparam>
    /// <param name="uri">The Uri the request is sent to</param>
    /// <returns></returns>
    public async System.Threading.Tasks.Task<T> GetAsync<T>(Uri uri) where T : class {
        var result = default(T);
        //Try to get content as T
        try {
            //send request and get the response
            var response = await httpClient.GetAsync(uri).ConfigureAwait(false);
            //if there is content in response to deserialize
            if (response.Content.Headers.ContentLength.GetValueOrDefault() > 0) {
                //get the content
                string responseBodyAsText = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                //desrialize it
                result = deserializeJsonToObject<T>(responseBodyAsText);
            }
        } catch (Exception ex) {
            Log.Error(ex);
        }
        return result;
    }

    //...other code
}

As you can see in the above example, a lot of the heavy lifting usually associated with using HttpClient is hidden behind the abstraction.

You connection class can then be inject with the abstracted client

public class Connection
{
    private IHttpClient _httpClient;

    public Connection(IHttpClient httpClient)
    {
        _httpClient = httpClient;
    }
}

Your test can then mock what is needed for your SUT

private IHttpClient _httpClient;

[TestMethod]
public void TestMockConnection()
{
    SomeModelObject model = new SomeModelObject();
    var httpClientMock = new Mock<IHttpClient>();
    httpClientMock.Setup(c => c.GetAsync<SomeModelObject>(It.IsAny<string>()))
        .Returns(() => Task.FromResult(model));

    _httpClient = httpClientMock.Object;

    var client = new Connection(_httpClient);

    // Assuming doSomething uses the client to make
    // a request for a model of type SomeModelObject
    client.doSomething();  
}

How do I count the number of rows and columns in a file using bash?

Simple row count is $(wc -l "$file"). Use $(wc -lL "$file") to show both the number of lines and the number of characters in the longest line.

Fastest way to update 120 Million records

If your int_field is indexed, remove the index before running the update. Then create your index again...

5 hours seem like a lot for 120 million recs.

Why can't I push to this bare repository?

Try this in your alice repository (before pushing):

git config push.default tracking

Or, configure it as the default for your user with git config --global ….


git push does default to the origin repository (which is normally the repository from which you cloned the current repository), but it does not default to pushing the current branch—it defaults to pushing only branches that exist in both the source repository and the destination repository.

The push.default configuration variable (see git-config(1)) controls what git push will push when it is not given any “refspec” arguments (i.e. something after a repository name). The default value gives the behavior described above.

Here are possible values for push.default:

  • nothing
    This forces you to supply a “refspec”.

  • matching (the default)
    This pushes all branches that exist in both the source repository and the destination repository.
    This is completely independent of the branch that is currently checked out.

  • upstream or tracking
    (Both values mean the same thing. The later was deprecated to avoid confusion with “remote-tracking” branches. The former was introduced in 1.7.4.2, so you will have to use the latter if you are using Git 1.7.3.1.)
    These push the current branch to the branch specified by its “upstream” configuration.

  • current
    This pushes the current branch to the branch of the same name at the destination repository.

    These last two end up being the same for common cases (e.g. working on local master which uses origin/master as its upstream), but they are different when the local branch has a different name from its “upstream” branch:

    git checkout master
    # hack, commit, hack, commit
    
    # bug report comes in, we want a fix on master without the above commits
    
    git checkout -b quickfix origin/master  # "upstream" is master on origin
    # fix, commit
    git push
    

    With push.default equal to upstream (or tracking), the push would go to origin’s master branch. When it is equal to current, the push would go to origin’s quickfix branch.

The matching setting will update bare’s master in your scenario once it has been established. To establish it, you could use git push origin master once.

However, the upstream setting (or maybe current) seems like it might be a better match for what you expect to happen, so you might want to try it:

# try it once (in Git 1.7.2 and later)
git -c push.default=upstream push

# configure it for only this repository
git config push.default upstream

# configure it for all repositories that do not override it themselves
git config --global push.default upstream

(Again, if you are still using a Git before 1.7.4.2, you will need to use tracking instead of upstream).

When to use the !important property in CSS

You use !important to override a css property.

For example, you have a control in ASP.NET and it renders a control with a background blue (in the HTML). You want to change it, and you don't have the source control so you attach a new CSS file and write the same selector and change the color and after it add !important.

Best practices is when you are branding / redesigning SharePoint sites, you use it a lot to override the default styles.

Pausing a batch file for amount of time

ping -n 11 -w 1000 127.0.0.1 > nul

Update

Beginner's mistake. Ping doesn't wait 1000 ms before or after an request, but inbetween requests. So to wait 10 seconds, you'll have to do 11 pings to have 10 'gaps' of a second inbetween.

How to create a QR code reader in a HTML5 website?

There aren't many JavaScript decoders.

There is one at http://www.webqr.com/index.html

The easiest way is to run ZXing or similar on your server. You can then POST the image and get the decoded result back in the response.

How to set up gradle and android studio to do release build?

in the latest version of android studio, you can just do:

./gradlew assembleRelease

or aR for short. This will produce an unsigned release apk. Building a signed apk can be done similarly or you can use Build -> Generate Signed Apk in Android Studio.

See the docs here

Here is my build.gradle for reference:

buildscript {
  repositories {
    mavenCentral()
  }
  dependencies {
    classpath 'com.android.tools.build:gradle:0.5.+'
  }
}
apply plugin: 'android'

dependencies {
  compile fileTree(dir: 'libs', include: '*.jar')
}

android {
compileSdkVersion 17
buildToolsVersion "17.0.0"

sourceSets {
    main {
        manifest.srcFile 'AndroidManifest.xml'
        java.srcDirs = ['src']
        resources.srcDirs = ['src']
        aidl.srcDirs = ['src']
        renderscript.srcDirs = ['src']
        res.srcDirs = ['res']
        assets.srcDirs = ['assets']
    }

    // Move the tests to tests/java, tests/res, etc...
    instrumentTest.setRoot('tests')

    // Move the build types to build-types/<type>
    // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
    // This moves them out of them default location under src/<type>/... which would
    // conflict with src/ being used by the main source set.
    // Adding new build types or product flavors should be accompanied
    // by a similar customization.
    debug.setRoot('build-types/debug')
    release.setRoot('build-types/release')

}

buildTypes {
    release {

    }
}

Live-stream video from one android phone to another over WiFi

You can check the android VLC it can stream and play video, if you want to indagate more, you can check their GIT to analyze what their do. Good luck!

How do I control how Emacs makes backup files?

Emacs backup/auto-save files can be very helpful. But these features are confusing.

Backup files

Backup files have tildes (~ or ~9~) at the end and shall be written to the user home directory. When make-backup-files is non-nil Emacs automatically creates a backup of the original file the first time the file is saved from a buffer. If you're editing a new file Emacs will create a backup the second time you save the file.

No matter how many times you save the file the backup remains unchanged. If you kill the buffer and then visit the file again, or the next time you start a new Emacs session, a new backup file will be made. The new backup reflects the file's content after reopened, or at the start of editing sessions. But an existing backup is never touched again. Therefore I find it useful to created numbered backups (see the configuration below).

To create backups explicitly use save-buffer (C-x C-s) with prefix arguments.

diff-backup and dired-diff-backup compares a file with its backup or vice versa. But there is no function to restore backup files. For example, under Windows, to restore a backup file

C:\Users\USERNAME\.emacs.d\backups\!drive_c!Users!USERNAME!.emacs.el.~7~

it has to be manually copied as

C:\Users\USERNAME\.emacs.el

Auto-save files

Auto-save files use hashmarks (#) and shall be written locally within the project directory (along with the actual files). The reason is that auto-save files are just temporary files that Emacs creates until a file is saved again (like with hurrying obedience).

  • Before the user presses C-x C-s (save-buffer) to save a file Emacs auto-saves files - based on counting keystrokes (auto-save-interval) or when you stop typing (auto-save-timeout).
  • Emacs also auto-saves whenever it crashes, including killing the Emacs job with a shell command.

When the user saves the file, the auto-saved version is deleted. But when the user exits the file without saving it, Emacs or the X session crashes, the auto-saved files still exist.

Use revert-buffer or recover-file to restore auto-save files. Note that Emacs records interrupted sessions for later recovery in files named ~/.emacs.d/auto-save-list. The recover-session function will use this information.

The preferred method to recover from an auto-saved filed is M-x revert-buffer RET. Emacs will ask either "Buffer has been auto-saved recently. Revert from auto-save file?" or "Revert buffer from file FILENAME?". In case of the latter there is no auto-save file. For example, because you have saved before typing another auto-save-intervall keystrokes, in which case Emacs had deleted the auto-save file.

Auto-save is nowadays disabled by default because it can slow down editing when connected to a slow machine, and because many files contain sensitive data.

Configuration

Here is a configuration that IMHO works best:

(defvar --backup-directory (concat user-emacs-directory "backups"))
(if (not (file-exists-p --backup-directory))
        (make-directory --backup-directory t))
(setq backup-directory-alist `(("." . ,--backup-directory)))
(setq make-backup-files t               ; backup of a file the first time it is saved.
      backup-by-copying t               ; don't clobber symlinks
      version-control t                 ; version numbers for backup files
      delete-old-versions t             ; delete excess backup files silently
      delete-by-moving-to-trash t
      kept-old-versions 6               ; oldest versions to keep when a new numbered backup is made (default: 2)
      kept-new-versions 9               ; newest versions to keep when a new numbered backup is made (default: 2)
      auto-save-default t               ; auto-save every buffer that visits a file
      auto-save-timeout 20              ; number of seconds idle time before auto-save (default: 30)
      auto-save-interval 200            ; number of keystrokes between auto-saves (default: 300)
      )

Sensitive data

Another problem is that you don't want to have Emacs spread copies of files with sensitive data. Use this mode on a per-file basis. As this is a minor mode, for my purposes I renamed it sensitive-minor-mode.

To enable it for all .vcf and .gpg files, in your .emacs use something like:

(setq auto-mode-alist
      (append
       (list
        '("\\.\\(vcf\\|gpg\\)$" . sensitive-minor-mode)
        )
       auto-mode-alist))

Alternatively, to protect only some files, like some .txt files, use a line like

// -*-mode:asciidoc; mode:sensitive-minor; fill-column:132-*-

in the file.

How to generate JAXB classes from XSD?

For Eclipse STS (3.5 at least) you don't need to install anything. Right click on schema.xsd -> Generate -> JAXB Classes. You'll have to specify the package & location in the next step and that's all, your classes should be generated. I guess all the above mentioned solutions work, but this seems by far the easiest (for STS users).

[UPDATE] Eclipse STS version 3.6 (based on Kepler) comes with the same functionality.

blah

Invoke-WebRequest, POST with parameters

This just works:

$body = @{
 "UserSessionId"="12345678"
 "OptionalEmail"="[email protected]"
} | ConvertTo-Json

$header = @{
 "Accept"="application/json"
 "connectapitoken"="97fe6ab5b1a640909551e36a071ce9ed"
 "Content-Type"="application/json"
} 

Invoke-RestMethod -Uri "http://MyServer/WSVistaWebClient/RESTService.svc/member/search" -Method 'Post' -Body $body -Headers $header | ConvertTo-HTML

Boolean operators && and ||

The shorter ones are vectorized, meaning they can return a vector, like this:

((-2:2) >= 0) & ((-2:2) <= 0)
# [1] FALSE FALSE  TRUE FALSE FALSE

The longer form evaluates left to right examining only the first element of each vector, so the above gives

((-2:2) >= 0) && ((-2:2) <= 0)
# [1] FALSE

As the help page says, this makes the longer form "appropriate for programming control-flow and [is] typically preferred in if clauses."

So you want to use the long forms only when you are certain the vectors are length one.

You should be absolutely certain your vectors are only length 1, such as in cases where they are functions that return only length 1 booleans. You want to use the short forms if the vectors are length possibly >1. So if you're not absolutely sure, you should either check first, or use the short form and then use all and any to reduce it to length one for use in control flow statements, like if.

The functions all and any are often used on the result of a vectorized comparison to see if all or any of the comparisons are true, respectively. The results from these functions are sure to be length 1 so they are appropriate for use in if clauses, while the results from the vectorized comparison are not. (Though those results would be appropriate for use in ifelse.

One final difference: the && and || only evaluate as many terms as they need to (which seems to be what is meant by short-circuiting). For example, here's a comparison using an undefined value a; if it didn't short-circuit, as & and | don't, it would give an error.

a
# Error: object 'a' not found
TRUE || a
# [1] TRUE
FALSE && a
# [1] FALSE
TRUE | a
# Error: object 'a' not found
FALSE & a
# Error: object 'a' not found

Finally, see section 8.2.17 in The R Inferno, titled "and and andand".

How to insert programmatically a new line in an Excel cell in C#?

Internally Excel uses U+000D U+000A (CR+LF, \r\n) for a line break, at least in its XML representation. I also couldn't find the value directly in a cell. It was migrated to another XML file containing shared strings. Maybe cells that contain line breaks are handled differently by the file format and your library doesn't know about this.

"for loop" with two variables?

If you really just have lock-step iteration over a range, you can do it one of several ways:

for i in range(x):
  j = i
  …
# or
for i, j in enumerate(range(x)):
  …
# or
for i, j in ((i,i) for i in range(x)):
  …

All of the above are equivalent to for i, j in zip(range(x), range(y)) if x <= y.

If you want a nested loop and you only have two iterables, just use a nested loop:

for i in range(x):
  for i in range(y):
    …

If you have more than two iterables, use itertools.product.

Finally, if you want lock-step iteration up to x and then to continue to y, you have to decide what the rest of the x values should be.

for i, j in itertools.zip_longest(range(x), range(y), fillvalue=float('nan')):
  …
# or
for i in range(min(x,y)):
  j = i
  …
for i in range(min(x,y), max(x,y)):
  j = float('nan')
  …

Can the :not() pseudo-class have multiple arguments?

Starting from CSS Selectors 4 using multiple arguments in the :not selector becomes possible (see here).

In CSS3, the :not selector only allows 1 selector as an argument. In level 4 selectors, it can take a selector list as an argument.

Example:

/* In this example, all p elements will be red, except for 
   the first child and the ones with the class special. */

p:not(:first-child, .special) {
  color: red;
}

Unfortunately, browser support is limited. For now, it only works in Safari.

Reading entire html file to String?

Here's a solution to retrieve the html of a webpage using only standard java libraries:

import java.io.*;
import java.net.*;

String urlToRead = "https://google.com";
URL url; // The URL to read
HttpURLConnection conn; // The actual connection to the web page
BufferedReader rd; // Used to read results from the web page
String line; // An individual line of the web page HTML
String result = ""; // A long string containing all the HTML
try {
 url = new URL(urlToRead);
 conn = (HttpURLConnection) url.openConnection();
 conn.setRequestMethod("GET");
 rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
 while ((line = rd.readLine()) != null) {
  result += line;
 }
 rd.close();
} catch (Exception e) {
 e.printStackTrace();
}

System.out.println(result);

SRC

pandas: to_numeric for multiple columns

df.loc[:,'col':] = df.loc[:,'col':].apply(pd.to_numeric, errors = 'coerce')

Change color of Button when Mouse is over

Try this- In this example Original color is green and mouseover color will be DarkGoldenrod

<Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Bottom" Width="50" Height="50" HorizontalContentAlignment="Left" BorderBrush="{x:Null}" Foreground="{x:Null}" Margin="50,0,0,0">
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Background" Value="Green"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Border Background="{TemplateBinding Background}">
                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Background" Value="DarkGoldenrod"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

How to select a single field for all documents in a MongoDB collection?

Apart from what people have already mentioned I am just introducing indexes to the mix.

So imagine a large collection, with let's say over 1 million documents and you have to run a query like this.

The WiredTiger Internal cache will have to keep all that data in the cache if you have to run this query on it, if not that data will be fed into the WT Internal Cache either from FS Cache or Disk before the retrieval from DB is done (in batches if being called for from a driver connected to database & given that 1 million documents are not returned in 1 go, cursor comes into play)

Covered query can be an alternative. Copying the text from docs directly.

When an index covers a query, MongoDB can both match the query conditions and return the results using only the index keys; i.e. MongoDB does not need to examine documents from the collection to return the results.

When an index covers a query, the explain result has an IXSCAN stage that is not a descendant of a FETCH stage, and in the executionStats, the totalDocsExamined is 0.

Query :  db.getCollection('qaa').find({roll_no : {$gte : 0}},{_id : 0, roll_no : 1})

Index : db.getCollection('qaa').createIndex({roll_no : 1})

If the index here is in WT Internal Cache then it would be a straight forward process to get the values. An index has impact on the write performance of the system thus this would make more sense if the reads are a plenty compared to the writes.

How to use git merge --squash?

Assume the name of the branch where you made multiple commits is called bugfix/123, and you want to squash these commits.
First, create a new branch from develop (or whatever the name of your repo is). Assume the name of the new branch is called bugfix/123_up. Checkout this branch in git bash -

  • git fetch
  • git checkout bugfix/123_up
  • git merge bugfix/123 --squash
  • git commit -m "your message"
  • git push origin bugfix/123_up

Now this branch will have only one commit with all your changes in it.

How to check if the URL contains a given string?

I like to create a boolean and then use that in a logical if.

//kick unvalidated users to the login page
var onLoginPage = (window.location.href.indexOf("login") > -1);

if (!onLoginPage) {
  console.log('redirected to login page');
  window.location = "/login";
} else {
  console.log('already on the login page');
}

How to create dynamic href in react render function?

You can use ES6 backtick syntax too

<a href={`/customer/${item._id}`} >{item.get('firstName')} {item.get('lastName')}</a>

More info on es6 template literals

Can a shell script set environment variables of the calling shell?

You could always use aliases

alias your_env='source ~/scripts/your_env.sh'

Can "git pull --all" update all my local branches?

I know this question is almost 3 years old, but I asked myself the very same question and did not found any ready made solution. So, I created a custom git command shell script my self.

Here it goes, the git-ffwd-update script does the following...

  1. it issues a git remote update to fetch the lates revs
  2. then uses git remote show to get a list of local branches that track a remote branch (e.g. branches that can be used with git pull)
  3. then it checks with git rev-list --count <REMOTE_BRANCH>..<LOCAL_BRANCH> how many commit the local branch is behind the remote (and ahead vice versa)
  4. if the local branch is 1 or more commits ahead, it can NOT be fast-forwarded and needs to be merged or rebased by hand
  5. if the local branch is 0 commits ahead and 1 or more commits behind, it can be fast-forwarded by git branch -f <LOCAL_BRANCH> -t <REMOTE_BRANCH>

the script can be called like:

$ git ffwd-update
Fetching origin
 branch bigcouch was 10 commit(s) behind of origin/bigcouch. resetting local branch to remote
 branch develop was 3 commit(s) behind of origin/develop. resetting local branch to remote
 branch master is 6 commit(s) behind and 1 commit(s) ahead of origin/master. could not be fast-forwarded

The full script, should be saved as git-ffwd-update and needs to be on the PATH.

#!/bin/bash

main() {
  REMOTES="$@";
  if [ -z "$REMOTES" ]; then
    REMOTES=$(git remote);
  fi
  REMOTES=$(echo "$REMOTES" | xargs -n1 echo)
  CLB=$(git rev-parse --abbrev-ref HEAD);
  echo "$REMOTES" | while read REMOTE; do
    git remote update $REMOTE
    git remote show $REMOTE -n \
    | awk '/merges with remote/{print $5" "$1}' \
    | while read RB LB; do
      ARB="refs/remotes/$REMOTE/$RB";
      ALB="refs/heads/$LB";
      NBEHIND=$(( $(git rev-list --count $ALB..$ARB 2>/dev/null) +0));
      NAHEAD=$(( $(git rev-list --count $ARB..$ALB 2>/dev/null) +0));
      if [ "$NBEHIND" -gt 0 ]; then
        if [ "$NAHEAD" -gt 0 ]; then
          echo " branch $LB is $NBEHIND commit(s) behind and $NAHEAD commit(s) ahead of $REMOTE/$RB. could not be fast-forwarded";
        elif [ "$LB" = "$CLB" ]; then
          echo " branch $LB was $NBEHIND commit(s) behind of $REMOTE/$RB. fast-forward merge";
          git merge -q $ARB;
        else
          echo " branch $LB was $NBEHIND commit(s) behind of $REMOTE/$RB. resetting local branch to remote";
          git branch -f $LB -t $ARB >/dev/null;
        fi
      fi
    done
  done
}

main $@