Programs & Examples On #Directory walk

Node.js: get path from the request

Combining solutions above when using express request:

let url=url.parse(req.originalUrl);
let page = url.parse(uri).path?url.parse(uri).path.match('^[^?]*')[0].split('/').slice(1)[0] : '';

this will handle all cases like

localhost/page
localhost:3000/page/
/page?item_id=1
localhost:3000/
localhost/

etc. Some examples:

> urls
[ 'http://localhost/page',
  'http://localhost:3000/page/',
  'http://localhost/page?item_id=1',
  'http://localhost/',
  'http://localhost:3000/',
  'http://localhost/',
  'http://localhost:3000/page#item_id=2',
  'http://localhost:3000/page?item_id=2#3',
  'http://localhost',
  'http://localhost:3000' ]
> urls.map(uri => url.parse(uri).path?url.parse(uri).path.match('^[^?]*')[0].split('/').slice(1)[0] : '' )
[ 'page', 'page', 'page', '', '', '', 'page', 'page', '', '' ]

Find the most popular element in int[] array

This one without maps:

public class Main {       

    public static void main(String[] args) {
        int[] a = new int[]{ 1, 2, 3, 4, 5, 6, 7, 7, 7, 7 };
        System.out.println(getMostPopularElement(a));        
    }

    private static int getMostPopularElement(int[] a) {             
        int maxElementIndex = getArrayMaximumElementIndex(a); 
        int[] b = new int[a[maxElementIndex] + 1]

        for (int i = 0; i < a.length; i++) {
            ++b[a[i]];
        }

        return getArrayMaximumElementIndex(b);
    }

    private static int getArrayMaximumElementIndex(int[] a) {
        int maxElementIndex = 0;

        for (int i = 1; i < a.length; i++) {
            if (a[i] >= a[maxElementIndex]) {
                maxElementIndex = i;
            }
        }

        return maxElementIndex;
    }      

}

You only have to change some code if your array can have elements which are < 0. And this algorithm is useful when your array items are not big numbers.

How can I read a large text file line by line using Java?

For reading a file with Java 8

package com.java.java8;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;

/**
 * The Class ReadLargeFile.
 *
 * @author Ankit Sood Apr 20, 2017
 */
public class ReadLargeFile {

    /**
     * The main method.
     *
     * @param args
     *            the arguments
     */
    public static void main(String[] args) {
        try {
            Stream<String> stream = Files.lines(Paths.get("C:\\Users\\System\\Desktop\\demoData.txt"));
            stream.forEach(System.out::println);
        }
        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

How to edit Docker container files from the host?

Here's the script I use:

#!/bin/bash
IFS=$'\n\t'
set -euox pipefail


CNAME="$1"
FILE_PATH="$2"

TMPFILE="$(mktemp)"
docker exec "$CNAME" cat "$FILE_PATH" > "$TMPFILE"
$EDITOR "$TMPFILE"
cat "$TMPFILE" | docker exec -i "$CNAME" sh -c 'cat > '"$FILE_PATH"
rm "$TMPFILE"

and the gist for when I fix it but forget to update this answer: https://gist.github.com/dmohs/b50ea4302b62ebfc4f308a20d3de4213

Including dependencies in a jar with Maven

This post may be a bit old, but I also had the same problem recently. The first solution proposed by John Stauffer is a good one, but I had some problems as I am working this spring. The spring's dependency-jars I use have some property files and xml-schemas declaration which share the same paths and names. Although these jars come from the same versions, the jar-with-dependencies maven-goal was overwriting theses file with the last file found.

In the end, the application was not able to start as the spring jars could not find the correct properties files. In this case the solution propose by Rop have solved my problem.

Also since then, the spring-boot project now exist. It has a very cool way to manage this problem by providing a maven goal which overload the package goal and provide its own class loader. See spring-boots Reference Guide

Unable to import a module that is definitely installed

I encountered this while trying to use keyring which I installed via sudo pip install keyring. As mentioned in the other answers, it's a permissions issue in my case.

What worked for me:

  1. Uninstalled keyring:
    • sudo pip uninstall keyring
  2. I used sudo's -H option and reinstalled keyring:
    • sudo -H pip install keyring

Hope this helps.

Find out how much memory is being used by an object in Python

Try this:

sys.getsizeof(object)

getsizeof() Return the size of an object in bytes. It calls the object’s __sizeof__ method and adds an additional garbage collector overhead if the object is managed by the garbage collector.

A recursive recipe

How can I do division with variables in a Linux shell?

Why not use let; I find it much easier. Here's an example you may find useful:

start=`date +%s`
# ... do something that takes a while ...
sleep 71

end=`date +%s`
let deltatime=end-start
let hours=deltatime/3600
let minutes=(deltatime/60)%60
let seconds=deltatime%60
printf "Time spent: %d:%02d:%02d\n" $hours $minutes $seconds

Another simple example - calculate number of days since 1970:

let days=$(date +%s)/86400

How do I `jsonify` a list in Flask?

If you are searching literally the way to return a JSON list in flask and you are completly sure that your variable is a list then the easy way is (where bin is a list of 1's and 0's):

   return jsonify({'ans':bin}), 201

Finally, in your client you will obtain something like

{ "ans": [ 0.0, 0.0, 1.0, 1.0, 0.0 ] }

Get an image extension from an uploaded file in Laravel

Tested in laravel 5.5

$extension = $request->file('file')->extension();

Could someone explain this for me - for (int i = 0; i < 8; i++)

for (int i = 0; i < 8; i++) {
  //code
}

In simplest terms

int i = 0;
if (i < 8) //code
i = i + 1; //i = 1
if (i < 8) //code
i = i + 1;  //i = 2
if (i < 8) //code
i = i + 1;  //i = 3
if (i < 8) //code
i = i + 1; //i = 4
if (i < 8) //code
i = i + 1; //i = 5
if (i < 8) //code
i = i + 1; //i = 6
if (i < 8) //code
i = i + 1; //i = 7
if (i < 8) //code
i = i + 1; //i = 8
if (i < 8) //code - this if won't pass

Python initializing a list of lists

The problem is that they're all the same exact list in memory. When you use the [x]*n syntax, what you get is a list of n many x objects, but they're all references to the same object. They're not distinct instances, rather, just n references to the same instance.

To make a list of 3 different lists, do this:

x = [[] for i in range(3)]

This gives you 3 separate instances of [], which is what you want

[[]]*n is similar to

l = []
x = []
for i in range(n):
    x.append(l)

While [[] for i in range(3)] is similar to:

x = []
for i in range(n):
    x.append([])   # appending a new list!

In [20]: x = [[]] * 4

In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object


In [22]: x=[[] for i in range(4)]

In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time

How to disable manual input for JQuery UI Datepicker field?

When you make the input, set it to be readonly.

<input type="text" name="datepicker" id="datepicker" readonly="readonly" />

Is Java "pass-by-reference" or "pass-by-value"?

I can't believe that nobody mentioned Barbara Liskov yet. When she designed CLU in 1974, she ran into this same terminology problem, and she invented the term call by sharing (also known as call by object-sharing and call by object) for this specific case of "call by value where the value is a reference".

Using print statements only to debug

A better way to debug the code is, by using module clrprint

It prints a color full output only when pass parameter debug=True

from clrprint import *
clrprint('ERROR:', information,clr=['r','y'], debug=True)

Export query result to .csv file in SQL Server 2008

I hope 10 years isn't too late, I used this in Windows Scheduler;

"C:\Program Files\Microsoft SQL Server\110\Tools\Binn\SQLCMD.EXE"
-S BLRREPSRVR\SQLEXPRESS -d Reporting_DB -o "C:\Reports\CHP_Gen.csv" -Q "EXEC dbo.CHP_Generation_Report" -W -w 999 -s ","

It opens sql command .exe and runs a script designed for sql command. The sql command script is very easy to use with a few google searches and trial and error. You can see that it picks a database, defines output location and executes a procedure. The procedure is just a query selecting which rows and columns to display from a table in the database.

What is the difference between HAVING and WHERE in SQL?

HAVING specifies a search condition for a group or an aggregate function used in SELECT statement.

Source

How to add custom html attributes in JSX

Consider you want to pass a custom attribute named myAttr with value myValue, this will work:

<MyComponent data-myAttr={myValue} />

Visual Studio 2010 always thinks project is out of date, but nothing has changed

Another simple solution referenced by Visual Studio Forum.

Changing configuration: menu Tools ? Options ? Projects and Solutions ? VC++ Project Settings ? Solution Explorer Mode to Show all files.

Then you can see all files in Solution Explorer.

Find the files marked by the yellow icon and remove them from the project.

It's OK.

Copying a local file from Windows to a remote server using scp

I see this post is very old, but in my search for an answer to this very question, I was unable to unearth a solution from the vast internet super highway. I, therefore, hope I can contribute and help someone as they too find themselves stumbling for an answer. This simple, natural question does not seem to be documented anywhere.

On Windows 10 Pro connecting to Windows 10 Pro, both running OpenSSH (Windows version 7.7p1, LibreSSL 2.6.5), I was able to find a solution by trial and error. Though surprisingly simple, it took a while. I found the required syntax to be

BY EXAMPLE INSTEAD OF MORE OBSCURE AND INCOMPLETE TEMPLATES:

Transferring securely from a remote system to your local system:

scp user@remotehost:\D\mySrcCode\ProjectFooBar\somefile.cpp C:\myRepo\ProjectFooBar

or going the other way around:

scp C:\myRepo\ProjectFooBar\somefile.cpp user@remotehost:\D\mySrcCode\ProjectFooBar

I also found that if spaces are in the path, the quotations should begin following the remote host name:

scp user@remotehost:"\D\My Long Folder Name\somefile.cpp" C:\myRepo\SimplerNamerBro

Also, for your particular case, I echo what Cornel says:

On Windows, use backslash, at least at conventional command console.

Kind Regards. RocketCityElectromagnetics

Run Button is Disabled in Android Studio

If you have changed jdk version then go to File->Project Structure->Select SDK Location from left bar->update JDK Location in editbar in right bar.

Creating NSData from NSString in Swift

To create not optional data I recommend using it:

let key = "1234567"
let keyData = Data(key.utf8)

Android Open External Storage directory(sdcard) for storing file

I want to open external storage directory path for saving file programatically.I tried but not getting sdcard path. How can i do this?is there any solution for this??

To store your app files in SD card, you should use File[] getExternalFilesDirs (String type) method in Context class. Generally, second returned path would be the storage path for microSD card (if any).

On my phone, second path returned was /storage/sdcard1/Android/data/your.application.package.appname/files after passing null as argument to getExternalFilesDirs (String type). But path may vary on different phones, different Android versions.

Both File getExternalStorageDirectory () and File getExternalStoragePublicDirectory (String type) in Environment class may return SD card directory or internal memory directory depending on your phone's model and Android OS version.

Because According to Official Android Guide external storage can be

removable storage media (such as an SD card) or an internal (non-removable) storage.

The Internal and External Storage terminology according to Google/official Android docs is quite different from what we think.

How to use a class object in C++ as a function parameter

At its simplest:

#include <iostream>
using namespace std;

class A {
   public:
     A( int x ) : n( x ){}
     void print() { cout << n << endl; }
   private:
     int n;
};

void func( A p ) {
   p.print();
}

int main () {
   A a;
   func ( a );
}

Of course, you should probably be using references to pass the object, but I suspect you haven't got to them yet.

How to convert .pfx file to keystore with private key?

If you work with JDK 1.5 or below the keytool utility will not have the -importkeystore option (see JDK 1.5 keytool documentation) and the solution by MikeD will be available only by transferring the .pfx on a machine with a newer JDK (1.6 or above).

Another option in JDK 1.5 or below (if you have Oracle WebLogic product), is to follow the instructions from this Oracle document: Using PFX and PEM Certificate Formats with Keystores. It describes the conversion into .pem format, how to extract certificates information from this textual format, and import it into .jks format with java utils.ImportPrivateKey utility (this is an utility included with WebLogic product).

If condition inside of map() React

There are two syntax errors in your ternary conditional:

  1. remove the keyword if. Check the correct syntax here.
  2. You are missing a parenthesis in your code. If you format it like this:

    {(this.props.schema.collectionName.length < 0 ? 
       (<Expandable></Expandable>) 
       : (<h1>hejsan</h1>) 
    )}
    

Hope this works!

Get the current date and time

Get Current DateTime

Now.ToShortDateString()
DateTime.Now
Today.Now

Converting time stamps in excel to dates

below formula worked form me in MS EXEL

=TEXT(CELL_VALUE/24/60/60/1000 + 25569,"YYYY-MM-DD HH:MM")

CELL_VALUE is timestamp in milliseconds

here is explanation for text function.

Android: how to refresh ListView contents?

I too have tried invalidate(), invalidateViews(), notifyDataSetChanged(). They all might work in some particular contexts but it did not do the job in my case.

In my case, I had to add some new rows to the list and it just does not work. Creating a new adapter solved the issue.

While debugging, I realized that the data was there but just not rendered. If invalidate() or invalidateViews() does not render (which it is supposed to), I don't know what would.

Creating a new Adapter object to refresh modified data does not seem to be a bad idea. It definitely works. The only downside could be the time consumed in allocating new memory for your adapter but that should be OK assuming the Android system is smart enough and takes care of that to keep it efficient.

If you take this out of the equation, the flow is almost same as to calling notifyDataSetChanged. In the sense, the same set of adapter functions are called in either case.

So we are not losing much but gaining a lot.

Generating UNIQUE Random Numbers within a range

I guess this is probably a non issue for most but I tried to solve it. I think I have a pretty decent solution. In case anyone else stumbles upon this issue.

function randomNums($gen, $trim, $low, $high)
{
    $results_to_gen = $gen;
    $low_range      = $low;
    $high_range     = $high;
    $trim_results_to= $trim;

    $items = array();
    $results = range( 1, $results_to_gen);
    $i = 1;

    foreach($results as $result)
    {
        $result = mt_rand( $low_range, $high_range);
        $items[] = $result;

    }


    $unique = array_unique( $items, SORT_NUMERIC);
    $countem = count( $unique);
    $unique_counted = $countem -$trim_results_to;

    $sum = array_slice($unique, $unique_counted);


    foreach ($sum as $key)
    {
        $output = $i++.' : '.$key.'<br>';
        echo $output;
    }

}

randomNums(1100, 1000 ,890000, 899999);

Can I replace groups in Java regex?

Add a third group by adding parens around .*, then replace the subsequence with "number" + m.group(2) + "1". e.g.:

String output = m.replaceFirst("number" + m.group(2) + "1");

Apache and IIS side by side (both listening to port 80) on windows2003

That's not quite true. E.g. for HTTP Windows supports URL based port sharing, allowing multiple processes to use the same IP address and Port.

Check, using jQuery, if an element is 'display:none' or block on click

another shortcut i personally prefer more than .is() or .length:

if($('.myclass:visible')[0]){
   // is visible
}else {
   // is hidden
}

Multiple maven repositories in one gradle file

In short you have to do like this

repositories {
  maven { url "http://maven.springframework.org/release" }
  maven { url "https://maven.fabric.io/public" }
}

Detail:

You need to specify each maven URL in its own curly braces. Here is what I got working with skeleton dependencies for the web services project I’m going to build up:

apply plugin: 'java'

sourceCompatibility = 1.7
version = '1.0'

repositories {
  maven { url "http://maven.springframework.org/release" }
  maven { url "http://maven.restlet.org" }
  mavenCentral()
}

dependencies {
  compile group:'org.restlet.jee', name:'org.restlet', version:'2.1.1'
  compile group:'org.restlet.jee', name:'org.restlet.ext.servlet',version.1.1'
  compile group:'org.springframework', name:'spring-web', version:'3.2.1.RELEASE'
  compile group:'org.slf4j', name:'slf4j-api', version:'1.7.2'
  compile group:'ch.qos.logback', name:'logback-core', version:'1.0.9'
  testCompile group:'junit', name:'junit', version:'4.11'
}

Blog

C++ Erase vector element by value rather than by position?

You can not do that directly. You need to use std::remove algorithm to move the element to be erased to the end of the vector and then use erase function. Something like: myVector.erase(std::remove(myVector.begin(), myVector.end(), 8), myVec.end());. See this erasing elements from vector for more details.

VB.NET - How to move to next item a For Each Loop?

When I tried Continue For it Failed, I got a compiler error. While doing this, I discovered 'Resume':

For Each I As Item In Items

    If I = x Then
       'Move to next item
       Resume Next
    End If

    'Do something

Next

Note: I am using VBA here.

Calling a function within a Class method?

example 1

class TestClass{
public function __call($name,$arg){
call_user_func($name,$arg);
}
}
class test {
     public function newTest(){

          function bigTest(){
               echo 'Big Test Here';
          }
          function smallTest(){
               echo 'Small Test Here';
          }

$obj=new TestClass;

return $obj;
     }

}
$rentry=new test;
$rentry->newTest()->bigTest();

example2

class test {
     public function newTest($method_name){

          function bigTest(){
               echo 'Big Test Here';
          }
          function smallTest(){
               echo 'Small Test Here';
          }

      if(function_exists( $method_name)){    
call_user_func($method_name);
      }
      else{
          echo 'method not exists';
      }
     }

}
$obj=new test;
$obj->newTest('bigTest')

Java array assignment (multiple values)

    public class arrayFloats {
      public static void main (String [] args){
        float [] Values = new float[3];
        float Incre = 0.1f;
        int Count = 0;

        for (Count = 0;Count<3 ;Count++ ) {
          Values [Count] = Incre + 0.0f;
          Incre += 0.1f;
          System.out.println("Values [" + Count + "] : " + Values [Count]);
        }


      }
    }

//OUTPUT:
//Values [0] : 0.1
//Values [1] : 0.2
//Values [2] : 0.3

This isn't the all and be all of assigning values to a specific array. Since I've seen the sample was 0.1 - 0.3 you could do it this way. This method is very useful if you're designing charts and graphs. You can have the x-value incremented by 0.1 until nth time.

Or you want to design some grid of some sort.

How to remove all the punctuation in a string? (Python)

This works, but there might be better solutions.

asking="hello! what's your name?"
asking = ''.join([c for c in asking if c not in ('!', '?')])
print asking

What does the symbol \0 mean in a string-literal?

char str[]= "Hello\0";

That would be 7 bytes.

In memory it'd be:

48 65 6C 6C 6F 00 00
H  e  l  l  o  \0 \0

Edit:

  • What does the \0 symbol mean in a C string?
    It's the "end" of a string. A null character. In memory, it's actually a Zero. Usually functions that handle char arrays look for this character, as this is the end of the message. I'll put an example at the end.

  • What is the length of str array? (Answered before the edit part)
    7

  • and with how much 0s it is ending?
    You array has two "spaces" with zero; str[5]=str[6]='\0'=0

Extra example:
Let's assume you have a function that prints the content of that text array. You could define it as:

char str[40];

Now, you could change the content of that array (I won't get into details on how to), so that it contains the message: "This is just a printing test" In memory, you should have something like:

54 68 69 73 20 69 73 20 6a 75 73 74 20 61 20 70 72 69 6e 74
69 6e 67 20 74 65 73 74 00 00 00 00 00 00 00 00 00 00 00 00

So you print that char array. And then you want a new message. Let's say just "Hello"

48 65 6c 6c 6f 00 73 20 6a 75 73 74 20 61 20 70 72 69 6e 74
69 6e 67 20 74 65 73 74 00 00 00 00 00 00 00 00 00 00 00 00

Notice the 00 on str[5]. That's how the print function will know how much it actually needs to send, despite the actual longitude of the vector and the whole content.

Can't fix Unsupported major.minor version 52.0 even after fixing compatibility

If you are trying to execute your program/application from the command prompt. Just make sure to restart your cmd after you have changed the JAVA_HOME var. Very simple but easily missed sometimes.

Selector on background color of TextView

Even this works.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@color/dim_orange_btn_pressed" />
    <item android:state_focused="true" android:drawable="@color/dim_orange_btn_pressed" />
    <item android:drawable="@android:color/white" />
</selector>

I added the android:drawable attribute to each item, and their values are colors.

By the way, why do they say that color is one of the attributes of selector? They don't write that android:drawable is required.

Color State List Resource

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:color="hex_color"
        android:state_pressed=["true" | "false"]
        android:state_focused=["true" | "false"]
        android:state_selected=["true" | "false"]
        android:state_checkable=["true" | "false"]
        android:state_checked=["true" | "false"]
        android:state_enabled=["true" | "false"]
        android:state_window_focused=["true" | "false"] />
</selector>

How do I create a local database inside of Microsoft SQL Server 2014?

install Local DB from following link https://www.microsoft.com/en-us/download/details.aspx?id=42299 then connect to the local db using windows authentication. (localdb)\MSSQLLocalDB

Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist

The root of my problem seemed to be selinux, which was turned on (enforcing) automatically on OS install.

I wanted my mysql in /data.

After verifying that my.cnf had:

datadir=/data/mysql

(and leaving the socket at /var/lib/mysql) I executed the command to turn off selinux for mysqld (alternative is to turn it off completely):

setsebool -P mysqld_disable_trans=1

I ran the following commands:

> chown -R mysql .
> chgrp -R mysql .
> mysql_install_db --user=mysql

I started the mysql daemon and everything worked fine after that.

How can I use MS Visual Studio for Android Development?

I suppose you can open Java files in Visual Studio and just use the command line tools directly. I don't think you'd get syntax highlighting or autocompletion though.

Eclipse is really not all that different from Visual Studio, and there are a lot of tools that are designed to make Android development more comfortable that work from within Eclipse.

Reload browser window after POST without prompting user to resend POST data

To reload opener window with all parameters (not all be sent with window.location.href method and method with form.submit() is maybe one step to late) i prefer to use window.history method.

window.opener.history.go(0);

What does Docker add to lxc-tools (the userspace LXC tools)?

Dockers use images which are build in layers. This adds a lot in terms of portability, sharing, versioning and other features. These images are very easy to port or transfer and since they are in layers, changes in subsequent versions are added in form of layers over previous layers. So, while porting many a times you don't need to port the base layers. Dockers have containers which run these images with execution environment contained, they add changes as new layers providing easy version control.

Apart from that Docker Hub is a good registry with thousands of public images, where you can find images which have OS and other softwares installed. So, you can get a pretty good head start for your application.

Python - Locating the position of a regex match in a string?

I don't think this question has been completely answered yet because all of the answers only give single match examples. The OP's question demonstrates the nuances of having 2 matches as well as a substring match which should not be reported because it is not a word/token.

To match multiple occurrences, one might do something like this:

iter = re.finditer(r"\bis\b", String)
indices = [m.start(0) for m in iter]

This would return a list of the two indices for the original string.

Ruby: Can I write multi-line string with no concatenation?

In ruby 2.0 you can now just use %

For example:

    SQL = %{
      SELECT user, name
      FROM users
      WHERE users.id = #{var}
      LIMIT #{var2}
    }

Is there any way to configure multiple registries in a single npmrc file

Not the best way but If you are using mac or linux even in windows you can set alias for different registries.

##############NPM ALIASES######################
alias npm-default='npm config set registry https://registry.npmjs.org'
alias npm-sinopia='npm config set registry http://localhost:4873/'

Bootstrap - dropdown menu not working?

putting

<script src="js/bootstrap.min.js"></script>    

file at the last after the

<script src="jq/jquery-2.1.1.min.js"></script>  solved this problem for me .

this is how i use write it now and no problem

<script src="jq/jquery-2.1.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>

Working with huge files in VIM

For huge one-liners (prints characters from 1 to 99):

cut -c 1-99 filename

Replace text inside td using jQuery having td containing other elements

Wrap your to be deleted contents within a ptag, then you can do something like this:

$(function(){
  $("td").click(function(){ console.log($("td").find("p"));
    $("td").find("p").remove();    });
});

FIDDLE DEMO: http://jsfiddle.net/y3p2F/

How to access parent Iframe from JavaScript

I would recommend using the postMessage API.

In your iframe, call:

window.parent.postMessage({message: 'Hello world'}, 'http://localhost/');

In the page you're including the iframe you can listen for events like this:

window.addEventListener('message', function(event) {
      if(event.origin === 'http://localhost/')
      {
        alert('Received message: ' + event.data.message);
      }
      else
      {
        alert('Origin not allowed!');
      }

    }, false);

By the way, it is also possible to do calls to other windows, and not only iframes.

Read more about the postMessage API on John Resigs blog here

Change SQLite database mode to read-write

This error usually happens when your database is accessed by one application already, and you're trying to access it with another application.

"End of script output before headers" error in Apache

Basing above suggestions from all, I was using xampp for running cgi scripts. Windows 8 it worked with out any changes, but Cent7.0 it was throwing errors like this as said above

AH01215: (2)No such file or directory: exec of '/opt/lampp/cgi-bin/pbsa_config.cgi' failed: /opt/lampp/cgi-bin/pbsa_config.cgi, referer: http://<>/MCB_HTML/TestBed.html

[Wed Aug 30 09:11:03.796584 2017] [cgi:error] [pid 32051] [client XX:60624] End of script output before headers: pbsa_config.cgi, referer: http://xx/MCB_HTML/TestBed.html

Try:

Disabled selinux

Given full permissions for script, but 755 will be ok

I finaly added like -w like below

#!/usr/bin/perl -w*

use CGI ':standard';
{

        print header(),
         ...
         end_html();


}

**-w** indictes enable all warnings.It started working, No idea why -w here.

Aligning a float:left div to center?

Just wrap floated elements in a <div> and give it this CSS:

.wrapper {

display: table;
margin: auto;

}

Convert seconds to HH-MM-SS with JavaScript?

For anyone using AngularJS, a simple solution is to filter the value with the date API, which converts milliseconds to a string based on the requested format. Example:

<div>Offer ends in {{ timeRemaining | date: 'HH:mm:ss' }}</div>

Note that this expects milliseconds, so you may want to multiply timeRemaining by 1000 if you are converting from seconds (as the original question was formulated).

Difference between modes a, a+, w, w+, and r+ in built-in open function?

The options are the same as for the fopen function in the C standard library:

w truncates the file, overwriting whatever was already there

a appends to the file, adding onto whatever was already there

w+ opens for reading and writing, truncating the file but also allowing you to read back what's been written to the file

a+ opens for appending and reading, allowing you both to append to the file and also read its contents

What does random.sample() method in python do?

random.sample(population, k)

It is used for randomly sampling a sample of length 'k' from a population. returns a 'k' length list of unique elements chosen from the population sequence or set

it returns a new list and leaves the original population unchanged and the resulting list is in selection order so that all sub-slices will also be valid random samples

I am putting up an example in which I am splitting a dataset randomly. It is basically a function in which you pass x_train(population) as an argument and return indices of 60% of the data as D_test.

import random

def randomly_select_70_percent_of_data_from_1_to_length(x_train):
    return random.sample(range(0, len(x_train)), int(0.6*len(x_train)))

Correct way to handle conditional styling in React

I came across this question while trying to answer the same question. McCrohan's approach with the classes array & join is solid.

Through my experience, I have been working with a lot of legacy ruby code that is being converted to React and as we build the component(s) up I find myself reaching out for both existing css classes and inline styles.

example snippet inside a component:

// if failed, progress bar is red, otherwise green 
<div
    className={`progress-bar ${failed ? failed' : ''}`}
    style={{ width: this.getPercentage() }} 
/>

Again, I find myself reaching out to legacy css code, "packaging" it with the component and moving on.

So, I really feel that it is a bit in the air as to what is "best" as that label will vary greatly depending on your project.

Android customized button; changing text color

ok very simple first go to 1. res-valuse and open colors.xml 2.copy 1 of the defined text their for example #FF4081 and change name for instance i changed to white and change its value for instance i changed to #FFFFFF for white value like this

<color name="White">#FFFFFF</color>

then inside your button add this line

 b3.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.White));

ok b3 is the name of my button so changed of the name of ur button all others will be same if u use white color if you change different color then change white to the name of your color but first you have define that color in colors.xml like i explained in pont 2

Where is body in a nodejs http.get response?

Needle module is also good, here is an example which uses needle module

var needle = require('needle');

needle.get('http://www.google.com', function(error, response) {
  if (!error && response.statusCode == 200)
    console.log(response.body);
});

What does android:layout_weight mean?

Think it that way, will be simpler

If you have 3 buttons and their weights are 1,3,1 accordingly, it will work like table in HTML

Provide 5 portions for that line: 1 portion for button 1, 3 portion for button 2 and 1 portion for button 1

Regard,

Image UriSource and Data Binding

You need to have an implementation of IValueConverter interface that converts the uri into an image. Your Convert implementation of IValueConverter will look something like this:

BitmapImage image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri(value as string);
image.EndInit();

return image;

Then you will need to use the converter in your binding:

<Image>
    <Image.Source>
        <BitmapImage UriSource="{Binding Path=ImagePath, Converter=...}" />
    </Image.Source>
</Image>

Eclipse: Syntax Error, parameterized types are only if source level is 1.5

Single answer couldn't solve my problem so I used both :

  • First right click on the error in problems tab
  • click Quick fix
  • ok
  • right click on the project
  • build path
  • configure build path
  • remove JRE library
  • add JRE library

.... tada...done... :)

How to create a self-signed certificate for a domain name for development?

To Create the new certificate for your specific domain:

Open Powershell ISE as admin, run the command:

New-SelfSignedCertificate -DnsName *.mydomain.com, localhost -CertStoreLocation cert:\LocalMachine\My

To trust the new certificate:

  • Open mmc.exe
  • Go to Console Root -> Certificates (Local Computer) -> Personal
  • Select the certificate you have created, do right click -> All Tasks -> Export and follow the export wizard to create a .pfx file
  • Go to Console Root -> Certificates -> Trusted Root Certification Authorities and import the new .pfx file

To bind the certificate to your site:

  • Open IIS Manager
  • Select your site and choose Edit Site -> Bindings in the right pane
  • Add new https binding with the correct hostname and the new certificate

$_POST not working. "Notice: Undefined index: username..."

first of all,

be sure that there is a post

if(isset($_POST['username'])) { 
    // check if the username has been set
}

second, and most importantly, sanitize the data, meaning that

$query = "SELECT password FROM users WHERE username='".$_POST['username']."'";

is deadly dangerous, instead use

$query = "SELECT password FROM users WHERE username='".mysql_real_escape_string($_POST['username'])."'";

and please research the subject sql injection

Spaces cause split in path with PowerShell

Would this do what you want?:

& "C:\Windows Services\MyService.exe"

Use &, the call operator, to invoke commands whose names or paths are stored in quoted strings and/or are referenced via variables, as in the accepted answer. Invoke-Expression is not only the wrong tool to use in this particular case, it should generally be avoided.

Redirect on select option in select box

I'd strongly suggest moving away from inline JavaScript, to something like the following:

function redirect(goto){
    var conf = confirm("Are you sure you want to go elswhere?");
    if (conf && goto != '') {
        window.location = goto;
    }
}

var selectEl = document.getElementById('redirectSelect');

selectEl.onchange = function(){
    var goto = this.value;
    redirect(goto);

};

JS Fiddle demo (404 linkrot victim).
JS Fiddle demo via Wayback Machine.
Forked JS Fiddle for current users.

In the mark-up in the JS Fiddle the first option has no value assigned, so clicking it shouldn't trigger the function to do anything, and since it's the default value clicking the select and then selecting that first default option won't trigger the change event anyway.

Update:
The latest example's (2017-08-09) redirect URLs required swapping out due to errors regarding mixed content between JS Fiddle and both domains, as well as both domains requiring 'sameorigin' for framed content. - Albert

Adjusting HttpWebRequest Connection Timeout in C#

Something I found later which helped, is the .ReadWriteTimeout property. This, in addition to the .Timeout property seemed to finally cut down on the time threads would spend trying to download from a problematic server. The default time for .ReadWriteTimeout is 5 minutes, which for my application was far too long.

So, it seems to me:

.Timeout = time spent trying to establish a connection (not including lookup time) .ReadWriteTimeout = time spent trying to read or write data after connection established

More info: HttpWebRequest.ReadWriteTimeout Property

Edit:

Per @KyleM's comment, the Timeout property is for the entire connection attempt, and reading up on it at MSDN shows:

Timeout is the number of milliseconds that a subsequent synchronous request made with the GetResponse method waits for a response, and the GetRequestStream method waits for a stream. The Timeout applies to the entire request and response, not individually to the GetRequestStream and GetResponse method calls. If the resource is not returned within the time-out period, the request throws a WebException with the Status property set to WebExceptionStatus.Timeout.

(Emphasis mine.)

Count all values in a matrix greater than a value

To count the number of values larger than x in any numpy array you can use:

n = len(matrix[matrix > x])

The boolean indexing returns an array that contains only the elements where the condition (matrix > x) is met. Then len() counts these values.

How to initialize array to 0 in C?

If you'd like to initialize the array to values other than 0, with gcc you can do:

int array[1024] = { [ 0 ... 1023 ] = -1 };

This is a GNU extension of C99 Designated Initializers. In older GCC, you may need to use -std=gnu99 to compile your code.

Check if an excel cell exists on another worksheet in a column - and return the contents of a different column

You can use following formulas.

For Excel 2007 or later:

=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")

For Excel 2003:

=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))

Note, that

  • I'm using List!A:C in VLOOKUP and returns value from column ? 3
  • I'm using 4th argument for VLOOKUP equals to FALSE, in that case VLOOKUP will only find an exact match, and the values in the first column of List!A:C do not need to be sorted (opposite to case when you're using TRUE).

How do I implement charts in Bootstrap?

Update 2018

Here's a simple example using Bootstrap 4 with ChartJs. Use an HTML5 Canvas element for the chart...

<div class="container">
    <div class="row">
        <div class="col-md-6">
            <div class="card">
                <div class="card-body">
                    <canvas id="chLine"></canvas>
                </div>
            </div>
        </div>
     </div>     
</div>

And then the appropriate JS to populate the chart...

var colors = ['#007bff','#28a745'];
var chLine = document.getElementById("chLine");
var chartData = {
  labels: ["S", "M", "T", "W", "T", "F", "S"],
  datasets: [{
    data: [589, 445, 483, 503, 689, 692, 634],
    borderColor: colors[0],
    borderWidth: 4,
    pointBackgroundColor: colors[0]
  },
  {
    data: [639, 465, 493, 478, 589, 632, 674],
    borderColor: colors[1],
    borderWidth: 4,
    pointBackgroundColor: colors[1]
  }]
};
if (chLine) {
  new Chart(chLine, {
  type: 'line',
  data: chartData,
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: false
        }
      }]
    },
    legend: {
      display: false
    }
  }
  });
}

Bootstrap 4 Charts Demo

Find nginx version?

My guess is it's not in your path.
in bash, try:
echo $PATH
and
sudo which nginx
And see if the folder containing nginx is also in your $PATH variable.
If not, either add the folder to your path environment variable, or create an alias (and put it in your .bashrc) ooor your could create a link i guess.
or sudo nginx -v if you just want that...

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

Starting the OracleServiceXXX from the services.msc worked for me in Windows.

Read data from a text file using Java

You can try FileUtils from org.apache.commons.io.FileUtils, try downloading jar from here

and you can use the following method: FileUtils.readFileToString("yourFileName");

Hope it helps you..

How can I solve the error 'TS2532: Object is possibly 'undefined'?

With the release of TypeScript 3.7, optional chaining (the ? operator) is now officially available.

As such, you can simplify your expression to the following:

const data = change?.after?.data();

You may read more about it from that version's release notes, which cover other interesting features released on that version.

Run the following to install the latest stable release of TypeScript.

npm install typescript

That being said, Optional Chaining can be used alongside Nullish Coalescing to provide a fallback value when dealing with null or undefined values

const data = change?.after?.data() ?? someOtherData();

Wpf control size to content?

I had a user control which sat on page in a free form way, not constrained by another container, and the contents within the user control would not auto size but expand to the full size of what the user control was handed.

To get the user control to simply size to its content, for height only, I placed it into a grid with on row set to auto size such as this:

<Grid Margin="0,60,10,200">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <controls1:HelpPanel x:Name="HelpInfoPanel"
                         Visibility="Visible"
                         Width="570"
                         HorizontalAlignment="Right"
                         ItemsSource="{Binding HelpItems}"
                         Background="#FF313131" />
</Grid>

Rails 4: before_filter vs. before_action

before_filter/before_action: means anything to be executed before any action executes.

Both are same. they are just alias for each other as their behavior is same.

How do I call a SQL Server stored procedure from PowerShell?

This answer was pulled from http://www.databasejournal.com/features/mssql/article.php/3683181

This same example can be used for any adhoc queries. Let us execute the stored procedure “sp_helpdb” as shown below.

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=HOME\SQLEXPRESS;Database=master;Integrated Security=True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "sp_helpdb"
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$DataSet.Tables[0]

Redirect to an external URL from controller action in Spring MVC

For external url you have to use "http://www.yahoo.com" as the redirect url.

This is explained in the redirect: prefix of Spring reference documentation.

redirect:/myapp/some/resource

will redirect relative to the current Servlet context, while a name such as

redirect:http://myhost.com/some/arbitrary/path

will redirect to an absolute URL

Python unittest - opposite of assertRaises?

Hi - I want to write a test to establish that an Exception is not raised in a given circumstance.

That's the default assumption -- exceptions are not raised.

If you say nothing else, that's assumed in every single test.

You don't have to actually write an any assertion for that.

How to check if element in groovy array/hash/collection/list?

You can also use matches with regular expression like this:

boolean bool = List.matches("(?i).*SOME STRING HERE.*")

CodeIgniter Active Record not equal

This should work (which you have tried)

$this->db->where_not_in('emailsToCampaigns.campaignId', $campaignId);

Stuck while installing Visual Studio 2015 (Update for Microsoft Windows (KB2999226))

I have the same problem today, stuck on the kb2999226 for over an hour. First, i thought it is because i am using a VM on my local machine. But decided to cancel the installation, then install kb2999226 first, then install the vs2015 community again, it works out much better, the installation move forward and progressing. thx.

How can I extract a predetermined range of lines from a text file on Unix?

sed -n '16224,16482p;16483q' filename > newfile

From the sed manual:

p - Print out the pattern space (to the standard output). This command is usually only used in conjunction with the -n command-line option.

n - If auto-print is not disabled, print the pattern space, then, regardless, replace the pattern space with the next line of input. If there is no more input then sed exits without processing any more commands.

q - Exit sed without processing any more commands or input. Note that the current pattern space is printed if auto-print is not disabled with the -n option.

and

Addresses in a sed script can be in any of the following forms:

number Specifying a line number will match only that line in the input.

An address range can be specified by specifying two addresses separated by a comma (,). An address range matches lines starting from where the first address matches, and continues until the second address matches (inclusively).

Search for an item in a Lua list

function table.find(t,value)
    if t and type(t)=="table" and value then
        for _, v in ipairs (t) do
            if v == value then
                return true;
            end
        end
        return false;
    end
    return false;
end

How to use Ajax.ActionLink?

Sure, a very similar question was asked before. Set the controller for ajax requests:

public ActionResult Show()
{
    if (Request.IsAjaxRequest()) 
    {
        return PartialView("Your_partial_view", new Model());
    }
    else 
    {
        return View();
    }
}

Set the action link as wanted:

@Ajax.ActionLink("Show", 
                 "Show", 
                 null, 
                 new AjaxOptions { HttpMethod = "GET", 
                 InsertionMode = InsertionMode.Replace, 
                 UpdateTargetId = "dialog_window_id", 
                 OnComplete = "your_js_function();" })

Note that I'm using Razor view engine, and that your AjaxOptions may vary depending on what you want. Finally display it on a modal window. The jQuery UI dialog is suggested.

Calculate median in c#

I have an histogram with the variable : group
Here how I calculate my median :

int[] group = new int[nbr]; 

// -- Fill the group with values---

// sum all data in median
int median = 0;
for (int i =0;i<nbr;i++) median += group[i];

// then divide by 2 
median = median / 2;

// find 50% first part 
for (int i = 0; i < nbr; i++)
{
   median -= group[i];
   if (median <= 0)
   {
      median = i;
      break;
   }
}

median is the group index of median

How do I negate a test with regular expressions in a bash script?

You can also put the exclamation mark inside the brackets:

if [[ ! $PATH =~ $temp ]]

but you should anchor your pattern to reduce false positives:

temp=/mnt/silo/bin
pattern="(^|:)${temp}(:|$)"
if [[ ! "${PATH}" =~ ${pattern} ]]

which looks for a match at the beginning or end with a colon before or after it (or both). I recommend using lowercase or mixed case variable names as a habit to reduce the chance of name collisions with shell variables.

Simple working Example of json.net in VB.net

In Place of using this

MsgBox(json.SelectToken("Venue").SelectToken("ID"))

You can also use

MsgBox(json.SelectToken("Venue.ID"))

TypeError : Unhashable type

A list is unhashable because its contents can change over its lifetime. You can update an item contained in the list at any time.

A list doesn't use a hash for indexing, so it isn't restricted to hashable items.

What is a practical use for a closure in JavaScript?

Yes, that is a good example of a useful closure. The call to warnUser creates the calledCount variable in its scope and returns an anonymous function which is stored in the warnForTamper variable. Because there is still a closure making use of the calledCount variable, it isn't deleted upon the function's exit, so each call to the warnForTamper() will increase the scoped variable and alert the value.

The most common issue I see on Stack Overflow is where someone wants to "delay" use of a variable that is increased upon each loop, but because the variable is scoped then each reference to the variable would be after the loop has ended, resulting in the end state of the variable:

for (var i = 0; i < someVar.length; i++)
    window.setTimeout(function () {
        alert("Value of i was "+i+" when this timer was set" )
    }, 10000);

This would result in every alert showing the same value of i, the value it was increased to when the loop ended. The solution is to create a new closure, a separate scope for the variable. This can be done using an instantly executed anonymous function, which receives the variable and stores its state as an argument:

for (var i = 0; i < someVar.length; i++)
    (function (i) {
        window.setTimeout(function () {
            alert("Value of i was " + i + " when this timer was set")
        }, 10000);
    })(i);

Why can't decimal numbers be represented exactly in binary?

There's a threshold because the meaning of the digit has gone from integer to non-integer. To represent 61, you have 6*10^1 + 1*10^0; 10^1 and 10^0 are both integers. 6.1 is 6*10^0 + 1*10^-1, but 10^-1 is 1/10, which is definitely not an integer. That's how you end up in Inexactville.

Android Studio and android.support.v4.app.Fragment: cannot resolve symbol

Do sth. modification (just to gradle sync) over app level build.gradle and sync. Again, redo what you changed in build.gradle and sync. It should fix your problem.

How to find out what is locking my tables?

For getting straight to "who is blocked/blocking" I combined/abbreviated sp_who and sp_lock into a single query which gives a nice overview of who has what object locked to what level.

--Create Procedure WhoLock
--AS
set nocount on
if object_id('tempdb..#locksummary') is not null Drop table #locksummary
if object_id('tempdb..#lock') is not null Drop table #lock
create table #lock (    spid int,    dbid int,    objId int,    indId int,    Type char(4),    resource nchar(32),    Mode char(8),    status char(6))
Insert into #lock exec sp_lock
if object_id('tempdb..#who') is not null Drop table #who
create table #who (     spid int, ecid int, status char(30),
            loginame char(128), hostname char(128),
            blk char(5), dbname char(128), cmd char(16)
            --
            , request_id INT --Needed for SQL 2008 onwards
            --
         )
Insert into #who exec sp_who
Print '-----------------------------------------'
Print 'Lock Summary for ' + @@servername  + ' (excluding tempdb):'
Print '-----------------------------------------' + Char(10)
Select     left(loginame, 28) as loginame, 
    left(db_name(dbid),128) as DB,
    left(object_name(objID),30) as object,
    max(mode) as [ToLevel],
    Count(*) as [How Many],
    Max(Case When mode= 'X' Then cmd Else null End) as [Xclusive lock for command],
    l.spid, hostname
into #LockSummary
from #lock l join #who w on l.spid= w.spid
where dbID != db_id('tempdb') and l.status='GRANT'
group by dbID, objID, l.spid, hostname, loginame

Select * from #LockSummary order by [ToLevel] Desc, [How Many] Desc, loginame, DB, object

Print '--------'
Print 'Who is blocking:'
Print '--------' + char(10)
SELECT p.spid
,convert(char(12), d.name) db_name
, program_name
, p.loginame
, convert(char(12), hostname) hostname
, cmd
, p.status
, p.blocked
, login_time
, last_batch
, p.spid
FROM      master..sysprocesses p
JOIN      master..sysdatabases d ON p.dbid =  d.dbid
WHERE     EXISTS (  SELECT 1
          FROM      master..sysprocesses p2
          WHERE     p2.blocked = p.spid )

Print '--------'
Print 'Details:'
Print '--------' + char(10)
Select     left(loginame, 30) as loginame,  l.spid,
    left(db_name(dbid),15) as DB,
    left(object_name(objID),40) as object,
    mode ,
    blk,
    l.status
from #lock l join #who w on l.spid= w.spid
where dbID != db_id('tempdb') and blk <>0
Order by mode desc, blk, loginame, dbID, objID, l.status

(For what the lock level abbreviations mean, see e.g. https://technet.microsoft.com/en-us/library/ms175519%28v=sql.105%29.aspx)

Copied from: sp_WhoLock – a T-SQL stored proc combining sp_who and sp_lock...

NB the [Xclusive lock for command] column can be misleading -- it shows the current command for that spid; but the X lock could have been triggered by an earlier command in the transaction.

grep using a character vector with multiple patterns

This should work:

grep(pattern = 'A1|A9|A6', x = myfile$Letter)

Or even more simply:

library(data.table)
myfile$Letter %like% 'A1|A9|A6'

How to print HTML content on click of a button, but not the page?

Below Code May Be Help You :

<html>
<head>
<script>
function printPage(id)
{
   var html="<html>";
   html+= document.getElementById(id).innerHTML;

   html+="</html>";

   var printWin = window.open('','','left=0,top=0,width=1,height=1,toolbar=0,scrollbars=0,status  =0');
   printWin.document.write(html);
   printWin.document.close();
   printWin.focus();
   printWin.print();
   printWin.close();
}
</script>
</head>
<body>
<div id="block1">
<table border="1" >
</tr>
<th colspan="3">Block 1</th>
</tr>
<tr>
<th>1</th><th>XYZ</th><th>athock</th>
</tr>
</table>

</div>

<div id="block2">
    This is Block 2 content
</div>

<input type="button" value="Print Block 1" onclick="printPage('block1');"></input>
<input type="button" value="Print Block 2" onclick="printPage('block2');"></input>
</body>
</html>

How to rename array keys in PHP?

You could use array_map() to do it.

$tags = array_map(function($tag) {
    return array(
        'name' => $tag['name'],
        'value' => $tag['url']
    );
}, $tags);

How to get all options in a drop-down list by Selenium WebDriver using C#?

Here is code in Java to get all options in dropdown list.

WebElement sel = myD.findElement(By.name("dropdown_name"));
List<WebElement> lists = sel.findElements(By.tagName("option"));
    for(WebElement element: lists)  
    {
        String var2 = tdElement.getText();
        System.out.println(var2);
    }

Hope it may helpful to someone.

Getting full JS autocompletion under Sublime Text

Suggestions are (basically) based on the text in the current open file and any snippets or completions you have defined (ref). If you want more text suggestions, I'd recommend:

As a side note, I'd really recommend installing Package control to take full advantage of the Sublime community. Some of the options above use Package control. I'd also highly recommend the tutsplus Sublime tutorial videos, which include all sorts of information about improving your efficiency when using Sublime.

Where to place $PATH variable assertions in zsh?

tl;dr version: use ~/.zshrc

And read the man page to understand the differences between:

~/.zshrc, ~/.zshenv and ~/.zprofile.


Regarding my comment

In my comment attached to the answer kev gave, I said:

This seems to be incorrect - /etc/profile isn't listed in any zsh documentation I can find.

This turns out to be partially incorrect: /etc/profile may be sourced by zsh. However, this only occurs if zsh is "invoked as sh or ksh"; in these compatibility modes:

The usual zsh startup/shutdown scripts are not executed. Login shells source /etc/profile followed by $HOME/.profile. If the ENV environment variable is set on invocation, $ENV is sourced after the profile scripts. The value of ENV is subjected to parameter expansion, command substitution, and arithmetic expansion before being interpreted as a pathname. [man zshall, "Compatibility"].

The ArchWiki ZSH link says:

At login, Zsh sources the following files in this order:
/etc/profile
This file is sourced by all Bourne-compatible shells upon login

This implys that /etc/profile is always read by zsh at login - I haven't got any experience with the Arch Linux project; the wiki may be correct for that distribution, but it is not generally correct. The information is incorrect compared to the zsh manual pages, and doesn't seem to apply to zsh on OS X (paths in $PATH set in /etc/profile do not make it to my zsh sessions).



To address the question:

where exactly should I be placing my rvm, python, node etc additions to my $PATH?

Generally, I would export my $PATH from ~/.zshrc, but it's worth having a read of the zshall man page, specifically the "STARTUP/SHUTDOWN FILES" section - ~/.zshrc is read for interactive shells, which may or may not suit your needs - if you want the $PATH for every zsh shell invoked by you (both interactive and not, both login and not, etc), then ~/.zshenv is a better option.

Is there a specific file I should be using (i.e. .zshenv which does not currently exist in my installation), one of the ones I am currently using, or does it even matter?

There's a bunch of files read on startup (check the linked man pages), and there's a reason for that - each file has it's particular place (settings for every user, settings for user-specific, settings for login shells, settings for every shell, etc).
Don't worry about ~/.zshenv not existing - if you need it, make it, and it will be read.

.bashrc and .bash_profile are not read by zsh, unless you explicitly source them from ~/.zshrc or similar; the syntax between bash and zsh is not always compatible. Both .bashrc and .bash_profile are designed for bash settings, not zsh settings.

Apache VirtualHost and localhost

localhost will always redirect to 127.0.0.1. You can trick this by naming your other VirtualHost to other local loop-back address, such as 127.0.0.2. Make sure you also change the corresponding hosts file to implement this.

For example, my httpd-vhosts.conf looks like this:

<VirtualHost 127.0.0.2:80>
    DocumentRoot "D:/6. App Data/XAMPP Shared/htdocs/intranet"
    ServerName intranet.dev
    ServerAlias www.intranet.dev
    ErrorLog "logs/intranet.dev-error.log"
    CustomLog "logs/intranet.dec-access.log" combined

    <Directory "D:/6. App Data/XAMPP Shared/htdocs/intranet">
        Options Indexes FollowSymLinks ExecCGI Includes
        Order allow,deny
        Allow from all
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

(Notice that in <VirtualHost> section I typed 127.0.0.2:80. It means that this block of VirtualHost will only affects requests to IP address 127.0.0.2 port 80, which is the default port for HTTP.

To route the name intranet.dev properly, my hosts entry line is like this:

127.0.0.2 intranet.dev

This way, it will prevent you from creating another VirtualHost block for localhost, which is unnecessary.

Updating records codeigniter

In your_controller write this...

public function update_title() 
{   
    $data = array
      (
        'table_id' => $this->input->post('table_id'),
        'table_title' => $this->input->post('table_title')
      );

    $this->load->model('your_model'); // First load the model
    if($this->your_model->update_title($data)) // call the method from the controller
    {
        // update successful...
    }
    else
    {
        // update not successful...
    }

}

While in your_model...

public function update_title($data)
{
   $this->db->set('table_title',$data['title'])
         ->where('table_id',$data['table_id'])
        ->update('your_table');
}

This will works fine...

Specify the date format in XMLGregorianCalendar

This is an easy way for any format. Just change it to required format string

XMLGregorianCalendar gregFmt = DatatypeFactory.newInstance().newXMLGregorianCalendar(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(new Date()));
System.out.println(gregFmt);

htaccess redirect all pages to single page

Are you trying to get visitors to old.com/about.htm to go to new.com/about.htm? If so, you can do this with a mod_rewrite rule in .htaccess:

RewriteEngine on

RewriteRule ^(.*)$ http://www.thenewdomain.com/$1 [R=permanent,L]

What is the syntax of the enhanced for loop in Java?

Enhanced for loop:

for (String element : array) {

    // rest of code handling current element
}

Traditional for loop equivalent:

for (int i=0; i < array.length; i++) {
    String element = array[i]; 

    // rest of code handling current element
}

Take a look at these forums: https://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with

http://www.java-tips.org/java-se-tips/java.lang/the-enhanced-for-loop.html

How to remove a file from the index in git?

According to my humble opinion and my work experience with git, staging area is not the same as index. I may be wrong of course, but as I said, my experience in using git and my logic tell me, that index is a structure that follows your changes to your working area(local repository) that are not excluded by ignoring settings and staging area is to keep files that are already confirmed to be committed, aka files in index on which add command was run on. You don't notice and realize that "slight" difference, because you use git commit -a -m "comment" adding indexed and cached files to stage area and committing in one command or using IDEs like IDEA for that too often. And cache is that what keeps changes in indexed files. If you want to remove file from index that has not been added to staging area before, options proposed before match for you, but... If you have done that already, you will need to use

Git restore --staged <file>

And, please, don't ask me where I was 10 years ago... I missed you, this answer is for further generations)

How to find the size of an int[]?

Assuming you merely want to know the size of an array whose type you know (int) but whose size, obviously, you don't know, it is suitable to verify whether the array is empty, otherwise you will end up with a division by zero (causing a Float point exception).

int array_size(int array[]) {
    if(sizeof(array) == 0) {
        return 0;
    }
    return sizeof(array)/sizeof(array[0]);
 }

Click button copy to clipboard using jQuery

You can use this code for copy input value in page in Clipboard by click a button

This is Html

<input type="text" value="xxx" id="link" class="span12" />
<button type="button" class="btn btn-info btn-sm" onclick="copyToClipboard('#link')">
    Copy Input Value
</button>

Then for this html , we must use this JQuery Code

function copyToClipboard(element) {
    $(element).select();
    document.execCommand("copy");
}

This is the simplest solution for this question

JavaScript seconds to time string with format hh:mm:ss

function toHHMMSS(seconds) {
    var h, m, s, result='';
    // HOURs
    h = Math.floor(seconds/3600);
    seconds -= h*3600;
    if(h){
        result = h<10 ? '0'+h+':' : h+':';
    }
    // MINUTEs
    m = Math.floor(seconds/60);
    seconds -= m*60;
    result += m<10 ? '0'+m+':' : m+':';
    // SECONDs
    s=seconds%60;
    result += s<10 ? '0'+s : s;
    return result;
}

Examples

    toHHMMSS(111); 
    "01:51"

    toHHMMSS(4444);
    "01:14:04"

    toHHMMSS(33);
    "00:33"

Python - Count elements in list

Len won't yield the total number of objects in a nested list (including multidimensional lists). If you have numpy, use size(). Otherwise use list comprehensions within recursion.

How can I make an svg scale with its parent container?

Adjusting the currentScale attribute works in IE ( I tested with IE 11), but not in Chrome.

VC++ fatal error LNK1168: cannot open filename.exe for writing

The problem is probably that you forgot to close the program and that you instead have the program running in the background.

Find the console window where the exe file program is running, and close it by clicking the X in the upper right corner. Then try to recompile the program. In my case this solved the problem.

I know this posting is old, but I am answering for the other people like me who find this through the search engines.

How do I set up Visual Studio Code to compile C++ code?

A makefile task example for new 2.0.0 tasks.json version.

In the snippet below some comments I hope they will be useful.

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "<TASK_NAME>",
            "type": "shell",
            "command": "make",
            // use options.cwd property if the Makefile is not in the project root ${workspaceRoot} dir
            "options": {
                "cwd": "${workspaceRoot}/<DIR_WITH_MAKEFILE>"
            },
            // start the build without prompting for task selection, use "group": "build" otherwise
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "presentation": {
                "echo": true,
                "reveal": "always",
                "focus": false,
                "panel": "shared"
            },
            // arg passing example: in this case is executed make QUIET=0
            "args": ["QUIET=0"],
            // Use the standard less compilation problem matcher.
            "problemMatcher": {
                "owner": "cpp",
                "fileLocation": ["absolute"],
                "pattern": {
                    "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
                    "file": 1,
                    "line": 2,
                    "column": 3,
                    "severity": 4,
                    "message": 5
                }
            }
        }
    ]
}

Get and set position with jQuery .offset()

It's doable but you have to know that using offset() sets the position of the element relative to the document:

$('.layer1').offset( $('.layer2').offset() );

Angular ForEach in Angular4/Typescript?

arrayData.forEach((key : any, val: any) => {
                        key['index'] = val + 1;

                        arrayData2.forEach((keys : any, vals :any) => {
                            if (key.group_id == keys.id) {
                                key.group_name = keys.group_name;
                            }
                        })
                    })

Set focus on textbox in WPF

Nobody explained so far why the code in the question doesn't work. My guess is that the code was placed in the constructor of the Window. But at this time it's too early to set the focus. It has to be done once the Window is ready for interaction. The best place for the code is the Loaded event:

public KonsoleWindow() {
  public TestWindow() {
    InitializeComponent();
    Loaded += TestWindow_Loaded;
  }

  private void TestWindow_Loaded(object sender, RoutedEventArgs e) {
    txtCompanyID.Focus();
  }
}

How do I read an image file using Python?

The word "read" is vague, but here is an example which reads a jpeg file using the Image class, and prints information about it.

from PIL import Image
jpgfile = Image.open("picture.jpg")

print(jpgfile.bits, jpgfile.size, jpgfile.format)

Differences between Ant and Maven

I can take a person that has never seen Ant - its build.xmls are reasonably well-written - and they can understand what is going on. I can take that same person and show them a Maven POM and they will not have any idea what is going on.

In an engineering organization that is huge, people write about Ant files becoming large and unmanageable. I've written those types and clean Ant scripts. It's really understanding upfront what you need to do going forward and designing a set of templates that can respond to change and scale over a 3+ year period.

Unless you have a simple project, learning the Maven conventions and the Maven way about getting things done is quite a bit of work.

At the end of the day you cannot consider project startup with Ant or Maven a factor: it's really the total cost of ownership. What it takes for the organization to maintain and extend its build system over a few years is one of the main factors that must be considered.

The most important aspects of a build system are dependency management and flexibility in expressing the build recipe. It must be somewhat intuitive when done well.

Convert between UIImage and Base64 string

Swift version - create base64 for image

In my opinion Implicitly Unwrapped Optional in case of UIImagePNGRepresenatation() is not safe, so I recommend to use extension like below:

extension UIImage {

    func toBase64() -> String? {
        let imageData = UIImagePNGRepresentation(self)
        return imageData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
    }
}

java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing

It sounds like a classpath issue, so there are a few different ways to go about it. Where does org/hamcret/SelfDescribing come from? Is that your class or in a different jar?

Try going to your project Build Path and on the Libraries tab, add a Library. You should be able to choose JUnit to your project. This is a little bit different than just having the JUnit jar file In your project.

In your Run Configuration for the JUnit test, check the Classpath. You could probably fix this by adding making sure your Classpath can see that SelfDescribing class there. The Run option in Eclipse has a different set of options for the JUnit options.

Can someone provide an example of a $destroy event for scopes in AngularJS?

Demo: http://jsfiddle.net/sunnycpp/u4vjR/2/

Here I have created handle-destroy directive.

ctrl.directive('handleDestroy', function() {
    return function(scope, tElement, attributes) {        
        scope.$on('$destroy', function() {
            alert("In destroy of:" + scope.todo.text);
        });
    };
});

Mapping two integers to one, in a unique and deterministic way

You're looking for a bijective NxN -> N mapping. These are used for e.g. dovetailing. Have a look at this PDF for an introduction to so-called pairing functions. Wikipedia introduces a specific pairing function, namely the Cantor pairing function:

pi(k1, k2) = 1/2(k1 + k2)(k1 + k2 + 1) + k2

Three remarks:

  • As others have made clear, if you plan to implement a pairing function, you may soon find you need arbitrarily large integers (bignums).
  • If you don't want to make a distinction between the pairs (a, b) and (b, a), then sort a and b before applying the pairing function.
  • Actually I lied. You are looking for a bijective ZxZ -> N mapping. Cantor's function only works on non-negative numbers. This is not a problem however, because it's easy to define a bijection f : Z -> N, like so:
    • f(n) = n * 2 if n >= 0
    • f(n) = -n * 2 - 1 if n < 0

What is dtype('O'), in pandas?

It means "a python object", i.e. not one of the builtin scalar types supported by numpy.

np.array([object()]).dtype
=> dtype('O')

How to remove all .svn directories from my application directories

What you wrote sends a list of newline separated file names (and paths) to rm, but rm doesn't know what to do with that input. It's only expecting command line parameters.

xargs takes input, usually separated by newlines, and places them on the command line, so adding xargs makes what you had work:

find . -name .svn | xargs rm -fr

xargs is intelligent enough that it will only pass as many arguments to rm as it can accept. Thus, if you had a million files, it might run rm 1,000,000/65,000 times (if your shell could accept 65,002 arguments on the command line {65k files + 1 for rm + 1 for -fr}).

As persons have adeptly pointed out, the following also work:

find . -name .svn -exec rm -rf {} \;
find . -depth -name .svn -exec rm -fr {} \;
find . -type d -name .svn -print0|xargs -0 rm -rf

The first two -exec forms both call rm for each folder being deleted, so if you had 1,000,000 folders, rm would be invoked 1,000,000 times. This is certainly less than ideal. Newer implementations of rm allow you to conclude the command with a + indicating that rm will accept as many arguments as possible:

find . -name .svn -exec rm -rf {} +

The last find/xargs version uses print0, which makes find generate output that uses \0 as a terminator rather than a newline. Since POSIX systems allow any character but \0 in the filename, this is truly the safest way to make sure that the arguments are correctly passed to rm or the application being executed.

In addition, there's a -execdir that will execute rm from the directory in which the file was found, rather than at the base directory and a -depth that will start depth first.

Export to CSV using MVC, C# and jQuery

Simple excel file create in mvc 4

public ActionResult results() { return File(new System.Text.UTF8Encoding().GetBytes("string data"), "application/csv", "filename.csv"); }

Best way to compare two complex objects

Serialize both objects, then calculate Hash Code, then compare.

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties

EntityFunctions is obsolete. Consider using DbFunctions instead.

var eventsCustom = eventCustomRepository.FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference)
   .Where(x => DbFunctions.TruncateTime(x.DateTimeStart) == currentDate.Date);

Update Android SDK Tool to 22.0.4(Latest Version) from 22.0.1

I faced the same issue, I tried the below solution and it worked for me In Android SDK Manager Window, click on Tools->Options-> under "Others", check "Force https://... sources to be fetched using http://..."

Disable all dialog boxes in Excel while running VB script?

From Excel Macro Security - www.excelfunctions.net:

Macro Security in Excel 2007, 2010 & 2013:

.....

The different Excel file types provided by the latest versions of Excel make it clear when workbook contains macros, so this in itself is a useful security measure. However, Excel also has optional macro security settings, which are controlled via the options menu. These are :

'Disable all macros without notification'

  • This setting does not allow any macros to run. When you open a new Excel workbook, you are not alerted to the fact that it contains macros, so you may not be aware that this is the reason a workbook does not work as expected.

'Disable all macros with notification'

  • This setting prevents macros from running. However, if there are macros in a workbook, a pop-up is displayed, to warn you that the macros exist and have been disabled.

'Disable all macros except digitally signed macros'

  • This setting only allow macros from trusted sources to run. All other macros do not run. When you open a new Excel workbook, you are not alerted to the fact that it contains macros, so you may not be aware that this is the reason a workbook does not work as expected.

'Enable all macros'

  • This setting allows all macros to run. When you open a new Excel workbook, you are not alerted to the fact that it contains macros and may not be aware of macros running while you have the file open.

If you trust the macros and are ok with enabling them, select this option:

'Enable all macros'

and this dialog box should not show up for macros.

As for the dialog for saving, after noting that this was running on Excel for Mac 2011, I came across the following question on SO, StackOverflow - Suppress dialog when using VBA to save a macro containing Excel file (.xlsm) as a non macro containing file (.xlsx). From it, removing the dialog does not seem to be possible, except for possibly by some Keyboard Input simulation. I would post another question to inquire about that. Sorry I could only get you halfway. The other option would be to use a Windows computer with Microsoft Excel, though I'm not sure if that is a option for you in this case.

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

Google throws this exception on Activity's onCreate method after v27, their meaning is : if an Activity is translucent or floating, its orientation should be relied on parent(background) Activity, can't make decision on itself.

Even if you remove android:screenOrientation="portrait" from the floating or translucent Activity but fix orientation on its parent(background) Activity, it is still fixed by the parent, I have tested already.

One special situation : if you make translucent on a launcher Activity, it has't parent(background), so always rotate with device. Want to fix it, you have to take another way to replace <item name="android:windowIsTranslucent">true</item> style.

How do I reset the setInterval timer?

If by "restart", you mean to start a new 4 second interval at this moment, then you must stop and restart the timer.

function myFn() {console.log('idle');}

var myTimer = setInterval(myFn, 4000);

// Then, later at some future time, 
// to restart a new 4 second interval starting at this exact moment in time
clearInterval(myTimer);
myTimer = setInterval(myFn, 4000);

You could also use a little timer object that offers a reset feature:

function Timer(fn, t) {
    var timerObj = setInterval(fn, t);

    this.stop = function() {
        if (timerObj) {
            clearInterval(timerObj);
            timerObj = null;
        }
        return this;
    }

    // start timer using current settings (if it's not already running)
    this.start = function() {
        if (!timerObj) {
            this.stop();
            timerObj = setInterval(fn, t);
        }
        return this;
    }

    // start with new or original interval, stop current interval
    this.reset = function(newT = t) {
        t = newT;
        return this.stop().start();
    }
}

Usage:

var timer = new Timer(function() {
    // your function here
}, 5000);


// switch interval to 10 seconds
timer.reset(10000);

// stop the timer
timer.stop();

// start the timer
timer.start();

Working demo: https://jsfiddle.net/jfriend00/t17vz506/

Functional style of Java 8's Optional.ifPresent and if-not-Present?

Supposing that you have a list and avoiding the isPresent() issue (related with optionals) you could use .iterator().hasNext() to check if not present.

VBA copy cells value and format

Following on from jpw it might be good to encapsulate his solution in a small subroutine to save on having lots of lines of code:

Private Sub CommandButton1_Click()
Dim i As Integer
Dim a As Integer
a = 15
For i = 11 To 32
  If Worksheets(1).Cells(i, 3) <> "" Then
    call copValuesAndFormat(i,3,a,15)        
    call copValuesAndFormat(i,5,a,17) 
    call copValuesAndFormat(i,6,a,18) 
    call copValuesAndFormat(i,7,a,19) 
    call copValuesAndFormat(i,8,a,20) 
    call copValuesAndFormat(i,9,a,21) 
    a = a + 1
  End If
Next i
end sub

sub copValuesAndFormat(x1 as integer, y1 as integer, x2 as integer, y2 as integer)
  Worksheets(1).Cells(x1, y1).Copy
  Worksheets(2).Cells(x2, y2).PasteSpecial Paste:=xlPasteFormats
  Worksheets(2).Cells(x2, y2).PasteSpecial Paste:=xlPasteValues
end sub

(I do not have Excel in current location so please excuse bugs as not tested)

How to make Toolbar transparent?

All you need to is to define theme which hide action bar, define action bar style with transparent background and set this style to the toolbar widget. Please note that toolbar should be drawen as last view (over all view tree)

<style name="Theme.Custom" parent="@android:style/Theme.AppCompat">
    <item name="windowActionBar">false</item>
    <item name="windowActionBarOverlay">true</item>
    <item name="android:windowActionBarOverlay">true</item>
</style>

<style name="CustomActionBar" parent="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="android:windowActionBarOverlay">true</item>
    <!-- Support library compatibility -->
    <item name="windowActionBarOverlay">true</item>
</style>

Layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- Toolbar should be above content-->
    <include layout="@layout/toolbar" />

</RelativeLayout>

Toolbar layout:

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:theme="@style/CustomActionBar"/>

How do I make a self extract and running installer

It's simple with open source 7zip SFX-Packager - easy way to just "Drag & drop" folders onto it, and it creates a portable/self-extracting package.

Creating a PHP header/footer

the simpler, the better.

index.php

<? 
if (empty($_SERVER['QUERY_STRING'])) { 
  $name="index"; 
} else { 
  $name=basename($_SERVER['QUERY_STRING']); 
} 
$file="txt/".$name.".htm"; 
if (is_readable($file)) { 
  include 'header.php';
  readfile($file);
} else { 
  header("HTTP/1.0 404 Not Found");
  exit;
} 
?>

header.php

<a href="index.php">Main page</a><br>
<a href=?about>About</a><br>
<a href=?links>Links</a><br>
<br><br> 

the actual static html pages stored in the txt folder in the page.htm format

Getting Checkbox Value in ASP.NET MVC 4

For the MVC using Model. Model:

public class UserInfo
{
    public string UserID { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public bool RememberMe { get; set; }
}

HTML:

<input type="checkbox" value="true" id="checkbox1" name="RememberMe" checked="@Model.RememberMe"/>
<label for="checkbox1"></label>

In [HttpPost] function, we can get its properties.

[HttpPost]
public ActionResult Login(UserInfo user)
{
   //...
   return View(user);
}

How to install JQ on Mac by command-line?

You can install any application/packages with brew on mac. If you want to know the exact command just search your package on https://brewinstall.org and you will get the set of commands needed to install that package.

First open terminal and install brew

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" < /dev/null 2> /dev/null

Now Install jq

brew install jq

Map a 2D array onto a 1D array

The typical formula for recalculation of 2D array indices into 1D array index is

index = indexX * arrayWidth + indexY;

Alternatively you can use

index = indexY * arrayHeight + indexX;

(assuming that arrayWidth is measured along X axis, and arrayHeight along Y axis)

Of course, one can come up with many different formulae that provide alternative unique mappings, but normally there's no need to.

In C/C++ languages built-in multidimensional arrays are stored in memory so that the last index changes the fastest, meaning that for an array declared as

int xy[10][10];

element xy[5][3] is immediately followed by xy[5][4] in memory. You might want to follow that convention as well, choosing one of the above two formulae depending on which index (X or Y) you consider to be the "last" of the two.

Python : Trying to POST form using requests

You can use the Session object

import requests
headers = {'User-Agent': 'Mozilla/5.0'}
payload = {'username':'niceusername','password':'123456'}

session = requests.Session()
session.post('https://admin.example.com/login.php',headers=headers,data=payload)
# the session instance holds the cookie. So use it to get/post later.
# e.g. session.get('https://example.com/profile')

How to hide a navigation bar from first ViewController in Swift?

In IOS 8 do it like

navigationController?.hidesBarsOnTap = true

but only when it's part of a UINavigationController

make it false when you want it back

How to replace space with comma using sed?

On Linux use below to test (it would replace the whitespaces with comma)

 sed 's/\s/,/g' /tmp/test.txt | head

later you can take the output into the file using below command:

sed 's/\s/,/g' /tmp/test.txt > /tmp/test_final.txt

PS: test is the file which you want to use

How to do a LIKE query with linq?

Try using string.Contains () combined with EndsWith.

var results = from c in db.Customers
              where c.FullName.Contains (FirstName) && c.FullName.EndsWith (LastName)
              select c;

How to commit changes to a new branch

If I understand right, you've made a commit to changed_branch and you want to copy that commit to other_branch? Easy:

git checkout other_branch
git cherry-pick changed_branch

How to add a hook to the application context initialization event?

Since Spring 4.2 you can use @EventListener (documentation)

@Component
class MyClassWithEventListeners {

    @EventListener({ContextRefreshedEvent.class})
    void contextRefreshedEvent() {
        System.out.println("a context refreshed event happened");
    }
}

How to disable back swipe gesture in UINavigationController on iOS 7

It worked for me for most of the viewcontrollers.

self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false

It wasn't not working for some viewcontrollers like UIPageViewController. On UIPageViewController's pagecontentviewcontroller below code worked for me.

override func viewDidLoad() {
   self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
   self.navigationController?.interactivePopGestureRecognizer?.delegate = self
}
override func viewWillDisappear(_ animated: Bool) {
   self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
   self.navigationController?.interactivePopGestureRecognizer?.delegate = nil
}

On UIGestureRecognizerDelegate,

func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
   if gestureRecognizer == self.navigationController?.interactivePopGestureRecognizer {
      return false
}
      return true
}

ImportError: No module named sqlalchemy

Probably a stupid mistake; but, I experienced this problem and the issue turned out to be that "pip3 install sqlalchemy" installs libraries in user specific directories.

On my Linux machine, I was logged in as user1 executing a python script in user2's directory. I installed sqlalchemy as user1 and it by default placed the files in user1's directory. After installing sqlalchemy in user2's directory the problem went away.

How to get a .csv file into R?

As Dirk said, the function you are after is 'read.csv' or one of the other read.table variants. Given your sample data above, I think you will want to do something like this:

setwd("c:/random/directory")

df <- read.csv("myRandomFile.csv", header=TRUE)

All we did in the above was set the directory to where your .csv file is and then read the .csv into a dataframe named df. You can check that the data loaded properly by checking the structure of the object with:

str(df)

Assuming the data loaded properly, you can think go on to perform any number of statistical methods with the data in your data frame. I think summary(df) would be a good place to start. Learning how to use the help in R will be immensely useful, and a quick read through the help on CRAN will save you lots of time in the future: http://cran.r-project.org/

Android Studio - No JVM Installation found

Control Panel -> System -> Advanced system settings -> Environment Variables

I changed JAVA_HOME to JAVA and again changed JAVA to JAVA_HOME.

and Its working fine.

What does the question mark operator mean in Ruby?

It may be worth pointing out that ?s are only allowed in method names, not variables. In the process of learning Ruby, I assumed that ? designated a boolean return type so I tried adding them to flag variables, leading to errors. This led to me erroneously believing for a while that there was some special syntax involving ?s.

Relevant: Why can't a variable name end with `?` while a method name can?

MVC 4 client side validation not working

I created this html <form action="/StudentInfo/Edit/2" method="post" novalidate="novalidate"> where the novalidate="novalidate" was preventing the client-side jQuery from executing, when I removed novalidate="novalidate", client-side jQuery was enabled and stared working.

Best tool for inspecting PDF files?

My sugession is Foxit PDF Reader which is very helpful to do important text editing work on pdf file.

How can I fix MySQL error #1064?

For my case, I was trying to execute procedure code in MySQL, and due to some issue with server in which Server can't figure out where to end the statement I was getting Error Code 1064. So I wrapped the procedure with custom DELIMITER and it worked fine.

For example, Before it was:

DROP PROCEDURE IF EXISTS getStats;
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
    /*Procedure Code Here*/
END;

After putting DELIMITER it was like this:

DROP PROCEDURE IF EXISTS getStats;
DELIMITER $$
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
    /*Procedure Code Here*/
END;
$$
DELIMITER ;

Check if $_POST exists

Try isset($_POST['fromPerson'])?

How to dynamically change header based on AngularJS partial view?

You could define controller at the <html> level.

 <html ng-app="app" ng-controller="titleCtrl">
   <head>
     <title>{{ Page.title() }}</title>
 ...

You create service: Page and modify from controllers.

myModule.factory('Page', function() {
   var title = 'default';
   return {
     title: function() { return title; },
     setTitle: function(newTitle) { title = newTitle }
   };
});

Inject Page and Call 'Page.setTitle()' from controllers.

Here is the concrete example: http://plnkr.co/edit/0e7T6l

Error: "Input is not proper UTF-8, indicate encoding !" using PHP's simplexml_load_string

We recently ran into a similar issue and was unable to find anything obvious as the cause. There turned out to be a control character in our string but when we outputted that string to the browser that character was not visible unless we copied the text into an IDE.

We managed to solve our problem thanks to this post and this:

preg_replace('/[\x00-\x1F\x7F]/', '', $input);

How to style a div to be a responsive square?

It is as easy as specifying a padding bottom the same size as the width in percent. So if you have a width of 50%, just use this example below

id or class{
    width: 50%;
    padding-bottom: 50%;
}

Here is a jsfiddle http://jsfiddle.net/kJL3u/2/

Edited version with responsive text: http://jsfiddle.net/kJL3u/394

Automatically set appsettings.json for dev and release environments in asp.net core?

I have added screenshots of a working environment, because it cost me several hours of R&D.

  1. First, add a key to your launch.json file.

    See the below screenshot, I have added Development as my environment.

    Declaration of the environment variable in launch.json

  2. Then, in your project, create a new appsettings.{environment}.json file that includes the name of the environment.

    In the following screenshot, look for two different files with the names:

    • appsettings.Development.Json
    • appSetting.json


    Project view of appsettings JSON files

  3. And finally, configure it to your StartUp class like this:

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
    
        Configuration = builder.Build();
    }
    
  4. And at last, you can run it from the command line like this:

    dotnet run --environment "Development"
    

    where "Development" is the name of my environment.

CORS header 'Access-Control-Allow-Origin' missing

This happens generally when you try access another domain's resources.

This is a security feature for avoiding everyone freely accessing any resources of that domain (which can be accessed for example to have an exact same copy of your website on a pirate domain).

The header of the response, even if it's 200OK do not allow other origins (domains, port) to access the ressources.

You can fix this problem if you are the owner of both domains:

Solution 1: via .htaccess

To change that, you can write this in the .htaccess of the requested domain file:

    <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
    </IfModule>

If you only want to give access to one domain, the .htaccess should look like this:

    <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin 'https://my-domain.tdl'
    </IfModule>

Solution 2: set headers the correct way

If you set this into the response header of the requested file, you will allow everyone to access the ressources:

Access-Control-Allow-Origin : *

OR

Access-Control-Allow-Origin : http://www.my-domain.com

Peace and code ;)

How to declare array of zeros in python (or an array of a certain size)

Use this:

bucket = [None] * 100
for i in range(100):
    bucket[i] = [None] * 100

OR

w, h = 100, 100
bucket = [[None] * w for i in range(h)]

Both of them will output proper empty multidimensional bucket list 100x100

Scroll back to the top of scrollable div

This is the only way it worked for me, with smooth scrolling transition:

  $('html, body').animate({
    scrollTop: $('#containerDiv').offset().top,
  }, 250);

Match two strings in one line with grep

And as people suggested perl and python, and convoluted shell scripts, here a simple awk approach:

awk '/string1/ && /string2/' filename

Having looked at the comments to the accepted answer: no, this doesn't do multi-line; but then that's also not what the author of the question asked for.

Angularjs - display current date

Just my 2 cents in case someone stumble upon this :)

What I am suggesting here will have the same result as the current answer however it has been recommended to write your controller the way that I have mentioned here.

Reference scroll to the first "Note" (Sorry it doesn't have anchor)

Here is the recommended way:

Controller:

var app = angular.module('myApp', []);   
app.controller( 'MyCtrl', ['$scope', function($scope) {
    $scope.date = new Date();
}]);

View:

<div ng-app="myApp">
  <div ng-controller="MyCtrl">
    {{date | date:'yyyy-MM-dd'}}
  </div>
</div>

error: the details of the application error from being viewed remotely

In my case I got this message because there's a special char (&) in my connectionstring, remove it then everything's good.

Cheers

using CASE in the WHERE clause

This is working Oracle example but it should work in MySQL too.

You are missing smth - see IN after END Replace 'IN' with '=' sign for a single value.

SELECT empno, ename, job
  FROM scott.emp
 WHERE (CASE WHEN job = 'MANAGER' THEN '1'  
         WHEN job = 'CLERK'   THEN '2' 
         ELSE '0'  END) IN (1, 2)

Provide an image for WhatsApp link sharing

Adding my 2 cents on this topic after loosing 4h.

I'm coding a vue app that's compiled with webpack. By default Webpack minifies the HTML, and does it like a butcher. It removes the double quotes from many attributes.

And Whatsapp hates that ! It just skips field not properly formated with quotes around attributes' values.

Turn off the minifaction of your index and things will be fine !

Here's how with Vue-CLI, add this on the vue.config.js file :

    module.exports = {
      chainWebpack: config => {
        config.plugin('html')
          .tap(args => {
            args[0].minify = false
            return args
          })
      }

from : https://github.com/vuejs/vue-cli/issues/4328#issuecomment-595682922

JSONP call showing "Uncaught SyntaxError: Unexpected token : "

Working fiddle:

http://jsfiddle.net/repjt/

$.ajax({
    url: 'https://api.flightstats.com/flex/schedules/rest/v1/jsonp/flight/AA/100/departing/2013/10/4?appId=19d57e69&appKey=e0ea60854c1205af43fd7b1203005d59',
    dataType: 'JSONP',
    jsonpCallback: 'callback',
    type: 'GET',
    success: function (data) {
        console.log(data);
    }
});

I had to manually set the callback to callback, since that's all the remote service seems to support. I also changed the url to specify that I wanted jsonp.

CS1617: Invalid option ‘6’ for /langversion; must be ISO-1, ISO-2, 3, 4, 5 or Default

Turns out this was a problem, because the ASP.NET MVC 4 project was referencing a specific version of the Microsoft.Net.Compilers package. Visual Studio was using the compiler from this specific package, and not the compiler that was installed otherwise on the computer.

A warning or something would have been nice from VS2019 :-)

The solution then is to update the Microsoft.Net.Compilers package to a newer version.

Version 1.x is for C# 6 Version 2.x is for C# 7 Version 3.x is for C# 8 How I got to solve this was not immediately obvious. Visual Studio could have suggested or hinted that by me selecting a new version in the project settings that setting now conflicted with the package installed into the project.

(I ended up turning on Diagnostics level MSBuild logging to find out which CSC.EXE the IDE is really trying to use)

https://developercommunity.visualstudio.com/content/problem/519531/c-7x-versions-do-not-seem-to-work-in-vs2019.html

Click a button programmatically - JS

window.onload = function() {
    var userImage = document.getElementById('imageOtherUser');
    var hangoutButton = document.getElementById("hangoutButtonId");
    userImage.onclick = function() {
       hangoutButton.click(); // this will trigger the click event
    };
};

this will do the trick

Adding placeholder text to textbox

Very effective solution here for WindowsForms TextBox control. (not sure about XAML).

This will work in Multliline mode also.

Probably it may be extended for other controls, like ComboBox control (not checked)

NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference

The exception occurs due to this statement,

called_from.equalsIgnoreCase("add")

It seem that the previous statement

String called_from = getIntent().getStringExtra("called");

returned a null reference.

You can check whether the intent to start this activity contains such a key "called".

How do you access a website running on localhost from iPhone browser

In my case first i connected my pc and mobile on the same network, you can ping your mobile from pc to test the connection.

I running my project with GGTS(Groovy/Grails Tool Suite) locally then accessing website from mobile using PC IP address and it's work very well.

PS. running from local it would give url like (http://localhost:8080/projectname) you should replace localhost with PC IP address if you are trying to access your local website from mobile

java.lang.ClassNotFoundException: org.springframework.core.io.Resource

org.springframework.core.io.Resource is part of spring-core-<version>.jar

But this lib is already in your lib folder. So I guess it is just a Deployment Problem. -- Try to clean your server and redeploy your application.

post ajax data to PHP and return data

 $.ajax({
            type: "POST",
            data: {data:the_id},
            url: "http://localhost/test/index.php/data/count_votes",
            success: function(data){
               //data will contain the vote count echoed by the controller i.e.  
                 "yourVoteCount"
              //then append the result where ever you want like
              $("span#votes_number").html(data); //data will be containing the vote count which you have echoed from the controller

                }
            });

in the controller

$data = $_POST['data'];  //$data will contain the_id
//do some processing
echo "yourVoteCount";

Clarification

i think you are confusing

{data:the_id}

with

success:function(data){

both the data are different for your own clarity sake you can modify it as

success:function(vote_count){
$(span#someId).html(vote_count);

Implementing a slider (SeekBar) in Android

For future readers!

Starting from material components android 1.2.0-alpha01, you have slider component

ex:

<com.google.android.material.slider.Slider
        android:id="@+id/slider"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:valueFrom="20f"
        android:valueTo="70f"
        android:stepSize="10" />

Setting active profile and config location from command line in spring boot

There are two different ways you can add/override spring properties on the command line.

Option 1: Java System Properties (VM Arguments)

It's important that the -D parameters are before your application.jar otherwise they are not recognized.

java -jar -Dspring.profiles.active=prod application.jar

Option 2: Program arguments

java -jar application.jar --spring.profiles.active=prod --spring.config.location=c:\config

In jQuery, how do I get the value of a radio button when they all have the same name?

in your selector, you should also specify that you want the checked radiobutton:

$(function(){
    $("#submit").click(function(){      
        alert($('input[name=q12_3]:checked').val());
    });
 });

Bash script prints "Command Not Found" on empty lines

I was also having some of the Cannot execute command. Everything looked correct, but in fact I was having a non-breakable space &nbsp; right before my command which was ofcourse impossible to spot with the naked eye:

if [[ "true" ]]; then
  &nbsp;highlight --syntax js "var i = 0;"
fi

Which, in Vim, looked like:

if [[ "true" ]]; then
  highlight --syntax js "var i = 0;"
fi

Only after running the Bash script checker shellcheck did I find the problem.

Binding a generic list to a repeater - ASP.NET

You should use ToList() method. (Don't forget about System.Linq namespace)

ex.:

IList<Model> models = Builder<Model>.CreateListOfSize(10).Build();
List<Model> lstMOdels = models.ToList();

Downloading a large file using curl

I use this handy function:

By downloading it with a 4094 byte step it will not full your memory

function download($file_source, $file_target) {
    $rh = fopen($file_source, 'rb');
    $wh = fopen($file_target, 'w+b');
    if (!$rh || !$wh) {
        return false;
    }

    while (!feof($rh)) {
        if (fwrite($wh, fread($rh, 4096)) === FALSE) {
            return false;
        }
        echo ' ';
        flush();
    }

    fclose($rh);
    fclose($wh);

    return true;
}

Usage:

     $result = download('http://url','path/local/file');

You can then check if everything is ok with:

     if (!$result)
         throw new Exception('Download error...');

How to get the query string by javascript?

Here's the method I use...

function Querystring() {
    var q = window.location.search.substr(1), qs = {};
    if (q.length) {
        var keys = q.split("&"), k, kv, key, val, v;
        for (k = keys.length; k--; ) {
            kv = keys[k].split("=");
            key = kv[0];
            val = decodeURIComponent(kv[1]);
            if (qs[key] === undefined) {
                qs[key] = val;
            } else {
                v = qs[key];
                if (v.constructor != Array) {
                    qs[key] = [];
                    qs[key].push(v);
                }
                qs[key].push(val);
            }
        }
    }
    return qs;
}

It returns an object of strings and arrays and seems to work quite well. (Strings for single keys, arrays for the same key with multiple values.)

iPhone - Get Position of UIView within entire UIWindow

In Swift:

let globalPoint = aView.superview?.convertPoint(aView.frame.origin, toView: nil)

Reading PDF documents in .Net

iTextSharp is the best bet. Used it to make a spider for lucene.Net so that it could crawl PDF.

using System;
using System.IO;
using iTextSharp.text.pdf;
using System.Text.RegularExpressions;

namespace Spider.Utils
{
    /// <summary>
    /// Parses a PDF file and extracts the text from it.
    /// </summary>
    public class PDFParser
    {
        /// BT = Beginning of a text object operator 
        /// ET = End of a text object operator
        /// Td move to the start of next line
        ///  5 Ts = superscript
        /// -5 Ts = subscript

        #region Fields

        #region _numberOfCharsToKeep
        /// <summary>
        /// The number of characters to keep, when extracting text.
        /// </summary>
        private static int _numberOfCharsToKeep = 15;
        #endregion

        #endregion

        #region ExtractText
        /// <summary>
        /// Extracts a text from a PDF file.
        /// </summary>
        /// <param name="inFileName">the full path to the pdf file.</param>
        /// <param name="outFileName">the output file name.</param>
        /// <returns>the extracted text</returns>
        public bool ExtractText(string inFileName, string outFileName)
        {
            StreamWriter outFile = null;
            try
            {
                // Create a reader for the given PDF file
                PdfReader reader = new PdfReader(inFileName);
                //outFile = File.CreateText(outFileName);
                outFile = new StreamWriter(outFileName, false, System.Text.Encoding.UTF8);

                Console.Write("Processing: ");

                int totalLen = 68;
                float charUnit = ((float)totalLen) / (float)reader.NumberOfPages;
                int totalWritten = 0;
                float curUnit = 0;

                for (int page = 1; page <= reader.NumberOfPages; page++)
                {
                    outFile.Write(ExtractTextFromPDFBytes(reader.GetPageContent(page)) + " ");

                    // Write the progress.
                    if (charUnit >= 1.0f)
                    {
                        for (int i = 0; i < (int)charUnit; i++)
                        {
                            Console.Write("#");
                            totalWritten++;
                        }
                    }
                    else
                    {
                        curUnit += charUnit;
                        if (curUnit >= 1.0f)
                        {
                            for (int i = 0; i < (int)curUnit; i++)
                            {
                                Console.Write("#");
                                totalWritten++;
                            }
                            curUnit = 0;
                        }

                    }
                }

                if (totalWritten < totalLen)
                {
                    for (int i = 0; i < (totalLen - totalWritten); i++)
                    {
                        Console.Write("#");
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                if (outFile != null) outFile.Close();
            }
        }
        #endregion

        #region ExtractTextFromPDFBytes
        /// <summary>
        /// This method processes an uncompressed Adobe (text) object 
        /// and extracts text.
        /// </summary>
        /// <param name="input">uncompressed</param>
        /// <returns></returns>
        public string ExtractTextFromPDFBytes(byte[] input)
        {
            if (input == null || input.Length == 0) return "";

            try
            {
                string resultString = "";

                // Flag showing if we are we currently inside a text object
                bool inTextObject = false;

                // Flag showing if the next character is literal 
                // e.g. '\\' to get a '\' character or '\(' to get '('
                bool nextLiteral = false;

                // () Bracket nesting level. Text appears inside ()
                int bracketDepth = 0;

                // Keep previous chars to get extract numbers etc.:
                char[] previousCharacters = new char[_numberOfCharsToKeep];
                for (int j = 0; j < _numberOfCharsToKeep; j++) previousCharacters[j] = ' ';


                for (int i = 0; i < input.Length; i++)
                {
                    char c = (char)input[i];
                    if (input[i] == 213)
                        c = "'".ToCharArray()[0];

                    if (inTextObject)
                    {
                        // Position the text
                        if (bracketDepth == 0)
                        {
                            if (CheckToken(new string[] { "TD", "Td" }, previousCharacters))
                            {
                                resultString += "\n\r";
                            }
                            else
                            {
                                if (CheckToken(new string[] { "'", "T*", "\"" }, previousCharacters))
                                {
                                    resultString += "\n";
                                }
                                else
                                {
                                    if (CheckToken(new string[] { "Tj" }, previousCharacters))
                                    {
                                        resultString += " ";
                                    }
                                }
                            }
                        }

                        // End of a text object, also go to a new line.
                        if (bracketDepth == 0 &&
                            CheckToken(new string[] { "ET" }, previousCharacters))
                        {

                            inTextObject = false;
                            resultString += " ";
                        }
                        else
                        {
                            // Start outputting text
                            if ((c == '(') && (bracketDepth == 0) && (!nextLiteral))
                            {
                                bracketDepth = 1;
                            }
                            else
                            {
                                // Stop outputting text
                                if ((c == ')') && (bracketDepth == 1) && (!nextLiteral))
                                {
                                    bracketDepth = 0;
                                }
                                else
                                {
                                    // Just a normal text character:
                                    if (bracketDepth == 1)
                                    {
                                        // Only print out next character no matter what. 
                                        // Do not interpret.
                                        if (c == '\\' && !nextLiteral)
                                        {
                                            resultString += c.ToString();
                                            nextLiteral = true;
                                        }
                                        else
                                        {
                                            if (((c >= ' ') && (c <= '~')) ||
                                                ((c >= 128) && (c < 255)))
                                            {
                                                resultString += c.ToString();
                                            }

                                            nextLiteral = false;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // Store the recent characters for 
                    // when we have to go back for a checking
                    for (int j = 0; j < _numberOfCharsToKeep - 1; j++)
                    {
                        previousCharacters[j] = previousCharacters[j + 1];
                    }
                    previousCharacters[_numberOfCharsToKeep - 1] = c;

                    // Start of a text object
                    if (!inTextObject && CheckToken(new string[] { "BT" }, previousCharacters))
                    {
                        inTextObject = true;
                    }
                }

                return CleanupContent(resultString);
            }
            catch
            {
                return "";
            }
        }

        private string CleanupContent(string text)
        {
            string[] patterns = { @"\\\(", @"\\\)", @"\\226", @"\\222", @"\\223", @"\\224", @"\\340", @"\\342", @"\\344", @"\\300", @"\\302", @"\\304", @"\\351", @"\\350", @"\\352", @"\\353", @"\\311", @"\\310", @"\\312", @"\\313", @"\\362", @"\\364", @"\\366", @"\\322", @"\\324", @"\\326", @"\\354", @"\\356", @"\\357", @"\\314", @"\\316", @"\\317", @"\\347", @"\\307", @"\\371", @"\\373", @"\\374", @"\\331", @"\\333", @"\\334", @"\\256", @"\\231", @"\\253", @"\\273", @"\\251", @"\\221"};
            string[] replace = {   "(",     ")",      "-",     "'",      "\"",      "\"",    "à",      "â",      "ä",      "À",      "Â",      "Ä",      "é",      "è",      "ê",      "ë",      "É",      "È",      "Ê",      "Ë",      "ò",      "ô",      "ö",      "Ò",      "Ô",      "Ö",      "ì",      "î",      "ï",      "Ì",      "Î",      "Ï",      "ç",      "Ç",      "ù",      "û",      "ü",      "Ù",      "Û",      "Ü",      "®",      "™",      "«",      "»",      "©",      "'" };

            for (int i = 0; i < patterns.Length; i++)
            {
                string regExPattern = patterns[i];
                Regex regex = new Regex(regExPattern, RegexOptions.IgnoreCase);
                text = regex.Replace(text, replace[i]);
            }

            return text;
        }

        #endregion

        #region CheckToken
        /// <summary>
        /// Check if a certain 2 character token just came along (e.g. BT)
        /// </summary>
        /// <param name="tokens">the searched token</param>
        /// <param name="recent">the recent character array</param>
        /// <returns></returns>
        private bool CheckToken(string[] tokens, char[] recent)
        {
            foreach (string token in tokens)
            {
                if ((recent[_numberOfCharsToKeep - 3] == token[0]) &&
                    (recent[_numberOfCharsToKeep - 2] == token[1]) &&
                    ((recent[_numberOfCharsToKeep - 1] == ' ') ||
                    (recent[_numberOfCharsToKeep - 1] == 0x0d) ||
                    (recent[_numberOfCharsToKeep - 1] == 0x0a)) &&
                    ((recent[_numberOfCharsToKeep - 4] == ' ') ||
                    (recent[_numberOfCharsToKeep - 4] == 0x0d) ||
                    (recent[_numberOfCharsToKeep - 4] == 0x0a))
                    )
                {
                    return true;
                }
            }
            return false;
        }
        #endregion
    }
}

Material UI and Grid system

I hope this is not too late to give a response.

I was also looking for a simple, robust, flexible and highly customizable bootstrap like react grid system to use in my projects.

The best I know of is react-pure-grid https://www.npmjs.com/package/react-pure-grid

react-pure-grid gives you the power to customize every aspect of your grid system, while at the same time it has built in defaults which probably suits any project

Usage

npm install react-pure-grid --save

-

import {Container, Row, Col} from 'react-pure-grid';

const App = () => (
      <Container>
        <Row>
          <Col xs={6} md={4} lg={3}>Hello, world!</Col>
        </Row>
        <Row>
            <Col xsOffset={5} xs={7}>Welcome!</Col>
        </Row>
      </Container>
);

Copy existing project with a new name in Android Studio

I'm following these steps and it's been working so far:

  1. Copy and paste the folder as used to.
  2. Open Android Studio (v3.0.1).
  3. Select Open an existing Project.
  4. Close the message that will pop up with title: "Import Gradle Projects".
  5. At left side on Android Tab go to: app -> java -> select the first folder (your project folder)
  6. Refactor => Rename... (Shift + F6)
  7. Rename Package, Select both options - Put the new folder's name in lowercase.
  8. Do Refactor
  9. Select: Sync Project with Gradle Files at toolbar.
  10. Build => Clean Project
  11. Go to app -> res -> values -> strings.xml, and change the app name at 2nd line.

Benefits of EBS vs. instance-store (and vice-versa)

For someone new to all this and if accidentally landed here

As of now all AMI's in quickstart section are EBS backed

enter image description here

Also there's a good explanation at official doc for difference between EBS and Instance store

& this image pretty much sums it up enter image description here

In Python how should I test if a variable is None, True or False

Never, never, never say

if something == True:

Never. It's crazy, since you're redundantly repeating what is redundantly specified as the redundant condition rule for an if-statement.

Worse, still, never, never, never say

if something == False:

You have not. Feel free to use it.

Finally, doing a == None is inefficient. Do a is None. None is a special singleton object, there can only be one. Just check to see if you have that object.

Filtering array of objects with lodash based on property value

**Filter by name, age ** also, you can use the map function

difference between map and filter

1. map - The map() method creates a new array with the results of calling a function for every array element. The map method allows items in an array to be manipulated to the user’s preference, returning the conclusion of the chosen manipulation in an entirely new array. For example, consider the following array:

2. filter - The filter() method creates an array filled with all array elements that pass a test implemented by the provided function. The filter method is well suited for particular instances where the user must identify certain items in an array that share a common characteristic. For example, consider the following array:

const users = [
    { name: "john", age: 23 },
    { name: "john", age:43 },
    { name: "jim", age: 101 },
    { name: "bob", age: 67 }
];

const user = _.filter(users, {name: 'jim', age: 101});
console.log(user);

Unable to create Android Virtual Device

I want to update this question with a screenshot of a recent Android Studio. It took a bit of poking around to find where to install new system images.

You get to the SDK Manager through one of two paths. Option 1. Tools > Android > SDK Manager Option 2. Android Studio > Preferences > Appearance & Behavior > System Settings > Android SDK (This is for Mac; adapt for others.)

In the pane "SDK Platforms," check the "Show Packages" box to see the system images.

Select the ones you want, click "Apply" and voilà!

enter image description here

How to "git show" a merge commit with combined diff output even when every changed file agrees with one of the parents?

A better solution (mentioned by @KrisNuttycombe):

git diff fc17405...ee2de56

for the merge commit:

commit 0e1329e551a5700614a2a34d8101e92fd9f2cad6 (HEAD, master)
Merge: fc17405 ee2de56
Author: Tilman Vogel <email@email>
Date:   Tue Feb 22 00:27:17 2011 +0100

to show all of the changes on ee2de56 that are reachable from commits on fc17405. Note the order of the commit hashes - it's the same as shown in the merge info: Merge: fc17405 ee2de56

Also note the 3 dots ... instead of two!

For a list of changed files, you can use:

git diff fc17405...ee2de56 --name-only

Code-first vs Model/Database-first

Code-first appears to be the rising star. I had a quick look at Ruby on Rails, and their standard is code-first, with database migrations.

If you are building an MVC3 application, I believe Code first has the following advantages:

  • Easy attribute decoration - You can decorate fields with validation, require, etc.. attributes, it's quite awkward with EF modelling
  • No weird modelling errors - EF modelling often has weird errors, such as when you try to rename an association property, it needs to match the underlying meta-data - very inflexible.
  • Not awkward to merge - When using code version control tools such as mercurial, merging .edmx files is a pain. You're a programmer used to C#, and there you are merging a .edmx. Not so with code-first.
  • Contrast back to Code first and you have complete control without all the hidden complexities and unknowns to deal with.
  • I recommend you use the Package Manager command line tool, don't even use the graphical tools to add a new controller to scaffold views.
  • DB-Migrations - Then you can also Enable-Migrations. This is so powerful. You make changes to your model in code, and then the framework can keep track of schema changes, so you can seamlessly deploy upgrades, with schema versions automatically upgraded (and downgraded if required). (Not sure, but this probably does work with model-first too)

Update

The question also asks for a comparison of code-first to EDMX model/db-first. Code-first can be used for both of these approaches too:

What are OLTP and OLAP. What is the difference between them?

OLTP: It stands for OnLine Transaction Processing and is used for managing current day to day data information.
OLAP: It stands for OnLine Analytical Processing and is used to maintain the past history of data and mainly used for data analysis, it can also be referred to as warehouse.