Programs & Examples On #Api hook

How to create a self-signed certificate with OpenSSL

This is the script I use on local boxes to set the SAN (subjectAltName) in self-signed certificates.

This script takes the domain name (example.com) and generates the SAN for *.example.com and example.com in the same certificate. The sections below are commented. Name the script (e.g. generate-ssl.sh) and give it executable permissions. The files will be written to the same directory as the script.

Chrome 58 an onward requires SAN to be set in self-signed certificates.

#!/usr/bin/env bash

# Set the TLD domain we want to use
BASE_DOMAIN="example.com"

# Days for the cert to live
DAYS=1095

# A blank passphrase
PASSPHRASE=""

# Generated configuration file
CONFIG_FILE="config.txt"

cat > $CONFIG_FILE <<-EOF
[req]
default_bits = 2048
prompt = no
default_md = sha256
x509_extensions = v3_req
distinguished_name = dn

[dn]
C = CA
ST = BC
L = Vancouver
O = Example Corp
OU = Testing Domain
emailAddress = webmaster@$BASE_DOMAIN
CN = $BASE_DOMAIN

[v3_req]
subjectAltName = @alt_names

[alt_names]
DNS.1 = *.$BASE_DOMAIN
DNS.2 = $BASE_DOMAIN
EOF

# The file name can be anything
FILE_NAME="$BASE_DOMAIN"

# Remove previous keys
echo "Removing existing certs like $FILE_NAME.*"
chmod 770 $FILE_NAME.*
rm $FILE_NAME.*

echo "Generating certs for $BASE_DOMAIN"

# Generate our Private Key, CSR and Certificate
# Use SHA-2 as SHA-1 is unsupported from Jan 1, 2017

openssl req -new -x509 -newkey rsa:2048 -sha256 -nodes -keyout "$FILE_NAME.key" -days $DAYS -out "$FILE_NAME.crt" -passin pass:$PASSPHRASE -config "$CONFIG_FILE"

# OPTIONAL - write an info to see the details of the generated crt
openssl x509 -noout -fingerprint -text < "$FILE_NAME.crt" > "$FILE_NAME.info"

# Protect the key
chmod 400 "$FILE_NAME.key"

This script also writes an information file, so you can inspect the new certificate and verify the SAN is set properly.

                ...
                28:dd:b8:1e:34:b5:b1:44:1a:60:6d:e3:3c:5a:c4:
                da:3d
            Exponent: 65537 (0x10001)
    X509v3 extensions:
        X509v3 Subject Alternative Name: 
            DNS:*.example.com, DNS:example.com
Signature Algorithm: sha256WithRSAEncryption
     3b:35:5a:d6:9e:92:4f:fc:f4:f4:87:78:cd:c7:8d:cd:8c:cc:
     ...

If you are using Apache, then you can reference the above certificate in your configuration file like so:

<VirtualHost _default_:443>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/htdocs

    SSLEngine on
    SSLCertificateFile path/to/your/example.com.crt
    SSLCertificateKeyFile path/to/your/example.com.key
</VirtualHost>

Remember to restart your Apache (or Nginx, or IIS) server for the new certificate to take effect.

Best way to pass parameters to jQuery's .load()

In the first case, the data are passed to the script via GET, in the second via POST.

http://docs.jquery.com/Ajax/load#urldatacallback

I don't think there are limits to the data size, but the completition of the remote call will of course take longer with great amount of data.

How to read a line from the console in C?

The best and simplest way to read a line from a console is using the getchar() function, whereby you will store one character at a time in an array.

{
char message[N];        /* character array for the message, you can always change the character length */
int i = 0;          /* loop counter */

printf( "Enter a message: " );
message[i] = getchar();    /* get the first character */
while( message[i] != '\n' ){
    message[++i] = getchar(); /* gets the next character */
}

printf( "Entered message is:" );
for( i = 0; i < N; i++ )
    printf( "%c", message[i] );

return ( 0 );

}

How to list active connections on PostgreSQL?

Oh, I just found that command on PostgreSQL forum:

SELECT * FROM pg_stat_activity;

Duplicate and rename Xcode project & associated folders

In the example code for the book "Instant OpenCV for iOS" I have found a bash script that copies a project from a folder to another.
Doing a little research I've found a blog post from what seems to be the original author of the script: http://mohrt.blogspot.it/2009/01/renaming-xcode-project-from-command.html, where you can download the script. I gave it a try and running it from terminal like this

    sh renameXcodeProject.sh <name-of-existing-folder> <name-of-folder-to-create>   

works fine.
Additional info can be found opening the file with a text editor. Hope that helps

How to spawn a process and capture its STDOUT in .NET?

You need to call p.Start() to actually run the process after you set the StartInfo. As it is, your function is probably hanging on the WaitForExit() call because the process was never actually started.

Expression must be a modifiable L-value

lvalue means "left value" -- it should be assignable. You cannot change the value of text since it is an array, not a pointer.

Either declare it as char pointer (in this case it's better to declare it as const char*):

const char *text;
if(number == 2) 
    text = "awesome"; 
else 
    text = "you fail";

Or use strcpy:

char text[60];
if(number == 2) 
    strcpy(text, "awesome"); 
else 
    strcpy(text, "you fail");

Mapping object to dictionary and vice versa

public class SimpleObjectDictionaryMapper<TObject>
{
    public static TObject GetObject(IDictionary<string, object> d)
    {
        PropertyInfo[] props = typeof(TObject).GetProperties();
        TObject res = Activator.CreateInstance<TObject>();
        for (int i = 0; i < props.Length; i++)
        {
            if (props[i].CanWrite && d.ContainsKey(props[i].Name))
            {
                props[i].SetValue(res, d[props[i].Name], null);
            }
        }
        return res;
    }

    public static IDictionary<string, object> GetDictionary(TObject o)
    {
        IDictionary<string, object> res = new Dictionary<string, object>();
        PropertyInfo[] props = typeof(TObject).GetProperties();
        for (int i = 0; i < props.Length; i++)
        {
            if (props[i].CanRead)
            {
                res.Add(props[i].Name, props[i].GetValue(o, null));
            }
        }
        return res;
    }
}

How to make android listview scrollable?

I found a tricky solution... which works only in a RelativeLayout. We only need to put a View above a ListView and set clickable 'true' on View and false for the ListView

 <ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/listview
    android:clickable="false" />

<View
    android:layout_width="match_parent"
    android:background="@drawable/gradient_white"
    android:layout_height="match_parent"
    android:clickable="true"
    android:layout_centerHorizontal="true"
    android:layout_alignTop="@+id/listview" />

Django - Did you forget to register or load this tag?

I had the same problem, here's how I solved it. Following the first section of this very excellent Django tutorial, I did the following:

  1. Create a new Django app by executing: python manage.py startapp new_app
  2. Edit the settings.py file, adding the following to the list of INSTALLED_APPS: 'new_app',
  3. Add a new module to the new_app package named new_app_tags.
  4. In a Django HTML template, add the following to the top of the file, but after {% extends 'base_template_name.html' %}: {% load new_app_tags %}
  5. In the new_app_tags module file, create a custom template tag (see below).
  6. In the same Django HTML template, from step 4 above, use your shiney new custom tag like so: {% multiply_by_two | "5.0" %}
  7. Celebrate!

Example from step 5 above:

from django import template

register = template.Library()

@register.simple_tag
def multiply_by_two(value):
    return float(value) * 2.0

Static variables in C++

Static variable in a header file:

say 'common.h' has

static int zzz;

This variable 'zzz' has internal linkage (This same variable can not be accessed in other translation units). Each translation unit which includes 'common.h' has it's own unique object of name 'zzz'.

Static variable in a class:

Static variable in a class is not a part of the subobject of the class. There is only one copy of a static data member shared by all the objects of the class.

$9.4.2/6 - "Static data members of a class in namespace scope have external linkage (3.5).A local class shall not have static data members."

So let's say 'myclass.h' has

struct myclass{
   static int zzz;        // this is only a declaration
};

and myclass.cpp has

#include "myclass.h"

int myclass::zzz = 0           // this is a definition, 
                               // should be done once and only once

and "hisclass.cpp" has

#include "myclass.h"

void f(){myclass::zzz = 2;}    // myclass::zzz is always the same in any 
                               // translation unit

and "ourclass.cpp" has

#include "myclass.h"
void g(){myclass::zzz = 2;}    // myclass::zzz is always the same in any 
                               // translation unit

So, class static members are not limited to only 2 translation units. They need to be defined only once in any one of the translation units.

Note: usage of 'static' to declare file scope variable is deprecated and unnamed namespace is a superior alternate

Javascript close alert box

I guess you could open a popup window and call that a dialog box. I'm unsure of the details, but I'm pretty sure you can close a window programmatically that you opened from javascript. Would this suffice?

What is Teredo Tunneling Pseudo-Interface?

Is to do with IPv6

All the gory details here: http://www.microsoft.com/technet/network/ipv6/teredo.mspx

Some people have had issues with it, and disabled it, but as a general rule, if it aint broke...

How do we determine the number of days for a given month in python

Just for the sake of academic interest, I did it this way...

(dt.replace(month = dt.month % 12 +1, day = 1)-timedelta(days=1)).day

White space at top of page

overflow: auto

Using overflow: auto on the <body> tag is a cleaner solution and will work a charm.

Disabling and enabling a html input button

Disabling/enabling an html input button with JavaScript:

(And React with refs. Replace "elementRef.current" with element selection if not using React)

 elementRef.current.setAttribute('disabled', 'disabled');

Enable:

 elementRef.current.removeAttribute('disabled');

wp-admin shows blank page, how to fix it?

Just visit the plugins folder and delete the last plugin you uploaded and should do the trick.

How to get system time in Java without creating a new Date

This should work:

System.currentTimeMillis();

SQL Server ON DELETE Trigger

CREATE TRIGGER sampleTrigger
    ON database1.dbo.table1
    FOR DELETE
AS
    DELETE FROM database2.dbo.table2
    WHERE bar = 4 AND ID IN(SELECT deleted.id FROM deleted)
GO

How to get an object's property's value by property name?

Expanding upon @aquinas:

Get-something | select -ExpandProperty PropertyName

or

Get-something | select -expand PropertyName

or

Get-something | select -exp PropertyName

I made these suggestions for those that might just be looking for a single-line command to obtain some piece of information and wanted to include a real-world example.

In managing Office 365 via PowerShell, here was an example I used to obtain all of the users/groups that had been added to the "BookInPolicy" list:

Get-CalendarProcessing [email protected] | Select -expand BookInPolicy

Just using "Select BookInPolicy" was cutting off several members, so thank you for this information!

Autocompletion in Vim

If you only wanna auto-completion from cache of your current buffers, supertab is easier to install than neocomplete, can work on Mac pre-installed vim out of box without the need of MacVim.

You can check other alternatives at vim awesome.

What is a elegant way in Ruby to tell if a variable is a Hash or an Array?

You can use instance_of?

e.g

@some_var.instance_of?(Hash)

Difference between JPanel, JFrame, JComponent, and JApplet

You might find it useful to lookup the classes on oracle. Eg:

http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JFrame.html

There you can see that JFrame extends JComponent and JContainer.

JComponent is a a basic object that can be drawn, JContainer extends this so that you can add components to it. JPanel and JFrame both extend JComponent as you can add things to them. JFrame provides a window, whereas JPanel is just a panel that goes inside a window. If that makes sense.

ValueError: all the input arrays must have same number of dimensions

If I start with a 3x4 array, and concatenate a 3x1 array, with axis 1, I get a 3x5 array:

In [911]: x = np.arange(12).reshape(3,4)
In [912]: np.concatenate([x,x[:,-1:]], axis=1)
Out[912]: 
array([[ 0,  1,  2,  3,  3],
       [ 4,  5,  6,  7,  7],
       [ 8,  9, 10, 11, 11]])
In [913]: x.shape,x[:,-1:].shape
Out[913]: ((3, 4), (3, 1))

Note that both inputs to concatenate have 2 dimensions.

Omit the :, and x[:,-1] is (3,) shape - it is 1d, and hence the error:

In [914]: np.concatenate([x,x[:,-1]], axis=1)
...
ValueError: all the input arrays must have same number of dimensions

The code for np.append is (in this case where axis is specified)

return concatenate((arr, values), axis=axis)

So with a slight change of syntax append works. Instead of a list it takes 2 arguments. It imitates the list append is syntax, but should not be confused with that list method.

In [916]: np.append(x, x[:,-1:], axis=1)
Out[916]: 
array([[ 0,  1,  2,  3,  3],
       [ 4,  5,  6,  7,  7],
       [ 8,  9, 10, 11, 11]])

np.hstack first makes sure all inputs are atleast_1d, and then does concatenate:

return np.concatenate([np.atleast_1d(a) for a in arrs], 1)

So it requires the same x[:,-1:] input. Essentially the same action.

np.column_stack also does a concatenate on axis 1. But first it passes 1d inputs through

array(arr, copy=False, subok=True, ndmin=2).T

This is a general way of turning that (3,) array into a (3,1) array.

In [922]: np.array(x[:,-1], copy=False, subok=True, ndmin=2).T
Out[922]: 
array([[ 3],
       [ 7],
       [11]])
In [923]: np.column_stack([x,x[:,-1]])
Out[923]: 
array([[ 0,  1,  2,  3,  3],
       [ 4,  5,  6,  7,  7],
       [ 8,  9, 10, 11, 11]])

All these 'stacks' can be convenient, but in the long run, it's important to understand dimensions and the base np.concatenate. Also know how to look up the code for functions like this. I use the ipython ?? magic a lot.

And in time tests, the np.concatenate is noticeably faster - with a small array like this the extra layers of function calls makes a big time difference.

How to access global variables

I would "inject" the starttime variable instead, otherwise you have a circular dependency between the packages.

main.go

var StartTime = time.Now()
func main() {
   otherPackage.StartTime = StartTime
}

otherpackage.go

var StartTime time.Time

Impact of Xcode build options "Enable bitcode" Yes/No

  • What does the ENABLE_BITCODE actually do, will it be a non-optional requirement in the future?

I'm not sure at what level you are looking for an answer at, so let's take a little trip. Some of this you may already know.

When you build your project, Xcode invokes clang for Objective-C targets and swift/swiftc for Swift targets. Both of these compilers compile the app to an intermediate representation (IR), one of these IRs is bitcode. From this IR, a program called LLVM takes over and creates the binaries needed for x86 32 and 64 bit modes (for the simulator) and arm6/arm7/arm7s/arm64 (for the device). Normally, all of these different binaries are lumped together in a single file called a fat binary.

The ENABLE_BITCODE option cuts out this final step. It creates a version of the app with an IR bitcode binary. This has a number of nice features, but one giant drawback: it can't run anywhere. In order to get an app with a bitcode binary to run, the bitcode needs to be recompiled (maybe assembled or transcoded… I'm not sure of the correct verb) into an x86 or ARM binary.

When a bitcode app is submitted to the App Store, Apple will do this final step and create the finished binaries.

Right now, bitcode apps are optional, but history has shown Apple turns optional things into requirements (like 64 bit support). This usually takes a few years, so third party developers (like Parse) have time to update.

  • can I use the above method without any negative impact and without compromising a future appstore submission?

Yes, you can turn off ENABLE_BITCODE and everything will work just like before. Until Apple makes bitcode apps a requirement for the App Store, you will be fine.

  • Are there any performance impacts if I enable / disable it?

There will never be negative performance impacts for enabling it, but internal distribution of an app for testing may get more complicated.

As for positive impacts… well that's complicated.

For distribution in the App Store, Apple will create separate versions of your app for each machine architecture (arm6/arm7/arm7s/arm64) instead of one app with a fat binary. This means the app installed on iOS devices will be smaller.

In addition, when bitcode is recompiled (maybe assembled or transcoded… again, I'm not sure of the correct verb), it is optimized. LLVM is always working on creating new a better optimizations. In theory, the App Store could recreate the separate version of the app in the App Store with each new release of LLVM, so your app could be re-optimized with the latest LLVM technology.

How can I enable the Windows Server Task Scheduler History recording?

As noted earlier, there is an option to turn on or off History provided you open up task manager under the elevated "Administrator" mode (right click on the Task Scheduler program/shortcut and choose "Run As Administrator"). Then under "Tasks" is your spot to stop or start History.

Can I use an HTML input type "date" to collect only a year?

No you can not but you may want to use input type number as a workaround. Look at the following example:

<input type="number" min="1900" max="2099" step="1" value="2016" />

How to use Session attributes in Spring-mvc

Use This method very simple easy to use

HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getNativeRequest();

                                                            request.getSession().setAttribute("errorMsg", "your massage");

in jsp once use then remove

<c:remove var="errorMsg" scope="session"/>      

Easy way to concatenate two byte arrays

If you don't want to mess with arrays' sizes, just use the magic of string concatenation:

byte[] c = (new String(a, "l1") + new String(b, "l1")).getBytes("l1");

Or define somewhere in your code

// concatenation charset
static final java.nio.charset.Charset cch = java.nio.charset.StandardCharsets.ISO_8859_1;

and use

byte[] c = (new String(a, cch) + new String(b, cch)).getBytes(cch);

This, of course, also works with more than two string concatenations using the + addition operator.


Both "l1" and ISO_8859_1 indicate the Western Latin 1 character set that encodes each character as a single byte. As no multi-byte translations are performed the characters in the string will have the same values as the bytes (except that they will always be interpreted as positive values, as char is unsigned). At least for the Oracle provided runtime, any byte will therefore be correctly "decoded" and then "encoded" again.

Beware that strings do expand the byte array considerately, requiring additional memory. Strings may also be interned and will therefore not easy be removed. Strings are also immutable, so the values inside them cannot be destroyed. You should therefore not concatenate sensitive arrays this way nor should you use this method for larger byte arrays. Giving a clear indication of what you are doing would also be required, as this method of array concatenation is not a common solution.

Where can I download Spring Framework jars without using Maven?

Please edit to keep this list of mirrors current

I found this maven repo where you could download from directly a zip file containing all the jars you need.

Alternate solution: Maven

The solution I prefer is using Maven, it is easy and you don't have to download each jar alone. You can do it with the following steps:

  1. Create an empty folder anywhere with any name you prefer, for example spring-source

  2. Create a new file named pom.xml

  3. Copy the xml below into this file

  4. Open the spring-source folder in your console

  5. Run mvn install

  6. After download finished, you'll find spring jars in /spring-source/target/dependencies

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>spring-source-download</groupId>
      <artifactId>SpringDependencies</artifactId>
      <version>1.0</version>
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
      <dependencies>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>3.2.4.RELEASE</version>
        </dependency>
      </dependencies>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.8</version>
            <executions>
              <execution>
                <id>download-dependencies</id>
                <phase>generate-resources</phase>
                <goals>
                  <goal>copy-dependencies</goal>
                </goals>
                <configuration>
                  <outputDirectory>${project.build.directory}/dependencies</outputDirectory>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </project>
    

Also, if you need to download any other spring project, just copy the dependency configuration from its corresponding web page.

For example, if you want to download Spring Web Flow jars, go to its web page, and add its dependency configuration to the pom.xml dependencies, then run mvn install again.

<dependency>
  <groupId>org.springframework.webflow</groupId>
  <artifactId>spring-webflow</artifactId>
  <version>2.3.2.RELEASE</version>
</dependency>

The SELECT permission was denied on the object 'Users', database 'XXX', schema 'dbo'

Check space of your database.this error comes when space increased compare to space given to database.

unix - count of columns in file

You could try

cat FILE | awk '{print NF}'

Bootstrap 4, how to make a col have a height of 100%?

Use bootstrap class vh-100 for exp:

<div class="vh-100">

How to remove text before | character in notepad++

Please use regex to remove anything before |

example

dsfdf | fdfsfsf
dsdss|gfghhghg
dsdsds |dfdsfsds

Use find and replace in notepad++

find: .+(\|) replace: \1

output

| fdfsfsf
|gfghhghg
|dfdsfsds

What is *.o file?

A .o object file file (also .obj on Windows) contains compiled object code (that is, machine code produced by your C or C++ compiler), together with the names of the functions and other objects the file contains. Object files are processed by the linker to produce the final executable. If your build process has not produced these files, there is probably something wrong with your makefile/project files.

setting JAVA_HOME & CLASSPATH in CentOS 6

It seems that you dont have any problem with the environmental variables.

Compile your file from src with

javac a/A.java

Then, run your program as

java a.A

Spring data JPA query with parameter properties

You can try something like this:

public interface PersonRepository extends CrudRepository<Person, Long> {
       @Query("select p from Person AS p"
       + " ,Name AS n"  
       + " where p.forename = n.forename "
       + " and p.surname = n.surname"
       + " and n = :name")
       Set<Person>findByName(@Param("name") Name name);
    }

Find the paths between two given nodes?

What you're trying to do is essentially to find a path between two vertices in a (directed?) graph check out Dijkstra's algorithm if you need shortest path or write a simple recursive function if you need whatever paths exist.

tsc is not recognized as internal or external command

In the VSCode file tasks.json, the "command": "tsc" will try to find the tsc windows command script in some folder that it deems to be your modules folder.

If you know where the command npm install -g typescript or npm install typescript is saving to, I would recommend replacing:

"command": "tsc"

with

"command": "D:\\Projects\\TS\\Tutorial\\node_modules\\.bin\\tsc"

where D:\\...\\bin is the folder that contains my tsc windows executable

Will determine where my vscode is natively pointing to right now to find the tsc and fix it I guess.

LaTeX source code listing like in professional books

And please, whatever you do, configure the listings package to use fixed-width font (as in your example; you'll find the option in the documentation). Default setting uses proportional font typeset on a grid, which is, IMHO, incredibly ugly and unreadable, as can be seen from the other answers with pictures. I am personally very irritated when I must read some code typeset in a proportional font.

Try setting fixed-width font with this:

\lstset{basicstyle=\ttfamily}

PHP get domain name

Similar question has been asked in stackoverflow before.

See here: PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

Also see this article: http://shiflett.org/blog/2006/mar/server-name-versus-http-host

Recommended using HTTP_HOST, and falling back on SERVER_NAME only if HTTP_HOST was not set. He said that SERVER_NAME could be unreliable on the server for a variety of reasons, including:

  • no DNS support
  • misconfigured
  • behind load balancing software

Source: http://discussion.dreamhost.com/thread-4388.html

What order are the Junit @Before/@After called?

You can use @BeforeClass annotation to assure that setup() is always called first. Similarly, you can use @AfterClass annotation to assure that tearDown() is always called last.

This is usually not recommended, but it is supported.

It's not exactly what you want - but it'll essentially keep your DB connection open the entire time your tests are running, and then close it once and for all at the end.

Laravel Eloquent: How to get only certain columns from joined tables

Check out, http://laravel.com/docs/database/eloquent#to-array

You should be able to define which columns you do not want displayed in your api.

Opening A Specific File With A Batch File?

@echo off
cd "folder directory to your file"
start filename.ext

For example:

cd "C:\Program Files (x86)\Winamp" 
Start winamp.exe

"The certificate chain was issued by an authority that is not trusted" when connecting DB in VM Role from Azure website

The same can be achieved from ssms client itself. Just open the ssms, insert the server name and then from options under heading connection properties make sure Trust server certificate is checked.

How can you tell if a value is not numeric in Oracle?

SELECT DECODE(REGEXP_COUNT(:value,'\d'),LENGTH(:value),'Y','N') AS is_numeric FROM dual;

There are many ways but this one works perfect for me.

Laravel 5.2 - pluck() method returns array

In Laravel 5.1+, you can use the value() instead of pluck.

To get first occurence, You can either use

DB::table('users')->value('name');

or use,

DB::table('users')->where('id', 1)->pluck('name')->first();

How to access first element of JSON object array?

the event property seems to be string first you have to parse it to json :

 var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' };
 var event = JSON.parse(req.mandrill_events);
 var ts =  event[0].ts

Get URL of ASP.Net Page in code-behind

Request.Url.GetLeftPart(UriPartial.Authority) + Request.FilePath + "?theme=blue";

that will give you the full path to the page you are sitting on. I added in the querystring.

How to convert list of numpy arrays into single numpy array?

I checked some of the methods for speed performance and find that there is no difference! The only difference is that using some methods you must carefully check dimension.

Timing:

|------------|----------------|-------------------|
|            | shape (10000)  |  shape (1,10000)  |
|------------|----------------|-------------------|
| np.concat  |    0.18280     |      0.17960      |
|------------|----------------|-------------------|
|  np.stack  |    0.21501     |      0.16465      |
|------------|----------------|-------------------|
| np.vstack  |    0.21501     |      0.17181      |
|------------|----------------|-------------------|
|  np.array  |    0.21656     |      0.16833      |
|------------|----------------|-------------------|

As you can see I tried 2 experiments - using np.random.rand(10000) and np.random.rand(1, 10000) And if we use 2d arrays than np.stack and np.array create additional dimension - result.shape is (1,10000,10000) and (10000,1,10000) so they need additional actions to avoid this.

Code:

from time import perf_counter
from tqdm import tqdm_notebook
import numpy as np
l = []
for i in tqdm_notebook(range(10000)):
    new_np = np.random.rand(10000)
    l.append(new_np)



start = perf_counter()
stack = np.stack(l, axis=0 )
print(f'np.stack: {perf_counter() - start:.5f}')

start = perf_counter()
vstack = np.vstack(l)
print(f'np.vstack: {perf_counter() - start:.5f}')

start = perf_counter()
wrap = np.array(l)
print(f'np.array: {perf_counter() - start:.5f}')

start = perf_counter()
l = [el.reshape(1,-1) for el in l]
conc = np.concatenate(l, axis=0 )
print(f'np.concatenate: {perf_counter() - start:.5f}')

require_once :failed to open stream: no such file or directory

The error pretty much explains what the problem is: you are trying to include a file that is not there.

Try to use the full path to the file, using realpath(), and use dirname(__FILE__) to get your current directory:

require_once(realpath(dirname(__FILE__) . '/../includes/dbconn.inc'));

Can I style an image's ALT text with CSS?

In Firefox and Chrome (and possibly more) we can insert the string ‘( .... )’ into the alt text of an image that hasn’t loaded.

_x000D_
_x000D_
img {_x000D_
  font-style: italic;_x000D_
  color: #c00;_x000D_
}_x000D_
_x000D_
img:after {_x000D_
  content: " (Image - Right click to reload if not loaded)";_x000D_
}_x000D_
_x000D_
img::after {_x000D_
  content: " (Image - Right click to reload if not loaded)";_x000D_
}
_x000D_
<img alt="Alt text - " />
_x000D_
_x000D_
_x000D_

Delete specific values from column with where condition?

You can also use REPLACE():

UPDATE Table
   SET Column = REPLACE(Column, 'Test123', 'Test')

How do I change Eclipse to use spaces instead of tabs?

From changing tabs to spaces in eclipse:

Window » Preferences » Java » Code Style » Formatter » Edit » Indentation (choose "Spaces Only")

Yarn install command error No such file or directory: 'install'

My solution was

curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -

echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list

sudo apt-get update && sudo apt-get install yarn

How can I find my Apple Developer Team id and Team Agent Apple ID?

For personal teams

grep DEVELOPMENT_TEAM MyProject.xcodeproj/project.pbxproj

should give you the team ID

DEVELOPMENT_TEAM = ZU88ND8437;

isset in jQuery?

function isset(element) {
    return element.length > 0;
}

http://jsfiddle.net/8KYxe/1/


Or, as a jQuery extension:

$.fn.exists = function() { return this.length > 0; };

// later ...
if ( $("#id").exists() ) {
  // do something
}

How to exit from ForEach-Object in PowerShell

Item #1. Putting a break within the foreach loop does exit the loop, but it does not stop the pipeline. It sounds like you want something like this:

$todo=$project.PropertyGroup 
foreach ($thing in $todo){
    if ($thing -eq 'some_condition'){
        break
    }
}

Item #2. PowerShell lets you modify an array within a foreach loop over that array, but those changes do not take effect until you exit the loop. Try running the code below for an example.

$a=1,2,3
foreach ($value in $a){
  Write-Host $value
}
Write-Host $a

I can't comment on why the authors of PowerShell allowed this, but most other scripting languages (Perl, Python and shell) allow similar constructs.

Could not find default endpoint element

In my case, I was referring to this service from a library project, not a startup Project. Once I copied <system.serviceModel> section to the configuration of the main startup project, The issue got resolved.

During running stage of any application, the configuration will be read from the startup/parent project instead of reading its own configurations mentioned in separate subprojects.

Getting only Month and Year from SQL DATE

SELECT REPLACE(RIGHT(CONVERT(VARCHAR(11), GETDATE(), 106), 8), ' ', '-')

Output: Mar-2019

Using ffmpeg to change framerate

You may consider using fps filter. It won't change the video playback speed:

ffmpeg -i <input> -filter:v fps=fps=30 <output>

Worked nice for reducing fps from 59.6 to 30.

in_array multiple values

Intersect the targets with the haystack and make sure the intersection is precisely equal to the targets:

$haystack = array(...);

$target = array('foo', 'bar');

if(count(array_intersect($haystack, $target)) == count($target)){
    // all of $target is in $haystack
}

Note that you only need to verify the size of the resulting intersection is the same size as the array of target values to say that $haystack is a superset of $target.

To verify that at least one value in $target is also in $haystack, you can do this check:

 if(count(array_intersect($haystack, $target)) > 0){
     // at least one of $target is in $haystack
 }

Read XML file using javascript

You can do something like this to read your nodes.

Also you can find some explanation in this page http://www.compoc.com/tuts/

<script type="text/javascript">
        var markers = null;
        $(document).ready(function () {
            $.get("File.xml", {}, function (xml){
              $('marker',xml).each(function(i){
                 markers = $(this);
              });
            });
        });
</script>

Parsing JSON from XmlHttpRequest.responseJSON

New ways I: fetch

TL;DR I'd recommend this way as long as you don't have to send synchronous requests or support old browsers.

A long as your request is asynchronous you can use the Fetch API to send HTTP requests. The fetch API works with promises, which is a nice way to handle asynchronous workflows in JavaScript. With this approach you use fetch() to send a request and ResponseBody.json() to parse the response:

fetch(url)
  .then(function(response) {
    return response.json();
  })
  .then(function(jsonResponse) {
    // do something with jsonResponse
  });

Compatibility: The Fetch API is not supported by IE11 as well as Edge 12 & 13. However, there are polyfills.

New ways II: responseType

As Londeren has written in his answer, newer browsers allow you to use the responseType property to define the expected format of the response. The parsed response data can then be accessed via the response property:

var req = new XMLHttpRequest();
req.responseType = 'json';
req.open('GET', url, true);
req.onload  = function() {
   var jsonResponse = req.response;
   // do something with jsonResponse
};
req.send(null);

Compatibility: responseType = 'json' is not supported by IE11.

The classic way

The standard XMLHttpRequest has no responseJSON property, just responseText and responseXML. As long as bitly really responds with some JSON to your request, responseText should contain the JSON code as text, so all you've got to do is to parse it with JSON.parse():

var req = new XMLHttpRequest();
req.overrideMimeType("application/json");
req.open('GET', url, true);
req.onload  = function() {
   var jsonResponse = JSON.parse(req.responseText);
   // do something with jsonResponse
};
req.send(null);

Compatibility: This approach should work with any browser that supports XMLHttpRequest and JSON.

JSONHttpRequest

If you prefer to use responseJSON, but want a more lightweight solution than JQuery, you might want to check out my JSONHttpRequest. It works exactly like a normal XMLHttpRequest, but also provides the responseJSON property. All you have to change in your code would be the first line:

var req = new JSONHttpRequest();

JSONHttpRequest also provides functionality to easily send JavaScript objects as JSON. More details and the code can be found here: http://pixelsvsbytes.com/2011/12/teach-your-xmlhttprequest-some-json/.

Full disclosure: I'm the owner of Pixels|Bytes. I thought that my script was a good solution for the original question, but it is rather outdated today. I do not recommend to use it anymore.

How to define an empty object in PHP

stdClass is the default PHP object. stdClass has no properties, methods or parent. It does not support magic methods, and implements no interfaces.

When you cast a scalar or array as Object, you get an instance of stdClass. You can use stdClass whenever you need a generic object instance.

<?php
// ways of creating stdClass instances
$x = new stdClass;
$y = (object) null;        // same as above
$z = (object) 'a';         // creates property 'scalar' = 'a'
$a = (object) array('property1' => 1, 'property2' => 'b');
?>

stdClass is NOT a base class! PHP classes do not automatically inherit from any class. All classes are standalone, unless they explicitly extend another class. PHP differs from many object-oriented languages in this respect.

<?php
// CTest does not derive from stdClass
class CTest {
    public $property1;
}
$t = new CTest;
var_dump($t instanceof stdClass);            // false
var_dump(is_subclass_of($t, 'stdClass'));    // false
echo get_class($t) . "\n";                   // 'CTest'
echo get_parent_class($t) . "\n";            // false (no parent)
?>

You cannot define a class named 'stdClass' in your code. That name is already used by the system. You can define a class named 'Object'.

You could define a class that extends stdClass, but you would get no benefit, as stdClass does nothing.

(tested on PHP 5.2.8)

how to delete installed library form react native project

If you want to unlink already installed packages in react native

  1. $ react-native unlink package_name
  2. $ yarn remove package_name (if it is npm then npm uninstall --save)

If you execute 2nd step before 1st step you need to install relevant package back and execute 2nd step

Where does Internet Explorer store saved passwords?

No guarantee, but I suspect IE uses the older Protected Storage API.

Java double comparison epsilon

Yes. Java doubles will hold their precision better than your given epsilon of 0.00001.

Any rounding error that occurs due to the storage of floating point values will occur smaller than 0.00001. I regularly use 1E-6 or 0.000001 for a double epsilon in Java with no trouble.

On a related note, I like the format of epsilon = 1E-5; because I feel it is more readable (1E-5 in Java = 1 x 10^-5). 1E-6 is easy to distinguish from 1E-5 when reading code whereas 0.00001 and 0.000001 look so similar when glancing at code I think they are the same value.

Switch case: can I use a range instead of a one number

I would use ternary operators to categorize your switch conditions.

So...

switch( number > 9 ? "High" :
        number > 5 ? "Mid" :
        number > 1 ? "Low" : "Floor")
        {
              case "High":
                    do the thing;
                    break;
               case "Mid":
                    do the other thing;
                    break;
               case "Low":
                    do something else;
                    break;
               case "Floor":
                    do whatever;
                    break;
         }

Unknown version of Tomcat was specified in Eclipse

For LINUX the installation directory for Tomcat 7 is: /usr/share/tomcat7

Please use this configuration.

More here: http://gridlab.dimes.unical.it/lackovic/eclipse-tomcat-ubuntu-jersey/

Adding days to a date in Python

In order to have have a less verbose code, and avoid name conflicts between datetime and datetime.datetime, you should rename the classes with CamelCase names.

from datetime import datetime as DateTime, timedelta as TimeDelta

So you can do the following, which I think it is clearer.

date_1 = DateTime.today() 
end_date = date_1 + TimeDelta(days=10)

Also, there would be no name conflict if you want to import datetime later on.

Copy folder recursively, excluding some folders

Use rsync:

rsync -av --exclude='path1/to/exclude' --exclude='path2/to/exclude' source destination

Note that using source and source/ are different. A trailing slash means to copy the contents of the folder source into destination. Without the trailing slash, it means copy the folder source into destination.

Alternatively, if you have lots of directories (or files) to exclude, you can use --exclude-from=FILE, where FILE is the name of a file containing files or directories to exclude.

--exclude may also contain wildcards, such as --exclude=*/.svn*

Replace specific characters within strings

With a regular expression and the function gsub():

group <- c("12357e", "12575e", "197e18", "e18947")
group
[1] "12357e" "12575e" "197e18" "e18947"

gsub("e", "", group)
[1] "12357" "12575" "19718" "18947"

What gsub does here is to replace each occurrence of "e" with an empty string "".


See ?regexp or gsub for more help.

What is mod_php?

It means that you have to have PHP installed as a module in Apache, instead of starting it as a CGI script.

How do I properly clean up Excel interop objects?

Just to add another solution to the many listed here, using C++/ATL automation (I imagine you could use something similar from VB/C#??)

Excel::_ApplicationPtr pXL = ...
  :
SendMessage ( ( HWND ) m_pXL->GetHwnd ( ), WM_DESTROY, 0, 0 ) ;

This works like a charm for me...

Get response from PHP file using AJAX

The good practice is to use like this:

$.ajax({
    type: "POST",
    url: "/ajax/request.html",
    data: {action: 'test'},
    dataType:'JSON', 
    success: function(response){
        console.log(response.blablabla);
        // put on console what server sent back...
    }
});

and the php part is:

<?php
    if(isset($_POST['action']) && !empty($_POST['action'])) {
        echo json_encode(array("blablabla"=>$variable));
    }
?>

Save the console.log in Chrome to a file

the other solutions in this thread weren't working on my mac. Here's a logger that saves a string representation intermittently using ajax. use it with console.save instead of console.log

var logFileString="";
var maxLogLength=1024*128;

console.save=function(){
  var logArgs={};

  for(var i=0; i<arguments.length; i++) logArgs['arg'+i]=arguments[i];
  console.log(logArgs);

  // keep a string representation of every log
  logFileString+=JSON.stringify(logArgs,null,2)+'\n';

  // save the string representation when it gets big
  if(logFileString.length>maxLogLength){
    // send a copy in case race conditions change it mid-save
    saveLog(logFileString);
    logFileString="";
  }
};

depending on what you need, you can save that string or just console.log it and copy and paste. here's an ajax for you in case you want to save it:

function saveLog(data){
  // do some ajax stuff with data.
  var xhttp = new XMLHttpRequest();

  xhttp.onreadystatechange = function(){
    if (this.readyState == 4 && this.status == 200) {}
  }

  xhttp.open("POST", 'saveLog.php', true);
  xhttp.send(data);
}

the saveLog.php should append the data to a log file somewhere. I didn't need that part so I'm not including it here. :)

https://www.google.com/search?q=php+append+to+log

ClientAbortException: java.net.SocketException: Connection reset by peer: socket write error

Windows Firewall could cause this exception, try to disable it or add a rule for port or even program (java)

Is there a way to iterate over a range of integers?

You can also check out github.com/wushilin/stream

It is a lazy stream like concept of java.util.stream.

// It doesn't really allocate the 10 elements.
stream1 := stream.Range(0, 10)

// Print each element.
stream1.Each(print)

// Add 3 to each element, but it is a lazy add.
// You only add when consume the stream
stream2 := stream1.Map(func(i int) int {
    return i + 3
})

// Well, this consumes the stream => return sum of stream2.
stream2.Reduce(func(i, j int) int {
    return i + j
})

// Create stream with 5 elements
stream3 := stream.Of(1, 2, 3, 4, 5)

// Create stream from array
stream4 := stream.FromArray(arrayInput)

// Filter stream3, keep only elements that is bigger than 2,
// and return the Sum, which is 12
stream3.Filter(func(i int) bool {
    return i > 2
}).Sum()

Hope this helps

Can I give a default value to parameters or optional parameters in C# functions?

This is a feature of C# 4.0, but was not possible without using function overload prior to that version.

Python 2.7 getting user input and manipulating as string without quotations

Use raw_input() instead of input():

testVar = raw_input("Ask user for something.")

input() actually evaluates the input as Python code. I suggest to never use it. raw_input() returns the verbatim string entered by the user.

How to increase IDE memory limit in IntelliJ IDEA on Mac?

Helpful trick I thought I'd share on this old thread.

You can see how much memory is being used and adjust things accordingly using the Show memory indicator setting.

enter image description here

It shows up in the lower right of the window.

enter image description here

REST API Best practices: Where to put parameters?

As per the REST Implementation,

1) Path variables are used for the direct action on the resources, like a contact or a song ex..
GET etc /api/resource/{songid} or
GET etc /api/resource/{contactid} will return respective data.

2) Query perms/argument are used for the in-direct resources like metadata of a song ex.., GET /api/resource/{songid}?metadata=genres it will return the genres data for that particular song.

Unable to get provider com.google.firebase.provider.FirebaseInitProvider

Instead of manually adding the package name on the build.gradle, you can do it this way:

first add this line at the beggining

import java.util.regex.Pattern

Then add this on the defaultConfig

android {
    ...
    defaultConfig {
        ...
        applicationId = doExtractStringFromManifest("package")
        ...
    }
    ...
}

And finally add the doExtractStringFromManifest method

def doExtractStringFromManifest(name) {
     def manifestFile = file(android.sourceSets.main.manifest.srcFile)
     def pattern = Pattern.compile(name + "=\"(\\S+)\"")
     def matcher = pattern.matcher(manifestFile.getText())
     matcher.find()
     return matcher.group(1)
}

As there are a lot of Cordova comments on the answer, if you are working with Cordova, you shouldn't really edit the build.gradle yourself, it has a comment at the beggining that say

// GENERATED FILE! DO NOT EDIT!

So, if you are using a Cordova, the best thing you can do is to update to cordova-android 5.1.0 or greater where this changes are already present.

How to overwrite files with Copy-Item in PowerShell

As I understand Copy-Item -Exclude then you are doing it correct. What I usually do, get 1'st, and then do after, so what about using Get-Item as in

Get-Item -Path $copyAdmin -Exclude $exclude |
Copy-Item  -Path $copyAdmin -Destination $AdminPath -Recurse -force

Get the selected value in a dropdown using jQuery.

I have gone through all the answers provided above. This is the easiest way which I used to get the selected value from the drop down list

$('#searchType').val() // for the value

How do I create executable Java program?

As suggested earlier too, you can look at launch4j to create the executable for your JAR file. Also, there is something called "JExePack" that can put an .exe wrapper around your jar file so that you can redistribute it (note: the client would anyways need a JRE to run the program on his pc) Exes created with GCJ will not have this dependency but the process is a little more involved.

cURL error 60: SSL certificate: unable to get local issuer certificate

All of the answers are correct ; but the most important thing is You have to find the right php.ini file. check this command in cmd " php --ini " is not the right answer for finding the right php.ini file.

if you edit

curl.cainfo ="PATH/cacert.pem"

and check

var_dump(openssl_get_cert_locations()); 

then curl.cainfo should have a value. if not then that's not right php.ini file;

*I recommend you to search *.ini in wamp/bin or xxamp/bin or any server you use and change them one by one and check it. *

How can I disable inherited css styles?

Give the div you don't want him inheriting the property background too.

Simple way to query connected USB devices info in Python?

When I run your code, I get the following output for example.

<usb.Device object at 0xef38c0>
Device: 001
  idVendor: 7531 (0x1d6b)
  idProduct: 1 (0x0001)
Manufacturer: 3
Serial: 1
Product: 2

Noteworthy are that a) I have usb.Device objects whereas you have usb.legacy.Device objects, and b) I have device filenames.

Each usb.Bus has a dirname field and each usb.Device has the filename. As you can see, the filename is something like 001, and so is the dirname. You can combine these to get the bus file. For dirname=001 and filname=001, it should be something like /dev/bus/usb/001/001.

You should first, though figure out what this "usb.legacy" situation is. I'm running the latest version and I don't even have a legacy sub-module.

Finally, you should use the idVendor and idProduct fields to uniquely identify the device when it's plugged in.

How to SSH to a VirtualBox guest externally through a host?

You can also use a Bridged Network (or "Bridge Adapter", in newer versions) in network settings. This will put your VM in a VLAN with your machine. So you can just ssh into the VM like this.

ssh user@IP_OF_VM

AppStore - App status is ready for sale, but not in app store

you must change Territory and click on save, after one minute your app will be available. No need to Remove from sale

MySQL - UPDATE multiple rows with different values in one query

update table_name
set cod_user = 
    CASE 
    WHEN user_rol = 'student' THEN '622057'
    WHEN user_rol = 'assistant' THEN '2913659'
    WHEN user_rol = 'admin' THEN '6160230'?
    END,date = '12082014'

WHERE user_rol IN ('student','assistant','admin')
AND cod_office = '17389551';

Where do I put a single filter that filters methods in two controllers in Rails

Two ways.

i. You can put it in ApplicationController and add the filters in the controller

    class ApplicationController < ActionController::Base       def filter_method       end     end      class FirstController < ApplicationController       before_filter :filter_method     end      class SecondController < ApplicationController       before_filter :filter_method     end 

But the problem here is that this method will be added to all the controllers since all of them extend from application controller

ii. Create a parent controller and define it there

 class ParentController < ApplicationController   def filter_method   end  end  class FirstController < ParentController   before_filter :filter_method end  class SecondController < ParentController   before_filter :filter_method end 

I have named it as parent controller but you can come up with a name that fits your situation properly.

You can also define the filter method in a module and include it in the controllers where you need the filter

Error: macro names must be identifiers using #ifdef 0

Note that you can also hit this error if you accidentally type:

#define <stdio.h>

...instead of...

#include <stdio.>

How to remove package using Angular CLI?

With the cli I don't know if it's a remove command but you can remove it from package.json and stop using it in your code.If you reinstall the packages you wilk not have it any more

Measuring elapsed time with the Time module

time.time() will do the job.

import time

start = time.time()
# run your code
end = time.time()

elapsed = end - start

You may want to look at this question, but I don't think it will be necessary.

How to use an array list in Java?

If you use Java 1.5 or beyond you could use:

List<String> S = new ArrayList<String>();
s.add("My text");

for (String item : S) {
  System.out.println(item);
}

Histogram using gnuplot?

I have a couple corrections/additions to Born2Smile's very useful answer:

  1. Empty bins caused the box for the adjacent bin to incorrectly extend into its space; avoid this using set boxwidth binwidth
  2. In Born2Smile's version, bins are rendered as centered on their lower bound. Strictly they ought to extend from the lower bound to the upper bound. This can be corrected by modifying the bin function: bin(x,width)=width*floor(x/width) + width/2.0

Method to get all files within folder and subfolders that will return a list

This is for anyone that is trying to get a list of all files in a folder and its sub-folders and save it in a text document. Below is the full code including the “using” statements, “namespace”, “class”, “methods” etc. I tried commenting as much as possible throughout the code so you could understand what each part is doing. This will create a text document that contains a list of all files in all folders and sub-folders of any given root folder. After all, what good is a list (like in Console.WriteLine) if you can’t do something with it. Here I have created a folder on the C drive called “Folder1” and created a folder inside that one called “Folder2”. Next I filled folder2 with a bunch of files, folders and files and folders within those folders. This example code will get all the files and create a list in a text document and place that text document in Folder1. Caution: you shouldn’t save the text document to Folder2 (the folder you are reading from), that would be just bad practice. Always save it to another folder.
I hope this helps someone down the line.

using System;
using System.IO;

namespace ConsoleApplication4
{
    class Program
    {
        public static void Main(string[] args)
        {
            // Create a header for your text file
            string[] HeaderA = { "****** List of Files ******" };
            System.IO.File.WriteAllLines(@"c:\Folder1\ListOfFiles.txt", HeaderA);

            // Get all files from a folder and all its sub-folders. Here we are getting all files in the folder
            // named "Folder2" that is in "Folder1" on the C: drive. Notice the use of the 'forward and back slash'.
            string[] arrayA = Directory.GetFiles(@"c:\Folder1/Folder2", "*.*", SearchOption.AllDirectories);
            {
                //Now that we have a list of files, write them to a text file.
                WriteAllLines(@"c:\Folder1\ListOfFiles.txt", arrayA);
            }

            // Now, append the header and list to the text file.
            using (System.IO.StreamWriter file =
                new System.IO.StreamWriter(@"c:\Folder1\ListOfFiles.txt"))
            {
                // First - call the header 
                foreach (string line in HeaderA)
                {
                    file.WriteLine(line);
                }

                file.WriteLine(); // This line just puts a blank space between the header and list of files. 


                // Now, call teh list of files.
                foreach (string name in arrayA)
                {
                    file.WriteLine(name);
                }

            }
          }


        // These are just the "throw new exception" calls that are needed when converting the array's to strings. 

        // This one is for the Header.
        private static void WriteAllLines(string v, string file)
        {
            //throw new NotImplementedException();
        }

        // And this one is for the list of files. 
        private static void WriteAllLines(string v, string[] arrayA)
        {
            //throw new NotImplementedException();
        }



    }
}

C++ sorting and keeping track of indexes

Beautiful solution by @Lukasz Wiklendt! Although in my case I needed something more generic so I modified it a bit:

template <class RAIter, class Compare>
vector<size_t> argSort(RAIter first, RAIter last, Compare comp) {

  vector<size_t> idx(last-first);
  iota(idx.begin(), idx.end(), 0);

  auto idxComp = [&first,comp](size_t i1, size_t i2) {
      return comp(first[i1], first[i2]);
  };

  sort(idx.begin(), idx.end(), idxComp);

  return idx;
}

Example: Find indices sorting a vector of strings by length, except for the first element which is a dummy.

vector<string> test = {"dummy", "a", "abc", "ab"};

auto comp = [](const string &a, const string& b) {
    return a.length() > b.length();
};

const auto& beginIt = test.begin() + 1;
vector<size_t> ind = argSort(beginIt, test.end(), comp);

for(auto i : ind)
    cout << beginIt[i] << endl;

prints:

abc
ab
a

Basic http file downloading and saving to disk in python?

I started down this path because ESXi's wget is not compiled with SSL and I wanted to download an OVA from a vendor's website directly onto the ESXi host which is on the other side of the world.

I had to disable the firewall(lazy)/enable https out by editing the rules(proper)

created the python script:

import ssl
import shutil
import tempfile
import urllib.request
context = ssl._create_unverified_context()

dlurl='https://somesite/path/whatever'
with urllib.request.urlopen(durl, context=context) as response:
    with open("file.ova", 'wb') as tmp_file:
        shutil.copyfileobj(response, tmp_file)

ESXi libraries are kind of paired down but the open source weasel installer seemed to use urllib for https... so it inspired me to go down this path

Delete an element in a JSON object

with open('writing_file.json', 'w') as w:
    with open('reading_file.json', 'r') as r:
        for line in r:
            element = json.loads(line.strip())
            if 'hours' in element:
                del element['hours']
            w.write(json.dumps(element))

this is the method i use..

How can I list all foreign keys referencing a given table in SQL Server?

Working off of what @Gishu did I was able to produce and use the following SQL in SQL Server 2005

SELECT t.name AS TableWithForeignKey, fk.constraint_column_id AS FK_PartNo, 
       c.name AS ForeignKeyColumn, o.name AS FK_Name 
  FROM sys.foreign_key_columns AS fk
       INNER JOIN sys.tables AS t ON fk.parent_object_id = t.object_id
       INNER JOIN sys.columns AS c ON fk.parent_object_id = c.object_id 
                                  AND fk.parent_column_id = c.column_id
       INNER JOIN sys.objects AS o ON fk.constraint_object_id = o.object_id
  WHERE fk.referenced_object_id = (SELECT object_id FROM sys.tables 
                                        WHERE name = 'TableOthersForeignKeyInto')
  ORDER BY TableWithForeignKey, FK_PartNo;

Which Displays the tables, columns and Foreign Key names all in 1 query.

Get current category ID of the active page

I think some of the above may work but using the get_the_category function seems tricky and may give unexpected results.

I think the most direct and simple way to access the cat ID in a category page is:

$wp_query->query_vars['cat']

Cheers

How do I import a .sql file in mysql database using PHP?

Grain Script is superb and save my day. Meanwhile mysql is depreciated and I rewrote Grain answer using PDO.

    $server  =  'localhost'; 
    $username   = 'root'; 
    $password   = 'your password';  
    $database = 'sample_db';

    /* PDO connection start */
    $conn = new PDO("mysql:host=$server; dbname=$database", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);         
    $conn->exec("SET CHARACTER SET utf8");     
    /* PDO connection end */

    // your config
    $filename = 'yourFile.sql';

    $maxRuntime = 8; // less then your max script execution limit


    $deadline = time()+$maxRuntime; 
    $progressFilename = $filename.'_filepointer'; // tmp file for progress
    $errorFilename = $filename.'_error'; // tmp file for erro



    ($fp = fopen($filename, 'r')) OR die('failed to open file:'.$filename);

    // check for previous error
    if( file_exists($errorFilename) ){
        die('<pre> previous error: '.file_get_contents($errorFilename));
    }

    // activate automatic reload in browser
    echo '<html><head> <meta http-equiv="refresh" content="'.($maxRuntime+2).'"><pre>';

    // go to previous file position
    $filePosition = 0;
    if( file_exists($progressFilename) ){
        $filePosition = file_get_contents($progressFilename);
        fseek($fp, $filePosition);
    }

    $queryCount = 0;
    $query = '';
    while( $deadline>time() AND ($line=fgets($fp, 1024000)) ){
        if(substr($line,0,2)=='--' OR trim($line)=='' ){
            continue;
        }

        $query .= $line;
        if( substr(trim($query),-1)==';' ){

            $igweze_prep= $conn->prepare($query);

            if(!($igweze_prep->execute())){ 
                $error = 'Error performing query \'<strong>' . $query . '\': ' . print_r($conn->errorInfo());
                file_put_contents($errorFilename, $error."\n");
                exit;
            }
            $query = '';
            file_put_contents($progressFilename, ftell($fp)); // save the current file position for 
            $queryCount++;
        }
    }

    if( feof($fp) ){
        echo 'dump successfully restored!';
    }else{
        echo ftell($fp).'/'.filesize($filename).' '.(round(ftell($fp)/filesize($filename), 2)*100).'%'."\n";
        echo $queryCount.' queries processed! please reload or wait for automatic browser refresh!';
    }

Visual Studio 64 bit?

No, but the 32-bit version runs just fine on 64-bit Windows.

Python append() vs. + operator on lists, why do these give different results?

To explain "why":

The + operation adds the array elements to the original array. The array.append operation inserts the array (or any object) into the end of the original array, which results in a reference to self in that spot (hence the infinite recursion).

The difference here is that the + operation acts specific when you add an array (it's overloaded like others, see this chapter on sequences) by concatenating the element. The append-method however does literally what you ask: append the object on the right-hand side that you give it (the array or any other object), instead of taking its elements.

An alternative

Use extend() if you want to use a function that acts similar to the + operator (as others have shown here as well). It's not wise to do the opposite: to try to mimic append with the + operator for lists (see my earlier link on why).

Little history

For fun, a little history: the birth of the array module in Python in February 1993. it might surprise you, but arrays were added way after sequences and lists came into existence.

jQuery .search() to any string

search() is a String method.

You are executing the attr function on every <li> element. You need to invoke each and use the this reference within.

Example:

$('li').each(function() {
    var isFound = $(this).attr('title').search(/string/i);
    //do something based on isFound...
});

Style bottom Line in Android

I feel it is straightforward, without all this negative paddings or storks.

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@color/main_bg_color"/>
    <item android:gravity="bottom">
        <shape android:shape="rectangle">
            <size android:height="5dp"/>
            <solid android:color="@color/bottom_bar_color"/>
        </shape>
    </item>
</layer-list>

Creating a "logical exclusive or" operator in Java

The only operator overloading in Java is + on Strings (JLS 15.18.1 String Concatenation Operator +).

The community has been divided in 3 for years, 1/3 doesn't want it, 1/3 want it, and 1/3 doesn't care.

You can use unicode to create method names that are symbols... so if you have a symbol you want to use you could do myVal = x.$(y); where $ is the symbol and x is not a primitive... but that is going to be dodgy in some editors and is limiting since you cannot do it on a primitive.

Underline text in UIlabel

Sometimes we developer stuck in small designing part of any UI screen. One of the most irritating requirement is under line text. Don’t worry here is the solution.

enter image description here

Underlining a text in a UILabel using Objective C

UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
label.backgroundColor=[UIColor lightGrayColor];
NSMutableAttributedString *attributedString;
attributedString = [[NSMutableAttributedString alloc] initWithString:@"Apply Underlining"];
[attributedString addAttribute:NSUnderlineStyleAttributeName value:@1 range:NSMakeRange(0,
[attributedString length])];
[label setAttributedText:attributedString];

Underlining a text in UILabel using Swift

 label.backgroundColor = .lightGray
 let attributedString = NSMutableAttributedString.init(string: "Apply UnderLining")
 attributedString.addAttribute(NSUnderlineStyleAttributeName, value: 1, range:
NSRange.init(location: 0, length: attributedString.length))
 label.attributedText = attributedString

Leaflet - How to find existing markers, and delete markers?

In my case, I have various layer groups so that users can show/hide clusters of like type markers. But, in any case you delete an individual marker by looping over your layer groups to find and delete it. While looping, search for a marker with a custom attribute, in my case a 'key', added when the marker was added to the layer group. Add your 'key' just like adding a title attribute. Later this is gotten an a layer option. When you find that match, you .removeLayer() and it gets rid of that particular marker. Hope that helps you out!

eventsLayerGroup.addLayer(L.marker([tag.latitude, tag.longitude],{title:tag.title, layer:tag.layer, timestamp:tag.timestamp, key:tag.key, bounceOnAdd: true, icon: L.AwesomeMarkers.icon({icon: 'vignette', markerColor: 'blue', prefix: '', iconColor: 'white'}) }).bindPopup(customPopup(tag),customOptions).on('click', markerClick)); 

function removeMarker(id){
    var layerGroupsArray = [eventsLayerGroup,landmarksLayerGroup,travelerLayerGroup,marketplaceLayerGroup,myLayerGroup];
    $.each(layerGroupsArray, function (key, value) {
        value.eachLayer(function (layer) {
            if(typeof value !== "undefined"){
                if (layer.options.layer){
                    console.log(layer.options.key);
                    console.log(id);
                    if (id === layer.options.key){
                        value.removeLayer(layer);
                    }
                }
            }
        });
    });
}

One line if/else condition in linux shell scripting

To summarize the other answers, for general use:

Multi-line if...then statement

if [ foo ]; then
    a; b
elif [ bar ]; then
    c; d
else
    e; f
fi

Single-line version

if [ foo ]; then a && b; elif [ bar ]; c && d; else e && f; fi

Using the OR operator

( foo && a && b ) || ( bar && c && d ) || e && f;

Notes

Remember that the AND and OR operators evaluate whether or not the result code of the previous operation was equal to true/success (0). So if a custom function returns something else (or nothing at all), you may run into problems with the AND/OR shorthand. In such cases, you may want to replace something like ( a && b ) with ( [ a == 'EXPECTEDRESULT' ] && b ), etc.

Also note that ( and [ are technically commands, so whitespace is required around them.

Instead of a group of && statements like then a && b; else, you could also run statements in a subshell like then $( a; b ); else, though this is less efficient. The same is true for doing something like result1=$( foo; a; b ); result2=$( bar; c; d ); [ "$result1" -o "$result2" ] instead of ( foo && a && b ) || ( bar && c && d ). Though at that point you'd be getting more into less-compact, multi-line stuff anyway.

How to make a variable accessible outside a function?

Your variable declarations and their scope are correct. The problem you are facing is that the first AJAX request may take a little bit time to finish. Therefore, the second URL will be filled with the value of sID before the its content has been set. You have to remember that AJAX request are normally asynchronous, i.e. the code execution goes on while the data is being fetched in the background.

You have to nest the requests:

$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   obj = name;   // sID is only now available!   sID = obj.id;   console.log(sID); }); 


Clean up your code!

  • Put the second request into a function
  • and let it accept sID as a parameter, so you don't have to declare it globally anymore! (Global variables are almost always evil!)
  • Remove sID and obj variables - name.id is sufficient unless you really need the other variables outside the function.


$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   // We don't need sID or obj here - name.id is sufficient   console.log(name.id);    doSecondRequest(name.id); });  /// TODO Choose a better name function doSecondRequest(sID) {   $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function(stats){         console.log(stats);   }); } 

Hapy New Year :)

Rollback to an old Git commit in a public repo

git read-tree -um @ $commit_to_revert_to

will do it. It's "git checkout" but without updating HEAD.

You can achieve the same effect with

git checkout $commit_to_revert_to
git reset --soft @{1}

if you prefer stringing convenience commands together.

These leave you with your worktree and index in the desired state, you can just git commit to finish.

How to center and crop an image to always appear in square shape with CSS?

Try putting your image into a container like so:

HTML:

<div>
    <img src="http://www.testimoniesofheavenandhell.com/Animal-Pictures/wp-content/uploads/2013/04/Dog-Animal-Picture-Siberian-Husky-Puppy-HD-Wallpaper.jpg" />
</div>

CSS:

div
{
    width: 200px;
    height: 200px;
    overflow: hidden;
}

div > img
{
    width: 300px;
}

Here's a fiddle.

Non greedy (reluctant) regex matching in sed?

echo "/home/one/two/three/myfile.txt" | sed 's|\(.*\)/.*|\1|'

don bother, i got it on another forum :)

less than 10 add 0 to number

Make a function that you can reuse:

function minTwoDigits(n) {
  return (n < 10 ? '0' : '') + n;
}

Then use it in each part of the coordinates:

c += minTwoDigits(deg) + "° ";

and so on.

Change image size via parent div

Yours:

  <div style="height:42px;width:42px">
  <img src="http://someimage.jpg">

Is it okay to use this code?

  <div class= "box">
  <img src= "http://someimage.jpg" class= "img">
  </div>

  <style type="text/css">
  .box{width: 42; height: 42;}
  .img{width: 20; height:20;}
  </style>

Just trying, though late. :3 For someone else reading this, letme know if the way i wrote the code were not good. im new in this kind of language. and i still want to learn more.

Get first key in a (possibly) associative array?

You could try

array_keys($data)[0]

Limit length of characters in a regular expression?

(^(\d{2})|^(\d{4})|^(\d{5}))$

This expression takes the number of length 2,4 and 5. Valid Inputs are 12 1234 12345

UPDATE and REPLACE part of a string

UPDATE table_name
SET field_name = '0'
WHERE field_name IS Null

SQL DROP TABLE foreign key constraint

If it is SQL Server you must drop the constraint before you can drop the table.

HTML5 pattern for formatting input box to take date mm/dd/yyyy?

Below pattern perfectly works in case of leap year and as well as with normal dates. The date format is : YYYY-MM-DD

<input type="text"  placeholder="YYYY-MM-DD" pattern="(?:19|20)(?:(?:[13579][26]|[02468][048])-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))|(?:[0-9]{2}-(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:29|30))|(?:(?:0[13578]|1[02])-31)))" class="form-control "  name="eventDate" id="" required autofocus autocomplete="nope">

I got this solution from http://html5pattern.com/Dates. Hope it may help someone.

Check if a JavaScript string is a URL

There's a lot of answers already, but here's another contribution: Taken directly from the URL polyfill validity check, use an input element with type="url" to take advantage of the browser's built-in validity check:

var inputElement = doc.createElement('input');
inputElement.type = 'url';
inputElement.value = url;

if (!inputElement.checkValidity()) {
    throw new TypeError('Invalid URL');
}

Source

How to export all collections in MongoDB?

For dump, your DB fallow the below CMD

   mongodump -d <your d name> -o <dump path>
Ex:mongodump -d qualetics -o D:\dbpackup\qualetics

How to use underscore.js as a template engine?

I wanted to share one more important finding.

use of <%= variable => would result in cross-site scripting vulnerability. So its more safe to use <%- variable -> instead.

We had to replace <%= with <%- to prevent cross-site scripting attacks. Not sure, whether this will it have any impact on the performance

How to use SVG markers in Google Maps API v3

You can render your icon using the SVG Path notation.

See Google documentation for more information.

Here is a basic example:

var icon = {

    path: "M-20,0a20,20 0 1,0 40,0a20,20 0 1,0 -40,0",
    fillColor: '#FF0000',
    fillOpacity: .6,
    anchor: new google.maps.Point(0,0),
    strokeWeight: 0,
    scale: 1
}

var marker = new google.maps.Marker({
    position: event.latLng,
    map: map,
    draggable: false,
    icon: icon
});

Here is a working example on how to display and scale a marker SVG icon:

JSFiddle demo

Edit:

Another example here with a complex icon:

JSFiddle demo

Edit 2:

And here is how you can have a SVG file as an icon:

JSFiddle demo

Is there an arraylist in Javascript?

In Java script you declare array as below:

var array=[];
array.push();

and for arraylist or object or array you have to use json; and Serialize it using json by using following code:

 var serializedMyObj = JSON.stringify(myObj);

ERROR! MySQL manager or server PID file could not be found! QNAP

Nothing of this worked for me. I tried everything and nothing worked.

I just did :

brew unlink mysql && brew install mariadb

My concern was if I would lost all the data, but luckily everything was there.

Hope it works for somebody else

Webdriver Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms

I think this could be a problem of display. If you do not have GUI in the box, then launching firefox from selenium webdriver would give this error.

To resolve this, first install Xvfb [yum install Xvfb -y]( a virtual display driver) in the box. Then run your test from jenkins with xvfv-run -a -d <your test execution command>. This will launch the browser in a virtual display buffer. Also it is capable of getting screenshots using selenium webdriver.

How to test the `Mosquitto` server?

The OP has not defined the scope of testing, however, simple (gross) 'smoke testing' an install should be performed before any time is invested with functionality testing.

How to test if application is installed ('smoke-test')

Log into the mosquitto server's command line and type:

mosquitto

If mosquitto is installed the machine will return:

 mosquitto version 1.4.8 (build date Wed, date of installation) starting
 Using default config.
 Opening ipv4 listen socket on port 1883

Gridview get Checkbox.Checked value

For run all lines of GridView don't use for loop, use foreach loop like:

foreach (GridViewRow row in yourGridName.Rows) //Running all lines of grid
{
    if (row.RowType == DataControlRowType.DataRow)
    {
         CheckBox chkRow = (row.Cells[0].FindControl("chkRow") as CheckBox);

         if (chkRow.Checked)
         {
              //if checked do something
         }
    }
}

Why does 'git commit' not save my changes?

I had an issue where I was doing commit --amend even after issuing a git add . and it still wasn't working. Turns out I made some .vimrc customizations and my editor wasn't working correctly. Fixing these errors so that vim returns the correct code resolved the issue.

Get selected item value from Bootstrap DropDown with specific ID

Did you just try

$('#datebox li a').on('click', function(){
    //$('#datebox').val($(this).text());
    alert($(this).text());
});

It works for me :)

How to load a tsv file into a Pandas DataFrame?

Try this

df = pd.read_csv("rating-data.tsv",sep='\t')
df.head()

enter image description here

You actually need to fix the sep parameter.

How to write a large buffer into a binary file in C++, fast?

Try the following, in order:

  • Smaller buffer size. Writing ~2 MiB at a time might be a good start. On my last laptop, ~512 KiB was the sweet spot, but I haven't tested on my SSD yet.

    Note: I've noticed that very large buffers tend to decrease performance. I've noticed speed losses with using 16-MiB buffers instead of 512-KiB buffers before.

  • Use _open (or _topen if you want to be Windows-correct) to open the file, then use _write. This will probably avoid a lot of buffering, but it's not certain to.

  • Using Windows-specific functions like CreateFile and WriteFile. That will avoid any buffering in the standard library.

npm install from Git in a specific version

The accepted answer did not work for me. Here's what I'm doing to pull a package from github:

npm install --save "git://github.com/username/package.git#commit"

Or adding it manually on package.json:

"dependencies": {
  "package": "git://github.com/username/package.git#commit"
}

Pure CSS checkbox image replacement

If you are still looking for further more customization,

Check out the following library: https://lokesh-coder.github.io/pretty-checkbox/

Thanks

What is the difference between a 'closure' and a 'lambda'?

A lambda is just an anonymous function - a function defined with no name. In some languages, such as Scheme, they are equivalent to named functions. In fact, the function definition is re-written as binding a lambda to a variable internally. In other languages, like Python, there are some (rather needless) distinctions between them, but they behave the same way otherwise.

A closure is any function which closes over the environment in which it was defined. This means that it can access variables not in its parameter list. Examples:

def func(): return h
def anotherfunc(h):
   return func()

This will cause an error, because func does not close over the environment in anotherfunc - h is undefined. func only closes over the global environment. This will work:

def anotherfunc(h):
    def func(): return h
    return func()

Because here, func is defined in anotherfunc, and in python 2.3 and greater (or some number like this) when they almost got closures correct (mutation still doesn't work), this means that it closes over anotherfunc's environment and can access variables inside of it. In Python 3.1+, mutation works too when using the nonlocal keyword.

Another important point - func will continue to close over anotherfunc's environment even when it's no longer being evaluated in anotherfunc. This code will also work:

def anotherfunc(h):
    def func(): return h
    return func

print anotherfunc(10)()

This will print 10.

This, as you notice, has nothing to do with lambdas - they are two different (although related) concepts.

Python: Tuples/dictionaries as keys, select, sort

With keys as tuples, you just filter the keys with given second component and sort it:

blue_fruit = sorted([k for k in data.keys() if k[1] == 'blue'])
for k in blue_fruit:
  print k[0], data[k] # prints 'banana 24', etc

Sorting works because tuples have natural ordering if their components have natural ordering.

With keys as rather full-fledged objects, you just filter by k.color == 'blue'.

You can't really use dicts as keys, but you can create a simplest class like class Foo(object): pass and add any attributes to it on the fly:

k = Foo()
k.color = 'blue'

These instances can serve as dict keys, but beware their mutability!

Intersection and union of ArrayLists in Java

  • retainAll will modify your list
  • Guava doesn't have APIs for List (only for set)

I found ListUtils very useful for this use case.

Use ListUtils from org.apache.commons.collections if you do not want to modify existing list.

ListUtils.intersection(list1, list2)

How to use Jquery how to change the aria-expanded="false" part of a dom element (Bootstrap)?

You can use .attr() as a part of however you plan to toggle it:

$("button").attr("aria-expanded","true");

What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types

I have a slightly different perspective on the difference between a DATETIME and a TIMESTAMP. A DATETIME stores a literal value of a date and time with no reference to any particular timezone. So, I can set a DATETIME column to a value such as '2019-01-16 12:15:00' to indicate precisely when my last birthday occurred. Was this Eastern Standard Time? Pacific Standard Time? Who knows? Where the current session time zone of the server comes into play occurs when you set a DATETIME column to some value such as NOW(). The value stored will be the current date and time using the current session time zone in effect. But once a DATETIME column has been set, it will display the same regardless of what the current session time zone is.

A TIMESTAMP column on the other hand takes the '2019-01-16 12:15:00' value you are setting into it and interprets it in the current session time zone to compute an internal representation relative to 1/1/1970 00:00:00 UTC. When the column is displayed, it will be converted back for display based on whatever the current session time zone is. It's a useful fiction to think of a TIMESTAMP as taking the value you are setting and converting it from the current session time zone to UTC for storing and then converting it back to the current session time zone for displaying.

If my server is in San Francisco but I am running an event in New York that starts on 9/1/1029 at 20:00, I would use a TIMESTAMP column for holding the start time, set the session time zone to 'America/New York' and set the start time to '2009-09-01 20:00:00'. If I want to know whether the event has occurred or not, regardless of the current session time zone setting I can compare the start time with NOW(). Of course, for displaying in a meaningful way to a perspective customer, I would need to set the correct session time zone. If I did not need to do time comparisons, then I would probably be better off just using a DATETIME column, which will display correctly (with an implied EST time zone) regardless of what the current session time zone is.

TIMESTAMP LIMITATION

The TIMESTAMP type has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC and so it may not usable for your particular application. In that case you will have to use a DATETIME type. You will, of course, always have to be concerned that the current session time zone is set properly whenever you are using this type with date functions such as NOW().

pass JSON to HTTP POST Request

       var request = require('request');
        request({
            url: "http://localhost:8001/xyz",
            json: true,
            headers: {
                "content-type": "application/json",
            },
            body: JSON.stringify(requestData)
        }, function(error, response, body) {
            console.log(response);
        });

LINQ .Any VS .Exists - What's the difference?

See documentation

List.Exists (Object method - MSDN)

Determines whether the List(T) contains elements that match the conditions defined by the specified predicate.

This exists since .NET 2.0, so before LINQ. Meant to be used with the Predicate delegate, but lambda expressions are backward compatible. Also, just List has this (not even IList)

IEnumerable.Any (Extension method - MSDN)

Determines whether any element of a sequence satisfies a condition.

This is new in .NET 3.5 and uses Func(TSource, bool) as argument, so this was intended to be used with lambda expressions and LINQ.

In behaviour, these are identical.

GridView sorting: SortDirection always Ascending

The problem with Session and Viewstate is that you also have to keep track of the gridview control for which SortColumn and Direction is stored if there is more than one gridview on the page.

An alternative to Session and Viewstate is to add 2 attributes to the Gridview and keep track of Column and Direction that way.

Here is an example:

private void GridViewSortDirection(GridView g, GridViewSortEventArgs e, out SortDirection d, out string f)
{
    f = e.SortExpression;
    d = e.SortDirection;

    //Check if GridView control has required Attributes
    if (g.Attributes["CurrentSortField"] != null && g.Attributes["CurrentSortDir"] != null)
    {
        if (f == g.Attributes["CurrentSortField"])
        {
            d = SortDirection.Descending;
            if (g.Attributes["CurrentSortDir"] == "ASC")
            {
                d = SortDirection.Ascending;
            }
        }

        g.Attributes["CurrentSortField"] = f;
        g.Attributes["CurrentSortDir"] = (d == SortDirection.Ascending ? "DESC" : "ASC");
    }

}

WCF ServiceHost access rights

Running Visual Studio as administrator could fix the issue, but if you use Visual Studio with for example TortoiseSVN, you cannot commit any changes. Another possible solution would be to run the service as administrator and the rest Visual Studio as local user.

Make Error 127 when running trying to compile code

Error 127 means one of two things:

  1. file not found: the path you're using is incorrect. double check that the program is actually in your $PATH, or in this case, the relative path is correct -- remember that the current working directory for a random terminal might not be the same for the IDE you're using. it might be better to just use an absolute path instead.
  2. ldso is not found: you're using a pre-compiled binary and it wants an interpreter that isn't on your system. maybe you're using an x86_64 (64-bit) distro, but the prebuilt is for x86 (32-bit). you can determine whether this is the answer by opening a terminal and attempting to execute it directly. or by running file -L on /bin/sh (to get your default/native format) and on the compiler itself (to see what format it is).

if the problem is (2), then you can solve it in a few diff ways:

  1. get a better binary. talk to the vendor that gave you the toolchain and ask them for one that doesn't suck.
  2. see if your distro can install the multilib set of files. most x86_64 64-bit distros allow you to install x86 32-bit libraries in parallel.
  3. build your own cross-compiler using something like crosstool-ng.
  4. you could switch between an x86_64 & x86 install, but that seems a bit drastic ;).

CSS table layout: why does table-row not accept a margin?

adding a br tag between the divs worked. add br tag between two divs that are display:table-row in a parent with display:table

How to read an entire file to a string using C#?

You can use like this

public static string ReadFileAndFetchStringInSingleLine(string file)
    {
        StringBuilder sb;
        try
        {
            sb = new StringBuilder();
            using (FileStream fs = File.Open(file, FileMode.Open))
            {
                using (BufferedStream bs = new BufferedStream(fs))
                {
                    using (StreamReader sr = new StreamReader(bs))
                    {
                        string str;
                        while ((str = sr.ReadLine()) != null)
                        {
                            sb.Append(str);
                        }
                    }
                }
            }
            return sb.ToString();
        }
        catch (Exception ex)
        {
            return "";
        }
    }

Hope this will help you.

How do I get some variable from another class in Java?

I am trying to get int x equal to 5 (as seen in the setNum() method) but when it prints it gives me 0.

To run the code in setNum you have to call it. If you don't call it, the default value is 0.

convert array into DataFrame in Python

In general you can use pandas rename function here. Given your dataframe you could change to a new name like this. If you had more columns you could also rename those in the dictionary. The 0 is the current name of your column

import pandas as pd    
import numpy as np   
e = np.random.normal(size=100)  
e_dataframe = pd.DataFrame(e)      

e_dataframe.rename(index=str, columns={0:'new_column_name'})

Does a foreign key automatically create an index?

Foreign keys do not create indexes. Only alternate key constraints(UNIQUE) and primary key constraints create indexes. This is true in Oracle and SQL Server.

Java equivalent to JavaScript's encodeURIComponent that produces identical output?

I came up with my own version of the encodeURIComponent, because the posted solution has one problem, if there was a + present in the String, which should be encoded, it will converted to a space.

So here is my class:

import java.io.UnsupportedEncodingException;
import java.util.BitSet;

public final class EscapeUtils
{
    /** used for the encodeURIComponent function */
    private static final BitSet dontNeedEncoding;

    static
    {
        dontNeedEncoding = new BitSet(256);

        // a-z
        for (int i = 97; i <= 122; ++i)
        {
            dontNeedEncoding.set(i);
        }
        // A-Z
        for (int i = 65; i <= 90; ++i)
        {
            dontNeedEncoding.set(i);
        }
        // 0-9
        for (int i = 48; i <= 57; ++i)
        {
            dontNeedEncoding.set(i);
        }

        // '()*
        for (int i = 39; i <= 42; ++i)
        {
            dontNeedEncoding.set(i);
        }
        dontNeedEncoding.set(33); // !
        dontNeedEncoding.set(45); // -
        dontNeedEncoding.set(46); // .
        dontNeedEncoding.set(95); // _
        dontNeedEncoding.set(126); // ~
    }

    /**
     * A Utility class should not be instantiated.
     */
    private EscapeUtils()
    {

    }

    /**
     * Escapes all characters except the following: alphabetic, decimal digits, - _ . ! ~ * ' ( )
     * 
     * @param input
     *            A component of a URI
     * @return the escaped URI component
     */
    public static String encodeURIComponent(String input)
    {
        if (input == null)
        {
            return input;
        }

        StringBuilder filtered = new StringBuilder(input.length());
        char c;
        for (int i = 0; i < input.length(); ++i)
        {
            c = input.charAt(i);
            if (dontNeedEncoding.get(c))
            {
                filtered.append(c);
            }
            else
            {
                final byte[] b = charToBytesUTF(c);

                for (int j = 0; j < b.length; ++j)
                {
                    filtered.append('%');
                    filtered.append("0123456789ABCDEF".charAt(b[j] >> 4 & 0xF));
                    filtered.append("0123456789ABCDEF".charAt(b[j] & 0xF));
                }
            }
        }
        return filtered.toString();
    }

    private static byte[] charToBytesUTF(char c)
    {
        try
        {
            return new String(new char[] { c }).getBytes("UTF-8");
        }
        catch (UnsupportedEncodingException e)
        {
            return new byte[] { (byte) c };
        }
    }
}

SyntaxError: missing ) after argument list

I faced the same issue in below scenario yesterday. However I fixed it as shown below. But it would be great if someone can explain me as to why this error was coming specifically in my case.

pasted content of index.ejs file that gave the error in the browser when I run my node file "app.js". It has a route "/blogs" that redirects to "index.ejs" file.

<%= include partials/header %>
<h1>Index Page</h1>
<% blogs.forEach(function(blog){ %>
    <div>
        <h2><%= blog.title %></h2>
        <image src="<%= blog.image %>">
        <span><%= blog.created %></span>
        <p><%= blog.body %></p>
    </div>
<% }) %>
<%= include partials/footer %>

The error that came on the browser :

SyntaxError: missing ) after argument list in /home/ubuntu/workspace/RESTful/RESTfulBlogApp/views/index.ejs while compiling ejs

How I fixed it : I removed "=" in the include statements at the top and the bottom and it worked fine.

Wait until an HTML5 video loads

call function on load:

<video onload="doWhatYouNeedTo()" src="demo.mp4" id="video">

get video duration

var video = document.getElementById("video");
var duration = video.duration;

How to lock specific cells but allow filtering and sorting

Here is an article that explains the problem and solution with alot more detail:

Sorting Locked Cells in Protected Worksheets

The thing to understand is that the purpose of locking cells is to prevent them from being changed, and sorting permanently changes cell values. You can write a macro, but a much better solution is to use the "Allow Users to Edit Ranges" feature. This makes the cells editable so sorting can work, but because the cells are still technically locked you can prevent users from selecting them.

How do I add multiple conditions to "ng-disabled"?

You can try something like this.

<button class="button" ng-disabled="(!data.var1 && !data.var2) ? false : true">
</button>

Its working fine for me.

How to resolve javax.mail.AuthenticationFailedException issue?

You need to implement a custom Authenticator

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;


class GMailAuthenticator extends Authenticator {
     String user;
     String pw;
     public GMailAuthenticator (String username, String password)
     {
        super();
        this.user = username;
        this.pw = password;
     }
    public PasswordAuthentication getPasswordAuthentication()
    {
       return new PasswordAuthentication(user, pw);
    }
}

Now use it in the Session

Session session = Session.getInstance(props, new GMailAuthenticator(username, password));

Also check out the JavaMail FAQ

What are the benefits of using C# vs F# or F# vs C#?

  • F# Has Better Performance than C# in Math
  • You could use F# projects in the same solution with C# (and call from one to another)
  • F# is really good for complex algorithmic programming, financial and scientific applications
  • F# logically is really good for the parallel execution (it is easier to make F# code execute on parallel cores, than C#)

How can I update NodeJS and NPM to the next versions?

For Linux, OSX, etc..

To install the latest version of NPM

npm install -g npm@latest

Or To Install the most recent release

npm install -g npm@next

Additional : To check your npm version

npm -v

If you are in a Windows Machine, I suggest going to the npm website

How to convert date in to yyyy-MM-dd Format?

You can't format the Date itself. You can only get the formatted result in String. Use SimpleDateFormat as mentioned by others.

Moreover, most of the getter methods in Date are deprecated.

Java null check why use == instead of .equals()

So I never get confused and avoid problems with this solution:

if(str.trim().length() <=0 ) {
   // is null !
}

How to group subarrays by a column value?

Expanding on @baba's answer, which I like, but creates a more complex three level deep multi-dimensional (array(array(array))):

$group = array();
 foreach ( $array as $value ) {
   $group[$value['id']][] = $value; 
 }

// output only data from id 96
foreach ($group as $key=>$value) { //outer loop
 foreach ($value as $k=>$v){ //inner loop
  if($key==96){ //if outer loop is equal to 96 (could be variable)
   for ($i=0;$i<count($k);$i++){ //iterate over the inner loop
        printf($key.' has a part no. of '.$v['part_no'].' and shipping no. of '.$v['shipping_no'].'<br>');
   }
 }
}
 }

Will output:

96 has a part no. of reterty and shipping number of 212755-1

96 has a part no. of dftgtryh and shipping number of 212755-1

Passing structs to functions

It is possible to construct a struct inside the function arguments:

function({ .variable = PUT_DATA_HERE });

Encode String to UTF-8

This solved my problem

    String inputText = "some text with escaped chars"
    InputStream is = new ByteArrayInputStream(inputText.getBytes("UTF-8"));

How to convert map to url query string?

If you actually want to build a complete URI, try URIBuilder from Apache Http Compoments (HttpClient 4).

This does not actually answer the question, but it answered the one I had when I found this question.

How do I parse a string to a float or int?

>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545

Check OS version in Swift?

Swift 5

func run() {
    let version = OperatingSystemVersion(majorVersion: 13, minorVersion: 0, patchVersion: 0)
    if ProcessInfo.processInfo.isOperatingSystemAtLeast(version) {
        runNewCode()
    } else {
        runLegacyCode()
    }
}

func runNewCode() {
    guard #available(iOS 13.0, *) else {
        fatalError()
    }
    // do new stuff
}

func runLegacyCode() {
    // do old stuff
}

Rendering raw html with reactjs

I used this library called Parser. It worked for what I needed.

import React, { Component } from 'react';    
import Parser from 'html-react-parser';

class MyComponent extends Component {
  render() {
    <div>{Parser(this.state.message)}</div>
  }
};

Strings as Primary Keys in SQL Database

It doesn't matter what you use as a primary key so long as it is UNIQUE. If you care about speed or good database design use the int unless you plan on replicating data, then use a GUID.

If this is an access database or some tiny app then who really cares. I think the reason why most of us developers slap the old int or guid at the front is because projects have a way of growing on us, and you want to leave yourself the option to grow.

iPad/iPhone hover problem causes the user to double click a link

I had the following problems with the existing solutions, and found something that seems to solve all of them. This assumes you're aiming for something cross browser, cross device, and don't want device sniffing.

The problems this solves

Using just touchstart or touchend:

  • Causes the event to fire when people are trying to scroll past the content and just happened to have their finger over this element when they starting swiping - triggering the action unexpectedly.
  • May cause the event to fire on longpress, similar to right click on desktop. For example, if your click event goes to URL X, and the user longpresses to open X in a new tab, the user will be confused to find X open in both tabs. On some browsers (e.g. iPhone) it may even prevent the long press menu from appearing.

Triggering mouseover events on touchstart and mouseout on touchmove has less serious consequences, but does interfere with the usual browser behaviour, for example:

  • A long press would trigger a mouseover that never ends.
  • Many Android browsers treat the location of the finger on touchstart like a mouseover, which is mouseouted on the next touchstart. One way to see mouseover content in Android is therefore to touch the area of interest and wiggle your finger, scrolling the page slightly. Treating touchmove as mouseout breaks this.

The solution

In theory, you could just add a flag with touchmove, but iPhones trigger touchmove even if there's no movement. In theory, you could just compare the touchstart and touchend event pageX and pageY but on iPhones, there's no touchend pageX or pageY.

So unfortunately to cover all bases it does end up a little more complicated.

$el.on('touchstart', function(e){
    $el.data('tstartE', e);
    if(event.originalEvent.targetTouches){
        // store values, not reference, since touch obj will change
        var touch = e.originalEvent.targetTouches[0];
        $el.data('tstartT',{ clientX: touch.clientX, clientY: touch.clientY } );
    }
});
$el.on('touchmove', function(e){
    if(event.originalEvent.targetTouches){
        $el.data('tstartM', event.originalEvent.targetTouches[0]);
    }
});

$el.on('click touchend', function(e){
    var oldE = $el.data('tstartE');
    if( oldE && oldE.timeStamp + 1000 < e.timeStamp ) {
        $el.data('tstartE',false);
        return;
    }
    if( $el.data('iosTouchM') && $el.data('tstartT') ){
        var start = $el.data('tstartT'), end = $el.data('tstartM');
        if( start.clientX != end.clientX || start.clientY != end.clientY ){
            $el.data('tstartT', false);
            $el.data('tstartM', false);
            $el.data('tstartE',false);
            return;
        }
    }
    $el.data('tstartE',false);

In theory, there are ways to get the exact time used for a longpress instead of just using 1000 as an approximation, but in practice it's not that simple and it's best to use a reasonable proxy.

Get the filePath from Filename using Java

You may use:

FileSystems.getDefault().getPath(new String()).toAbsolutePath();

or

FileSystems.getDefault().getPath(new String("./")).toAbsolutePath().getParent()

This will give you the root folder path without using the name of the file. You can then drill down to where you want to go.

Example: /src/main/java...

Python: How to remove empty lists from a list?

I found this question because I wanted to do the same as the OP. I would like to add the following observation:

The iterative way (user225312, Sven Marnach):

list2 = [x for x in list1 if x]

Will return a list object in python3 and python2 . Instead the filter way (lunaryorn, Imran) will differently behave over versions:

list2 = filter(None, list1)

It will return a filter object in python3 and a list in python2 (see this question found at the same time). This is a slight difference but it must be take in account when developing compatible scripts.

This does not make any assumption about performances of those solutions. Anyway the filter object can be reverted to a list using:

list3 = list(list2)

Multidimensional arrays in Swift

var array: Int[][] = [[1,2,3],[4,5,6],[7,8,9]]

for first in array {
    for second in first {
        println("value \(second)")
    }
}

To achieve what you're looking for you need to initialize the array to the correct template and then loop to add the row and column arrays:

var NumColumns = 27
var NumRows = 52
var array = Array<Array<Int>>()
var value = 1

for column in 0..NumColumns {
    var columnArray = Array<Int>()
    for row in 0..NumRows {
        columnArray.append(value++)
    }
    array.append(columnArray)
}

println("array \(array)")

How do I concatenate or merge arrays in Swift?

My favorite method since Swift 2.0 is flatten

var a:[CGFloat] = [1, 2, 3]
var b:[CGFloat] = [4, 5, 6]

let c = [a, b].flatten()

This will return FlattenBidirectionalCollection so if you just want a CollectionType this will be enough and you will have lazy evaluation for free. If you need exactly the Array you can do this:

let c = Array([a, b].flatten())

How does BitLocker affect performance?

I used to use the PGP disk encryption product on a laptop (and ran NTFS compressed on top of that!). It didn't seem to have much effect if the amount of disk to be read was small; and most software sources aren't huge by disk standards.

You have lots of RAM and pretty fast processors. I spent most of my time thinking, typing or debugging.

I wouldn't worry very much about it.

Eclipse: The resource is not on the build path of a Java project

You can add the src folder to build path by:

  1. Select Java perspective.
  2. Right click on src folder.
  3. Select Build Path > Use a source folder.

And you are done. Hope this help.

EDIT: Refer to the Eclipse documentation

how to show lines in common (reverse diff)?

Found this answer on a question listed as a duplicate. I find grep to be more admin-friendly than comm, so if you just want the set of matching lines (useful for comparing CSVs, for instance) simply use

grep -F -x -f file1 file2

or the simplified fgrep version

fgrep -xf file1 file2

Plus, you can use file2* to glob and look for lines in common with multiple files, rather than just two.

Some other handy variations include

  • -n flag to show the line number of each matched line
  • -c to only count the number of lines that match
  • -v to display only the lines in file2 that differ (or use diff).

Using comm is faster, but that speed comes at the expense of having to sort your files first. It isn't very useful as a 'reverse diff'.

How to get function parameter names/values dynamically?

Taking the answer from @jack-allan I modified the function slightly to allow ES6 default properties such as:

function( a, b = 1, c ){};

to still return [ 'a', 'b' ]

/**
 * Get the keys of the paramaters of a function.
 *
 * @param {function} method  Function to get parameter keys for
 * @return {array}
 */
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var ARGUMENT_NAMES = /(?:^|,)\s*([^\s,=]+)/g;
function getFunctionParameters ( func ) {
    var fnStr = func.toString().replace(STRIP_COMMENTS, '');
    var argsList = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')'));
    var result = argsList.match( ARGUMENT_NAMES );

    if(result === null) {
        return [];
    }
    else {
        var stripped = [];
        for ( var i = 0; i < result.length; i++  ) {
            stripped.push( result[i].replace(/[\s,]/g, '') );
        }
        return stripped;
    }
}

Download Excel file via AJAX MVC

using ClosedXML.Excel;

   public ActionResult Downloadexcel()
    {   
        var Emplist = JsonConvert.SerializeObject(dbcontext.Employees.ToList());
        DataTable dt11 = (DataTable)JsonConvert.DeserializeObject(Emplist, (typeof(DataTable)));
        dt11.TableName = "Emptbl";
        FileContentResult robj;
        using (XLWorkbook wb = new XLWorkbook())
        {
            wb.Worksheets.Add(dt11);
            using (MemoryStream stream = new MemoryStream())
            {
                wb.SaveAs(stream);
                var bytesdata = File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "myFileName.xlsx");
                robj = bytesdata;
            }
        }


        return Json(robj, JsonRequestBehavior.AllowGet);
    }

Force re-download of release dependency using Maven

I just deleted my ~/.m2/repository and that forced a re-download ;)

How to get Device Information in Android

You may want to take a look at those pages : http://developer.android.com/reference/android/os/Build.html and http://developer.android.com/reference/java/lang/System.html (the getProperty() method might do the job).

For instance :

System.getProperty("os.version"); // OS version
android.os.Build.VERSION.SDK      // API Level
android.os.Build.DEVICE           // Device
android.os.Build.MODEL            // Model 
android.os.Build.PRODUCT          // Product

Etc...

Getting the encoding of a Postgres database

If you want to get database encodings:

psql  -U postgres -h somehost --list

You'll see something like:

List of databases
           Name         |  Owner   | Encoding
------------------------+----------+----------
db1                     | postgres | UTF8

How to open every file in a folder

you should try using os.walk

yourpath = 'path'

import os
for root, dirs, files in os.walk(yourpath, topdown=False):
    for name in files:
        print(os.path.join(root, name))
        stuff
    for name in dirs:
        print(os.path.join(root, name))
        stuff

Python TypeError: cannot convert the series to <class 'int'> when trying to do math on dataframe

What if you do this (as was suggested earlier):

new_time = dfs['XYF']['TimeUS'].astype(float)
new_time_F = new_time / 1000000

Oracle: what is the situation to use RAISE_APPLICATION_ERROR?

There are two uses for RAISE_APPLICATION_ERROR. The first is to replace generic Oracle exception messages with our own, more meaningful messages. The second is to create exception conditions of our own, when Oracle would not throw them.

The following procedure illustrates both usages. It enforces a business rule that new employees cannot be hired in the future. It also overrides two Oracle exceptions. One is DUP_VAL_ON_INDEX, which is thrown by a unique key on EMP(ENAME). The other is a a user-defined exception thrown when the foreign key between EMP(MGR) and EMP(EMPNO) is violated (because a manager must be an existing employee).

create or replace procedure new_emp
    ( p_name in emp.ename%type
      , p_sal in emp.sal%type
      , p_job in emp.job%type
      , p_dept in emp.deptno%type
      , p_mgr in emp.mgr%type 
      , p_hired in emp.hiredate%type := sysdate )
is
    invalid_manager exception;
    PRAGMA EXCEPTION_INIT(invalid_manager, -2291);
    dummy varchar2(1);
begin
    -- check hiredate is valid
    if trunc(p_hired) > trunc(sysdate) 
    then
        raise_application_error
            (-20000
             , 'NEW_EMP::hiredate cannot be in the future'); 
    end if;

    insert into emp
        ( ename
          , sal
          , job
          , deptno
          , mgr 
          , hiredate )
    values      
        ( p_name
          , p_sal
          , p_job
          , p_dept
          , p_mgr 
          , trunc(p_hired) );
exception
    when dup_val_on_index then
        raise_application_error
            (-20001
             , 'NEW_EMP::employee called '||p_name||' already exists'
             , true); 
    when invalid_manager then
        raise_application_error
            (-20002
             , 'NEW_EMP::'||p_mgr ||' is not a valid manager'); 

end;
/

How it looks:

SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate+1)
BEGIN new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate+1); END;

*
ERROR at line 1:
ORA-20000: NEW_EMP::hiredate cannot be in the future
ORA-06512: at "APC.NEW_EMP", line 16
ORA-06512: at line 1

SQL>
SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 8888, sysdate)
BEGIN new_emp ('DUGGAN', 2500, 'SALES', 10, 8888, sysdate); END;

*
ERROR at line 1:
ORA-20002: NEW_EMP::8888 is not a valid manager
ORA-06512: at "APC.NEW_EMP", line 42
ORA-06512: at line 1


SQL>
SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate)

PL/SQL procedure successfully completed.

SQL>
SQL> exec new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate)
BEGIN new_emp ('DUGGAN', 2500, 'SALES', 10, 7782, sysdate); END;

*
ERROR at line 1:
ORA-20001: NEW_EMP::employee called DUGGAN already exists
ORA-06512: at "APC.NEW_EMP", line 37
ORA-00001: unique constraint (APC.EMP_UK) violated
ORA-06512: at line 1

Note the different output from the two calls to RAISE_APPLICATION_ERROR in the EXCEPTIONS block. Setting the optional third argument to TRUE means RAISE_APPLICATION_ERROR includes the triggering exception in the stack, which can be useful for diagnosis.

There is more useful information in the PL/SQL User's Guide.

Psql could not connect to server: No such file or directory, 5432 error?

If non of the above answers are not working for you, then please try this one,

Many people have mentioned many solutions to this problem! But all of them forgot that, the same problem will arise when your disk don't have enough space or the space you are assigned for postgres is full

Check your system storage, if its full free up some space! then restart your postgres by sudo service postgresql restart or do a stop and start sudo service posgresql stop then sudo service postgresql start

This will solve the issue, it solved for me

An unhandled exception of type 'System.TypeInitializationException' occurred in EntityFramework.dll

In static class, if you are getting information from xml or reg, class tries to initialize all properties. therefore, you should control if the config variable is there otherwise properties will not initialize so the class.

Check xml referance variable is there, Check reg referance variable is is there, Make sure you handle if they are not there.

PostgreSQL return result set as JSON array?

TL;DR

SELECT json_agg(t) FROM t

for a JSON array of objects, and

SELECT
    json_build_object(
        'a', json_agg(t.a),
        'b', json_agg(t.b)
    )
FROM t

for a JSON object of arrays.

List of objects

This section describes how to generate a JSON array of objects, with each row being converted to a single object. The result looks like this:

[{"a":1,"b":"value1"},{"a":2,"b":"value2"},{"a":3,"b":"value3"}]

9.3 and up

The json_agg function produces this result out of the box. It automatically figures out how to convert its input into JSON and aggregates it into an array.

SELECT json_agg(t) FROM t

There is no jsonb (introduced in 9.4) version of json_agg. You can either aggregate the rows into an array and then convert them:

SELECT to_jsonb(array_agg(t)) FROM t

or combine json_agg with a cast:

SELECT json_agg(t)::jsonb FROM t

My testing suggests that aggregating them into an array first is a little faster. I suspect that this is because the cast has to parse the entire JSON result.

9.2

9.2 does not have the json_agg or to_json functions, so you need to use the older array_to_json:

SELECT array_to_json(array_agg(t)) FROM t

You can optionally include a row_to_json call in the query:

SELECT array_to_json(array_agg(row_to_json(t))) FROM t

This converts each row to a JSON object, aggregates the JSON objects as an array, and then converts the array to a JSON array.

I wasn't able to discern any significant performance difference between the two.

Object of lists

This section describes how to generate a JSON object, with each key being a column in the table and each value being an array of the values of the column. It's the result that looks like this:

{"a":[1,2,3], "b":["value1","value2","value3"]}

9.5 and up

We can leverage the json_build_object function:

SELECT
    json_build_object(
        'a', json_agg(t.a),
        'b', json_agg(t.b)
    )
FROM t

You can also aggregate the columns, creating a single row, and then convert that into an object:

SELECT to_json(r)
FROM (
    SELECT
        json_agg(t.a) AS a,
        json_agg(t.b) AS b
    FROM t
) r

Note that aliasing the arrays is absolutely required to ensure that the object has the desired names.

Which one is clearer is a matter of opinion. If using the json_build_object function, I highly recommend putting one key/value pair on a line to improve readability.

You could also use array_agg in place of json_agg, but my testing indicates that json_agg is slightly faster.

There is no jsonb version of the json_build_object function. You can aggregate into a single row and convert:

SELECT to_jsonb(r)
FROM (
    SELECT
        array_agg(t.a) AS a,
        array_agg(t.b) AS b
    FROM t
) r

Unlike the other queries for this kind of result, array_agg seems to be a little faster when using to_jsonb. I suspect this is due to overhead parsing and validating the JSON result of json_agg.

Or you can use an explicit cast:

SELECT
    json_build_object(
        'a', json_agg(t.a),
        'b', json_agg(t.b)
    )::jsonb
FROM t

The to_jsonb version allows you to avoid the cast and is faster, according to my testing; again, I suspect this is due to overhead of parsing and validating the result.

9.4 and 9.3

The json_build_object function was new to 9.5, so you have to aggregate and convert to an object in previous versions:

SELECT to_json(r)
FROM (
    SELECT
        json_agg(t.a) AS a,
        json_agg(t.b) AS b
    FROM t
) r

or

SELECT to_jsonb(r)
FROM (
    SELECT
        array_agg(t.a) AS a,
        array_agg(t.b) AS b
    FROM t
) r

depending on whether you want json or jsonb.

(9.3 does not have jsonb.)

9.2

In 9.2, not even to_json exists. You must use row_to_json:

SELECT row_to_json(r)
FROM (
    SELECT
        array_agg(t.a) AS a,
        array_agg(t.b) AS b
    FROM t
) r

Documentation

Find the documentation for the JSON functions in JSON functions.

json_agg is on the aggregate functions page.

Design

If performance is important, ensure you benchmark your queries against your own schema and data, rather than trust my testing.

Whether it's a good design or not really depends on your specific application. In terms of maintainability, I don't see any particular problem. It simplifies your app code and means there's less to maintain in that portion of the app. If PG can give you exactly the result you need out of the box, the only reason I can think of to not use it would be performance considerations. Don't reinvent the wheel and all.

Nulls

Aggregate functions typically give back NULL when they operate over zero rows. If this is a possibility, you might want to use COALESCE to avoid them. A couple of examples:

SELECT COALESCE(json_agg(t), '[]'::json) FROM t

Or

SELECT to_jsonb(COALESCE(array_agg(t), ARRAY[]::t[])) FROM t

Credit to Hannes Landeholm for pointing this out

Unit testing click event in Angular

I'm using Angular 6. I followed Mav55's answer and it worked. However I wanted to make sure if fixture.detectChanges(); was really necessary so I removed it and it still worked. Then I removed tick(); to see if it worked and it did. Finally I removed the test from the fakeAsync() wrap, and surprise, it worked.

So I ended up with this:

it('should call onClick method', () => {
  const onClickMock = spyOn(component, 'onClick');
  fixture.debugElement.query(By.css('button')).triggerEventHandler('click', null);
  expect(onClickMock).toHaveBeenCalled();
});

And it worked just fine.

Identifying Exception Type in a handler Catch Block

you can add some extra information to your exception in your class and then when you catch the exception you can control your custom information to identify your exception

this.Data["mykey"]="keyvalue"; //you can add any type of data if you want 

and then you can get your value

string mystr = (string) err.Data["mykey"];

like that for more information: http://msdn.microsoft.com/en-us/library/system.exception.data.aspx

Insert value into a string at a certain position?

You can't modify strings; they're immutable. You can do this instead:

txtBox.Text = txtBox.Text.Substring(0, i) + "TEXT" + txtBox.Text.Substring(i);

The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application

I have removed the scope and then used a maven update to solve this problem.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
    **<!-- <scope>provided</scope> -->**
</dependency>

The jstl lib is not present in the tomcat lib folder.So we have to include it. I don't understand why we are told to keep both servlet-api and jstl's scope as provided.