Programs & Examples On #Reduce reduce conflict

Python: Removing spaces from list objects

List comprehension [num.strip() for num in hello] is the fastest.

>>> import timeit
>>> hello = ['999 ',' 666 ']

>>> t1 = lambda: map(str.strip, hello)
>>> timeit.timeit(t1)
1.825870468015296

>>> t2 = lambda: list(map(str.strip, hello))
>>> timeit.timeit(t2)
2.2825958750515269

>>> t3 = lambda: [num.strip() for num in hello]
>>> timeit.timeit(t3)
1.4320335103944899

>>> t4 = lambda: [num.replace(' ', '') for num in hello]
>>> timeit.timeit(t4)
1.7670568718943969

Can't access Tomcat using IP address

New versions of application servers removed the ability of binding to your entire network interface and limited it just to the local interface (localhost). The reason being was for security. From what I know, Tomcat and JBoss implement the same security measures.

If you want to bind it to another IP you can explicitly set it in your connector string:

  • Tomcat: address="192.168.1.100"
  • JBoss: you pass in a -b 192.168.1.100 as a command line.

Just remember that binding 0.0.0.0 allows anyone access to your box to access that server. It will bind to all addresses. If that is what you want, then use 0.0.0.0, if it isn't then specify the address you would like to explicitly bind instead.

Just make sure you understand the consequences binding to all addresses (0.0.0.0)

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

Enable Multidex through build.gradle of your app module

multiDexEnabled true

Same as below -

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

Then follow below steps -

  1. From the Build menu -> press the Clean Project button.
  2. When task completed, press the Rebuild Project button from the Build menu.
  3. From menu File -> Invalidate cashes / Restart

compile is now deprecated so it's better to use implementation or api

python ValueError: invalid literal for float()

I would all but guarantee that the issue is some sort of non-printing character that's present in the value you pulled off your socket. It looks like you're using Python 2.x, in which case you can check for them with this:

print repr(temp)

You'll likely see something in there that's escaped in the form \x00. These non-printing characters don't show up when you print directly to the console, but their presence is enough to negatively impact the parsing of a string value into a float.

-- Edited for question changes --

It turns this is partly accurate for your issue - the root cause however appears to be that you're reading more information than you expect from your socket or otherwise receiving multiple values. You could do something like

map(float, temp.strip().split('\r\n'))

In order to convert each of the values, but if your function is supposed to return a single float value this is likely to cause confusion. Anyway, the issue certainly revolves around the presence of characters you did not expect to see in the value you retrieved from your socket.

How do I add a user when I'm using Alpine as a base image?

Alpine uses the command adduser and addgroup for creating users and groups (rather than useradd and usergroup).

FROM alpine:latest

# Create a group and user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup

# Tell docker that all future commands should run as the appuser user
USER appuser

The flags for adduser are:

Usage: adduser [OPTIONS] USER [GROUP]

Create new user, or add USER to GROUP

        -h DIR          Home directory
        -g GECOS        GECOS field
        -s SHELL        Login shell
        -G GRP          Group
        -S              Create a system user
        -D              Don't assign a password
        -H              Don't create home directory
        -u UID          User id
        -k SKEL         Skeleton directory (/etc/skel)

Add new user official docs

How can I initialize an array without knowing it size?

Here is the code for you`r class . but this also contains lot of refactoring. Please add a for each rather than for. cheers :)

 static int isLeft(ArrayList<String> left, ArrayList<String> right)

    {
        int f = 0;
        for (int i = 0; i < left.size(); i++) {
            for (int j = 0; j < right.size(); j++)

            {
                if (left.get(i).charAt(0) == right.get(j).charAt(0)) {
                    System.out.println("Grammar is left recursive");
                    f = 1;
                }

            }
        }
        return f;

    }

    public static void main(String[] args) {
        // TODO code application logic here
        ArrayList<String> left = new ArrayList<String>();
        ArrayList<String> right = new ArrayList<String>();


        Scanner sc = new Scanner(System.in);
        System.out.println("enter no of prod");
        int n = sc.nextInt();
        for (int i = 0; i < n; i++) {
            System.out.println("enter left prod");
            String leftText = sc.next();
            left.add(leftText);
            System.out.println("enter right prod");
            String rightText = sc.next();
            right.add(rightText);
        }

        System.out.println("the productions are");
        for (int i = 0; i < n; i++) {
            System.out.println(left.get(i) + "->" + right.get(i));
        }
        int flag;
        flag = isLeft(left, right);
        if (flag == 1) {
            System.out.println("Removing left recursion");
        } else {
            System.out.println("No left recursion");
        }

    }

What is the difference between canonical name, simple name and class name in Java Class?

If you're unsure about something, try writing a test first.

I did this:

class ClassNameTest {
    public static void main(final String... arguments) {
        printNamesForClass(
            int.class,
            "int.class (primitive)");
        printNamesForClass(
            String.class,
            "String.class (ordinary class)");
        printNamesForClass(
            java.util.HashMap.SimpleEntry.class,
            "java.util.HashMap.SimpleEntry.class (nested class)");
        printNamesForClass(
            new java.io.Serializable(){}.getClass(),
            "new java.io.Serializable(){}.getClass() (anonymous inner class)");
    }

    private static void printNamesForClass(final Class<?> clazz, final String label) {
        System.out.println(label + ":");
        System.out.println("    getName():          " + clazz.getName());
        System.out.println("    getCanonicalName(): " + clazz.getCanonicalName());
        System.out.println("    getSimpleName():    " + clazz.getSimpleName());
        System.out.println("    getTypeName():      " + clazz.getTypeName()); // added in Java 8
        System.out.println();
    }
}

Prints:

int.class (primitive):
    getName():          int
    getCanonicalName(): int
    getSimpleName():    int
    getTypeName():      int

String.class (ordinary class):
    getName():          java.lang.String
    getCanonicalName(): java.lang.String
    getSimpleName():    String
    getTypeName():      java.lang.String

java.util.HashMap.SimpleEntry.class (nested class):
    getName():          java.util.AbstractMap$SimpleEntry
    getCanonicalName(): java.util.AbstractMap.SimpleEntry
    getSimpleName():    SimpleEntry
    getTypeName():      java.util.AbstractMap$SimpleEntry

new java.io.Serializable(){}.getClass() (anonymous inner class):
    getName():          ClassNameTest$1
    getCanonicalName(): null
    getSimpleName():    
    getTypeName():      ClassNameTest$1

There's an empty entry in the last block where getSimpleName returns an empty string.

The upshot looking at this is:

  • the name is the name that you'd use to dynamically load the class with, for example, a call to Class.forName with the default ClassLoader. Within the scope of a certain ClassLoader, all classes have unique names.
  • the canonical name is the name that would be used in an import statement. It might be useful during toString or logging operations. When the javac compiler has complete view of a classpath, it enforces uniqueness of canonical names within it by clashing fully qualified class and package names at compile time. However JVMs must accept such name clashes, and thus canonical names do not uniquely identify classes within a ClassLoader. (In hindsight, a better name for this getter would have been getJavaName; but this method dates from a time when the JVM was used solely to run Java programs.)
  • the simple name loosely identifies the class, again might be useful during toString or logging operations but is not guaranteed to be unique.
  • the type name returns "an informative string for the name of this type", "It's like toString: it's purely informative and has no contract value". (as written by sir4ur0n)

Docker-compose: node_modules not present in a volume after npm install succeeds

You can try something like this in your Dockerfile:

FROM node:0.12
WORKDIR /worker
CMD bash ./start.sh

Then you should use the Volume like this:

volumes:
  - worker/:/worker:rw

The startscript should be a part of your worker repository and looks like this:

#!/bin/sh
npm install
npm start

So the node_modules are a part of your worker volume and gets synchronized and the npm scripts are executed when everything is up.

Error while inserting date - Incorrect date value:

You need to convert the date to YYYY-MM-DD in order to insert it as a MySQL date using the default configuration.

One way to do that is STR_TO_DATE():

insert into your_table (...)
values (...,str_to_date('07-25-2012','%m-%d-%Y'),...);

The database cannot be opened because it is version 782. This server supports version 706 and earlier. A downgrade path is not supported

Try changing Tools > Options > Database Tools > Data Connections > SQL Server Instance Name.

The default for VS2013 is (LocalDB)\v11.0.

Changing to (LocalDB)\MSSQLLocalDB, for example, seems to work - no more version 782 error.

How to "grep" out specific line ranges of a file

The following command will do what you asked for "extract the lines between 1234 and 5555" in someFile.

sed -n '1234,5555p' someFile

How to use regex with find command?

on Mac OS X (BSD find): Same as accepted answer, the .*/ prefix is needed to match a complete path:

$ find -E . -regex ".*/[a-f0-9\-]{36}.jpg"

man find says -E uses extended regex support

Getting "Skipping JaCoCo execution due to missing execution data file" upon executing JaCoCo

jacoco-maven-plugin:0.7.10-SNAPSHOT

From jacoco:prepare-agent that says:

One of the ways to do this in case of maven-surefire-plugin - is to use syntax for late property evaluation:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <configuration>
    <argLine>@{argLine} -your -extra -arguments</argLine>
  </configuration>
</plugin>

Note the @{argLine} that's added to -your -extra -arguments.

Thanks Slava Semushin for noticing the change and reporting in the comment.

jacoco-maven-plugin:0.7.2-SNAPSHOT

Following jacoco:prepare-agent that says:

[org.jacoco:jacoco-maven-plugin:0.7.2-SNAPSHOT:prepare-agent] Prepares a property pointing to the JaCoCo runtime agent that can be passed as a VM argument to the application under test. Depending on the project packaging type by default a property with the following name is set:

  • tycho.testArgLine for packaging type eclipse-test-plugin and
  • argLine otherwise.

Note that these properties must not be overwritten by the test configuration, otherwise the JaCoCo agent cannot be attached. If you need custom parameters please append them. For example:

<argLine>${argLine} -your -extra -arguments</argLine>

Resulting coverage information is collected during execution and by default written to a file when the process terminates.

you should change the following line in maven-surefire-plugin plugin configuration from (note the ${argLine} inside <argLine>):

<argLine>-Xmx2048m</argLine>

to

<argLine>${argLine} -Xmx2048m</argLine>

Make also the necessary changes to the other plugin maven-failsafe-plugin and replace the following (again, notice the ${argLine}):

<argLine>-Xmx4096m -XX:MaxPermSize=512M ${itCoverageAgent}</argLine>

to

<argLine>${argLine} -Xmx4096m -XX:MaxPermSize=512M ${itCoverageAgent}</argLine>

How to only get file name with Linux 'find'?

As others have pointed out, you can combine find and basename, but by default the basename program will only operate on one path at a time, so the executable will have to be launched once for each path (using either find ... -exec or find ... | xargs -n 1), which may potentially be slow.

If you use the -a option on basename, then it can accept multiple filenames in a single invocation, which means that you can then use xargs without the -n 1, to group the paths together into a far smaller number of invocations of basename, which should be more efficient.

Example:

find /dir1 -type f -print0 | xargs -0 basename -a

Here I've included the -print0 and -0 (which should be used together), in order to cope with any whitespace inside the names of files and directories.

Here is a timing comparison, between the xargs basename -a and xargs -n1 basename versions. (For sake of a like-with-like comparison, the timings reported here are after an initial dummy run, so that they are both done after the file metadata has already been copied to I/O cache.) I have piped the output to cksum in both cases, just to demonstrate that the output is independent of the method used.

$ time sh -c 'find /usr/lib -type f -print0 | xargs -0 basename -a | cksum'
2532163462 546663

real    0m0.063s
user    0m0.058s
sys 0m0.040s

$ time sh -c 'find /usr/lib -type f -print0 | xargs -0 -n 1 basename | cksum' 
2532163462 546663

real    0m14.504s
user    0m12.474s
sys 0m3.109s

As you can see, it really is substantially faster to avoid launching basename every time.

How to retrieve checkboxes values in jQuery

The following may be useful since I got here looking for a slightly different solution. My script needed to automatically loop through input elements and had to return their values (for jQuery.post() function), the problem was with checkboxes returning their values regardless of checked status. This was my solution:

jQuery.fn.input_val = function(){

    if(jQuery(this).is("input[type=checkbox]")) {
        if(jQuery(this).is(":checked")) {
            return jQuery(this).val();
        } else {
            return false;
        }
    } else {
        return jQuery(this).val();
    }
};

Usage:

jQuery(".element").input_val();

If the given input field is a checkbox, the input_val function only returns a value if its checked. For all other elements, the value is returned regardless of checked status.

How to convert JSONObjects to JSONArray?

Something like this:

JSONObject songs= json.getJSONObject("songs");
Iterator x = songs.keys();
JSONArray jsonArray = new JSONArray();

while (x.hasNext()){
    String key = (String) x.next();
    jsonArray.put(songs.get(key));
}

How to use MySQL DECIMAL?

MySQL 5.x specification for decimal datatype is: DECIMAL[(M[,D])] [UNSIGNED] [ZEROFILL]. The answer above is wrong (now corrected) in saying that unsigned decimals are not possible.

To define a field allowing only unsigned decimals, with a total length of 6 digits, 4 of which are decimals, you would use: DECIMAL (6,4) UNSIGNED.

You can likewise create unsigned (ie. not negative) FLOAT and DOUBLE datatypes.


Update on MySQL 8.0.17+, as in MySQL 8 Manual: 11.1.1 Numeric Data Type Syntax:

"Numeric data types that permit the UNSIGNED attribute also permit SIGNED. However, these data types are signed by default, so the SIGNED attribute has no effect.*

As of MySQL 8.0.17, the UNSIGNED attribute is deprecated for columns of type FLOAT, DOUBLE, and DECIMAL (and any synonyms); you should expect support for it to be removed in a future version of MySQL. Consider using a simple CHECK constraint instead for such columns.

Allowing Java to use an untrusted certificate for SSL/HTTPS connection

Here is some relevant code:

// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{
    new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public void checkClientTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
        public void checkServerTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
    }
};

// Install the all-trusting trust manager
try {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}

// Now you can access an https URL without having the certificate in the truststore
try {
    URL url = new URL("https://hostname/index.html");
} catch (MalformedURLException e) {
}

This will completely disable SSL checking—just don't learn exception handling from such code!

To do what you want, you would have to implement a check in your TrustManager that prompts the user.

sql ORDER BY multiple values in specific order?

...
WHERE
   x_field IN ('f', 'p', 'i', 'a') ...
ORDER BY
   CASE x_field
      WHEN 'f' THEN 1
      WHEN 'p' THEN 2
      WHEN 'i' THEN 3
      WHEN 'a' THEN 4
      ELSE 5 --needed only is no IN clause above. eg when = 'b'
   END, id

How to access a preexisting collection with Mongoose?

Mongoose added the ability to specify the collection name under the schema, or as the third argument when declaring the model. Otherwise it will use the pluralized version given by the name you map to the model.

Try something like the following, either schema-mapped:

new Schema({ url: String, text: String, id: Number}, 
           { collection : 'question' });   // collection name

or model mapped:

mongoose.model('Question', 
               new Schema({ url: String, text: String, id: Number}), 
               'question');     // collection name

Python circular importing?

I was able to import the module within the function (only) that would require the objects from this module:

def my_func():
    import Foo
    foo_instance = Foo()

SQL Server - In clause with a declared variable

You need to execute this as a dynamic sp like

DECLARE @ExcludedList VARCHAR(MAX)

SET @ExcludedList = '3,4,22,6014'
declare @sql nvarchar(Max)

Set @sql='SELECT * FROM [A] WHERE Id NOT IN ('+@ExcludedList+')'

exec sp_executesql @sql

How do I run a Java program from the command line on Windows?

Since Java 11, java command line tool has been able to run a single-file source-code directly. e.g.

java HelloWorld.java

This was an enhancement with JEP 330: https://openjdk.java.net/jeps/330

For the details of the usage and the limitations, see the manual of your Java implementation such as one provided by Oracle: https://docs.oracle.com/en/java/javase/11/tools/java.html

How to echo text during SQL script execution in SQLPLUS

You can change the name of the column, therefore instead of "COUNT(*)" you would have something meaningful. You will have to update your "RowCount.sql" script for that.

For example:

SQL> select count(*) as RecordCountFromTableOne from TableOne;

Will be displayed as:

RecordCountFromTableOne
-----------------------
           0

If you want to have space in the title, you need to enclose it in double quotes

SQL> select count(*) as "Record Count From Table One" from TableOne;

Will be displayed as:

Record Count From Table One
---------------------------
            0

Angular2 router (@angular/router), how to set default route?

The path should be left blank to make it default component.

{ path: '', component: DashboardComponent },

Understanding REST: Verbs, error codes, and authentication

About REST return codes: it is wrong to mix HTTP protocol codes and REST results.

However, I saw many implementations mixing them, and many developers may not agree with me.

HTTP return codes are related to the HTTP Request itself. A REST call is done using a Hypertext Transfer Protocol request and it works at a lower level than invoked REST method itself. REST is a concept/approach, and its output is a business/logical result, while HTTP result code is a transport one.

For example, returning "404 Not found" when you call /users/ is confuse, because it may mean:

  • URI is wrong (HTTP)
  • No users are found (REST)

"403 Forbidden/Access Denied" may mean:

  • Special permission needed. Browsers can handle it by asking the user/password. (HTTP)
  • Wrong access permissions configured on the server. (HTTP)
  • You need to be authenticated (REST)

And the list may continue with '500 Server error" (an Apache/Nginx HTTP thrown error or a business constraint error in REST) or other HTTP errors etc...

From the code, it's hard to understand what was the failure reason, a HTTP (transport) failure or a REST (logical) failure.

If the HTTP request physically was performed successfully it should always return 200 code, regardless is the record(s) found or not. Because URI resource is found and was handled by the http server. Yes, it may return an empty set. Is it possible to receive an empty web-page with 200 as http result, right?

Instead of this you may return 200 HTTP code and simply a JSON with an empty array/object, or to use a bool result/success flag to inform about the performed operation status.

Also, some internet providers may intercept your requests and return you a 404 http code. This does not means that your data are not found, but it's something wrong at transport level.

From Wiki:

In July 2004, the UK telecom provider BT Group deployed the Cleanfeed content blocking system, which returns a 404 error to any request for content identified as potentially illegal by the Internet Watch Foundation. Other ISPs return a HTTP 403 "forbidden" error in the same circumstances. The practice of employing fake 404 errors as a means to conceal censorship has also been reported in Thailand and Tunisia. In Tunisia, where censorship was severe before the 2011 revolution, people became aware of the nature of the fake 404 errors and created an imaginary character named "Ammar 404" who represents "the invisible censor".

TensorFlow not found using pip

2.0 COMPATIBLE SOLUTION:

Execute the below commands in Terminal (Linux/MacOS) or in Command Prompt (Windows) to install Tensorflow 2.0 using Pip:

#Install tensorflow using pip virtual env 
pip install virtualenv
virtualenv tf_2.0.0   # tf_2.0.0 is virtual env name
source tf_2.0.0/bin/activate
#You should see tf_2.0.0 Env now. Execute the below steps
pip install tensorflow==2.0.0
python
>>import tensorflow as tf
>>tf.__version__
2.0.0

Execute the below commands in Terminal (Linux/MacOS) or in Command Prompt (Windows) to install Tensorflow 2.0 using Bazel:

git clone https://github.com/tensorflow/tensorflow.git
cd tensorflow

#The repo defaults to the master development branch. You can also checkout a release branch to build:
git checkout r2.0

#Configure the Build => Use the Below line for Windows Machine
python ./configure.py 

#Configure the Build => Use the Below line for Linux/MacOS Machine
./configure
#This script prompts you for the location of TensorFlow dependencies and asks for additional build configuration options. 

#Build Tensorflow package

#CPU support
bazel build --config=opt //tensorflow/tools/pip_package:build_pip_package 

#GPU support
bazel build --config=opt --config=cuda --define=no_tensorflow_py_deps=true //tensorflow/tools/pip_package:build_pip_package

How to change facet labels?

I have another way to achieve the same goal without changing the underlying data:

ggplot(transform(survey, survey = factor(survey,
        labels = c("Hosp 1", "Hosp 2", "Hosp 3", "Hosp 4"))), aes(x = age)) +
  stat_bin(aes(n = nrow(h3),y=..count../n), binwidth = 10) +
  scale_y_continuous(formatter = "percent", breaks = c(0, 0.1, 0.2)) +
  facet_grid(hospital ~ .) +
  opts(panel.background = theme_blank())

What I did above is changing the labels of the factor in the original data frame, and that is the only difference compared with your original code.

The maximum recursion 100 has been exhausted before statement completion

it is just a sample to avoid max recursion error. we have to use option (maxrecursion 365); or option (maxrecursion 0);

DECLARE @STARTDATE datetime; 
DECLARE @EntDt datetime; 
set @STARTDATE = '01/01/2009';  
set @EntDt = '12/31/2009'; 
declare @dcnt int; 
;with DateList as   
 (   
    select @STARTDATE DateValue   
    union all   
    select DateValue + 1 from    DateList      
    where   DateValue + 1 < convert(VARCHAR(15),@EntDt,101)   
 )   
  select count(*) as DayCnt from (   
  select DateValue,DATENAME(WEEKDAY, DateValue ) as WEEKDAY from DateList
  where DATENAME(WEEKDAY, DateValue ) not IN ( 'Saturday','Sunday' )     
  )a
option (maxrecursion 365);

How to update /etc/hosts file in Docker image during "docker build"

With a more recent version of docker, this could be done with docker-compose and its extra_hosts directive

Add hostname mappings.
Use the same values as the docker run client --add-host parameter (which should already be available for docker 1.8).

extra_hosts:
 - "somehost:162.242.195.82"
 - "otherhost:50.31.209.229"

In short: modify /etc/hosts of your container when running it, instead of when building it.


With Docker 17.x+, you have a docker build --add-host mentioned below, but, as commented in issue 34078 and in this answer:

The --add-host feature during build is designed to allow overriding a host during build, but not to persist that configuration in the image.

The solutions mentioned do refer the docker-compose I was suggesting above:

  • Run an internal DNS; you can set the default DNS server to use in the daemon; that way every container started will automatically use the configured DNS by default
  • Use docker compose and provide a docker-compose.yml to your developers.
    The docker compose file allows you to specify all the options that should be used when starting a container, so developers could just docker compose up to start the container with all the options they need to set.

Is there a CSS parent selector?

Try this...

This solution uses plain CSS1 with no Javascript and works in all browsers, old and new. When clicked, the child anchor tag activates its active pseudo-class event. It then simply hides itself, allowing the active event to bubble up to the parent li tag who then restyles himself and reveals his anchor child again with a new style. The child has styled the parent.

Using your example:

<ul>
    <li class="listitem">
        <a class="link" href="#">This is a Link</a>
    </li>
</ul>

Now apply these styles with the active pseudo-class on a to restyle the parent li tag when the link is clicked:

a.link {
    display: inline-block;
    color: white;
    background-color: green;
    text-decoration: none;
    padding: 5px;
}

li.listitem {
    display: inline-block;
    margin: 0;
    padding: 0;
    background-color: transparent;
}

/* When this 'active' pseudo-class event below fires on click, it hides itself,
triggering the active event again on its parent which applies new styles to itself and its child. */

a.link:active {
    display: none;
}

.listitem:active {
    background-color: blue;
}

.listitem:active a.link {
    display: inline-block;
    background-color: transparent;
}

You should see the link with a green background now change to the list item's blue background on click.

enter image description here

turns to

enter image description here

on click.

how to find seconds since 1970 in java

Since Java8:

java.time.Instant.now().getEpochSecond()

Regular expression to limit number of characters to 10

It might be beneficial to add greedy matching to the end of the string, so you can accept strings > than 10 and the regex will only return up to the first 10 chars. /^[a-z0-9]{0,10}$?/

Floating elements within a div, floats outside of div. Why?

As Lucas says, what you are describing is the intended behaviour for the float property. What confuses many people is that float has been pushed well beyond its original intended usage in order to make up for shortcomings in the CSS layout model.

Have a look at Floatutorial if you'd like to get a better understanding of how this property works.

Can a constructor in Java be private?

Yes, a constructor can be private. There are different uses of this. One such use is for the singleton design anti-pattern, which I would advise against you using. Another, more legitimate use, is in delegating constructors; you can have one constructor that takes lots of different options that is really an implementation detail, so you make it private, but then your remaining constructors delegate to it.

As an example of delegating constructors, the following class allows you to save a value and a type, but it only lets you do it for a subset of types, so making the general constructor private is needed to ensure that only the permitted types are used. The common private constructor helps code reuse.

public class MyClass {
     private final String value;
     private final String type;

     public MyClass(int x){
         this(Integer.toString(x), "int");
     }

     public MyClass(boolean x){
         this(Boolean.toString(x), "boolean");
     }

     public String toString(){
         return value;
     }

     public String getType(){
         return type;
     }

     private MyClass(String value, String type){
         this.value = value;
         this.type = type;
     }
}

Edit
Looking at this answer from several years later, I would like to note that this answer is both incomplete and also a little bit extreme. Singletons are indeed an anti-pattern and should generally be avoided where possible; however, there are many uses of private constructors besides singletons, and my answer names only one.

To give a couple more cases where private constructors are used:

  1. To create an uninstantiable class that is just a collection of related static functions (this is basically a singleton, but if it is stateless and the static functions operate strictly on the parameters rather than on class state, this is not as unreasonable an approach as my earlier self would seem to suggest, though using an interface that is dependency injected often makes it easier to maintain the API when the implementation requires larger numbers of dependencies or other forms of context).

  2. When there are multiple different ways to create the object, a private constructor may make it easier to understand the different ways of constructing it (e.g., which is more readable to you new ArrayList(5) or ArrayList.createWithCapacity(5), ArrayList.createWithContents(5), ArrayList.createWithInitialSize(5)). In other words, a private constructor allows you to provide factory function's whose names are more understandable, and then making the constructor private ensures that people use only the more self-evident names. This is also commonly used with the builder pattern. For example:

    MyClass myVar = MyClass
        .newBuilder()
        .setOption1(option1)
        .setOption2(option2)
        .build();
    

Getting request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

Basically, to make a cross domain AJAX requests, the requested server should allow the cross origin sharing of resources (CORS). You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/

In your scenario, you are setting the headers in the client which in fact needs to be set into http://localhost:8080/app server side code.

If you are using PHP Apache server, then you will need to add following in your .htaccess file:

Header set Access-Control-Allow-Origin "*"

C# switch on type

I have used this form of switch-case on rare occasion. Even then I have found another way to do what I wanted. If you find that this is the only way to accomplish what you need, I would recommend @Mark H's solution.

If this is intended to be a sort of factory creation decision process, there are better ways to do it. Otherwise, I really can't see why you want to use the switch on a type.

Here is a little example expanding on Mark's solution. I think it is a great way to work with types:

Dictionary<Type, Action> typeTests;

public ClassCtor()
{
    typeTests = new Dictionary<Type, Action> ();

    typeTests[typeof(int)] = () => DoIntegerStuff();
    typeTests[typeof(string)] = () => DoStringStuff();
    typeTests[typeof(bool)] = () => DoBooleanStuff();
}

private void DoBooleanStuff()
{
   //do stuff
}

private void DoStringStuff()
{
    //do stuff
}

private void DoIntegerStuff()
{
    //do stuff
}

public Action CheckTypeAction(Type TypeToTest)
{
    if (typeTests.Keys.Contains(TypeToTest))
        return typeTests[TypeToTest];

    return null; // or some other Action delegate
}

SQLite: How do I save the result of a query as a CSV file?

All the existing answers only work from the sqlite command line, which isn't ideal if you'd like to build a reusable script. Python makes it easy to build a script that can be executed programatically.

import pandas as pd
import sqlite3

conn = sqlite3.connect('your_cool_database.sqlite')

df = pd.read_sql('SELECT * from orders', conn)
df.to_csv('orders.csv', index = False)

You can customize the query to only export part of the sqlite table to the CSV file.

You can also run a single command to export all sqlite tables to CSV files:

for table in c.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall():
    t = table[0]
    df = pd.read_sql('SELECT * from ' + t, conn)
    df.to_csv(t + '_one_command.csv', index = False)

See here for more info.

How to get the name of the current Windows user in JavaScript

JavaScript runs in the context of the current HTML document, so it won't be able to determine anything about a current user unless it's in the current page or you do AJAX calls to a server-side script to get more information.

JavaScript will not be able to determine your Windows user name.

Does WGET timeout?

The default timeout is 900 second. You can specify different timeout.

-T seconds
--timeout=seconds

The default is to retry 20 times. You can specify different tries.

-t number
--tries=number

link: wget man document

Where can I find the default timeout settings for all browsers?

firstly I don't think there is just one solution to your problem....

As you know each browser is vastly differant.

But lets see if we can get any closer to the answer you need....

I think IE Might be easy...

Check this link http://support.microsoft.com/kb/181050

For Firefox try this:

Open Firefox, and in the address bar, type "about:config" (without quotes). From there, scroll down to the Network.http.keep-alive and make sure that is set to "true". If it is not, double click it, and it will go from false to true. Now, go one below that to network.http.keep-alive.timeout -- and change that number by double clicking it. if you put in, say, 500 there, you should be good. let us know if this helps at all

Bootstrap modal: close current, open new

I might be a bit late to this but I think I've found working solution.

Required -

jQuery

All modals with a closing/dismissal button having attributes set as follows -

<button type="button" class="btn close_modal" data-toggle="modal" data-target="#Modal">Close</button>  

Please see the class close_modal added to the button's classes

Now to close all existing modals, we'll call

$(".close_modal").trigger("click");

So, wherever you want to open a modal

Just add the above code and your all open modals shall get closed.

Then add your normal code to open the desired modal

$("#DesiredModal").modal();

Create Windows service from executable

these extras prove useful.. need to be executed as an administrator

sc create  <service_name> binpath=<binary_path>
sc stop    <service_name>
sc queryex <service_name>
sc delete  <service_name>

If your service name has any spaces, enclose in "quotes".

Why does using from __future__ import print_function breaks Python2-style print?

First of all, from __future__ import print_function needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print as a function now. That's the whole point of from __future__ import print_function; to bring the print function from Python 3 into Python 2.6+.

from __future__ import print_function

import sys, os, time

for x in range(0,10):
    print(x, sep=' ', end='')  # No need for sep here, but okay :)
    time.sleep(1)

__future__ statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

The documentation also mentions that the only things that can precede a __future__ statement are the module docstring, comments, blank lines, and other future statements.

Python lookup hostname from IP with 1 second timeout

What you're trying to accomplish is called Reverse DNS lookup.

socket.gethostbyaddr("IP") 
# => (hostname, alias-list, IP)

http://docs.python.org/library/socket.html?highlight=gethostbyaddr#socket.gethostbyaddr

However, for the timeout part I have read about people running into problems with this. I would check out PyDNS or this solution for more advanced treatment.

How to create a dynamic array of integers

dynamically allocate some memory using new:

int* array = new int[SIZE];

How to unstash only certain files?

First list all the stashes

git stash list

?

stash@{0}: WIP on Produktkonfigurator: 132c06a5 Cursor bei glyphicon plus und close zu zeigende Hand ändern
stash@{1}: WIP on Produktkonfigurator: 132c06a5 Cursor bei glyphicon plus und close zu zeigende Hand ändern
stash@{2}: WIP on master: 7e450c81 Merge branch 'Offlineseite'

Then show which files are in the stash (lets pick stash 1):

git stash show 1 --name-only

//Hint: you can also write
//git stash show stash@{1} --name-only

?

 ajax/product.php
 ajax/productPrice.php
 errors/Company/js/offlineMain.phtml
 errors/Company/mage.php
 errors/Company/page.phtml
 js/konfigurator/konfigurator.js

Then apply the file you like to:

git checkout stash@{1} -- <filename>

or whole folder:

git checkout stash@{1} /errors

It also works without -- but it is recommended to use them. See this post.

It is also conventional to recognize a double hyphen as a signal to stop option interpretation and treat all following arguments literally.

Validate phone number with JavaScript

\\(?\d{3}\\)?([\-\s\.])?\d{3}\1?\d{4}

This will validate any phone number of variable format:

\\(?\d{3}\\)? finds 3 digits enclosed by parenthesis or not.

([\-\s\.])? finds any of these separator characters or not

\d{3} finds 3 digits

\1 uses the first matched separator - this ensures that the separators are the same. So (000) 999-5555 will not validate here because there is a space and dash separator, so just remove the "\1" and replace with the separator sub-pattern (doing so will also validate non standard formats). You should however be format hinting for user input anyway.

\d{4} finds 4 digits

Validates:

  • (000) 999 5555
  • (000)-999-5555
  • (000).999.5555
  • (000) 999-5555
  • (000)9995555
  • 000 999 5555
  • 000-999-5555
  • 000.999.5555
  • 0009995555

BTW this is for JavaScript hence to double escapes.

Why does javascript replace only first instance when using replace?

You can use:

String.prototype.replaceAll = function(search, replace) {
if (replace === undefined) {
    return this.toString();
}
return this.split(search).join(replace);
}

How can I get the Windows last reboot reason

Take a look at the Event Log API. Case a) (bluescreen, user cut the power cord or system hang) causes a note ('system did not shutdown correctly' or something like that) to be left in the 'System' event log the next time the system is rebooted properly. You should be able to access it programmatically using the above API (honestly, I've never used it but it should work).

What exactly is RESTful programming?

This is very less mentioned everywhere but the Richardson's Maturity Model is one of the best methods to actually judge how Restful is one's API. More about it here:

Richardson's Maturity Model

Get the IP Address of local computer

Also, note that "the local IP" might not be a particularly unique thing. If you are on several physical networks (wired+wireless+bluetooth, for example, or a server with lots of Ethernet cards, etc.), or have TAP/TUN interfaces setup, your machine can easily have a whole host of interfaces.

send bold & italic text on telegram bot with html

If you are using PHP you can use this, and I'm sure it's almost similar in other languages as well

$WebsiteURL = "https://api.telegram.org/bot".$BotToken;
$text = "<b>This</b> <i>is some Text</i>";
$Update = file_get_contents($WebsiteURL."/sendMessage?chat_id=$chat_id&text=$text&parse_mode=html);

echo $Update;

Here is the list of all tags that you can use

<b>bold</b>, <strong>bold</strong>
<i>italic</i>, <em>italic</em>
<a href="http://www.example.com/">inline URL</a>
<code>inline fixed-width code</code>
<pre>pre-formatted fixed-width code block</pre>

How can I access a hover state in reactjs?

ReactJs defines the following synthetic events for mouse events:

onClick onContextMenu onDoubleClick onDrag onDragEnd onDragEnter onDragExit
onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave
onMouseMove onMouseOut onMouseOver onMouseUp

As you can see there is no hover event, because browsers do not define a hover event natively.

You will want to add handlers for onMouseEnter and onMouseLeave for hover behavior.

ReactJS Docs - Events

How to POST a JSON object to a JAX-RS service

Jersey makes the process very easy, my service class worked well with JSON, all I had to do is to add the dependencies in the pom.xml

@Path("/customer")
public class CustomerService {

    private static Map<Integer, Customer> customers = new HashMap<Integer, Customer>();

    @POST
    @Path("save")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public SaveResult save(Customer c) {

        customers.put(c.getId(), c);

        SaveResult sr = new SaveResult();
        sr.sucess = true;
        return sr;
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("{id}")
    public Customer getCustomer(@PathParam("id") int id) {
        Customer c = customers.get(id);
        if (c == null) {
            c = new Customer();
            c.setId(id * 3);
            c.setName("unknow " + id);
        }
        return c;
    }
}

And in the pom.xml

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet</artifactId>
    <version>2.7</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.7</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-moxy</artifactId>
    <version>2.7</version>
</dependency>

Deserialize JSON to ArrayList<POJO> using Jackson

This works for me.

@Test
public void cloneTest() {
    List<Part> parts = new ArrayList<Part>();
    Part part1 = new Part(1);
    parts.add(part1);
    Part part2 = new Part(2);
    parts.add(part2);
    try {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = objectMapper.writeValueAsString(parts);

        List<Part> cloneParts = objectMapper.readValue(jsonStr, new TypeReference<ArrayList<Part>>() {});
    } catch (Exception e) {
        //fail("failed.");
        e.printStackTrace();
    }

    //TODO: Assert: compare both list values.
}

C# An established connection was aborted by the software in your host machine

An established connection was aborted by the software in your host machine

That is a boiler-plate error message, it comes out of Windows. The underlying error code is WSAECONNABORTED. Which really doesn't mean more than "connection was aborted". You have to be a bit careful about the "your host machine" part of the phrase. In the vast majority of Windows application programs, it is indeed the host that the desktop app is connected to that aborted the connection. Usually a server somewhere else.

The roles are reversed however when you implement your own server. Now you need to read the error message as "aborted by the application at the other end of the wire". Which is of course not uncommon when you implement a server, client programs that use your server are not unlikely to abort a connection for whatever reason. It can mean that a fire-wall or a proxy terminated the connection but that's not very likely since they typically would not allow the connection to be established in the first place.

You don't really know why a connection was aborted unless you have insight what is going on at the other end of the wire. That's of course hard to come by. If your server is reachable through the Internet then don't discount the possibility that you are being probed by a port scanner. Or your customers, looking for a game cheat.

Chrome javascript debugger breakpoints don't do anything?

I had a minifier that was stripping out debugger statements ¯_(?)_/¯

The type or namespace name 'Entity' does not exist in the namespace 'System.Data'

I noticed that in the csproj the framework entity had hintpath like

<HintPath>..\..\..\..\..\..\Users\{myusername}

I had this in the nuget.config file:

 <config>
 <add key="repositoryPath" value="../lib" />
 </config>

a) I removed the above lines, b) uninstalled the framework entity package, c) THEN CLOSED THE solution and reopened it, d) reinstalled the framework.

It fixed my issue.

Knockout validation

Knockout.js validation is handy but it is not robust. You always have to create server side validation replica. In your case (as you use knockout.js) you are sending JSON data to server and back asynchronously, so you can make user think that he sees client side validation, but in fact it would be asynchronous server side validation.

Take a look at example here upida.cloudapp.net:8080/org.upida.example.knockout/order/create?clientId=1 This is a "Create Order" link. Try to click "save", and play with products. This example is done using upida library (there are spring mvc version and asp.net mvc of this library) from codeplex.

Create a BufferedImage from file and make it TYPE_INT_ARGB

try {
    File img = new File("somefile.png");
    BufferedImage image = ImageIO.read(img ); 
    System.out.println(image);
} catch (IOException e) { 
    e.printStackTrace(); 
}

Example output for my image file:

BufferedImage@5d391d: type = 5 ColorModel: #pixelBits = 24 
numComponents = 3 color 
space = java.awt.color.ICC_ColorSpace@50a649 
transparency = 1 
has alpha = false 
isAlphaPre = false 
ByteInterleavedRaster: 
width = 800 
height = 600 
#numDataElements 3 
dataOff[0] = 2

You can run System.out.println(object); on just about any object and get some information about it.

Find maximum value of a column and return the corresponding row values using Pandas

Assuming df has a unique index, this gives the row with the maximum value:

In [34]: df.loc[df['Value'].idxmax()]
Out[34]: 
Country        US
Place      Kansas
Value         894
Name: 7

Note that idxmax returns index labels. So if the DataFrame has duplicates in the index, the label may not uniquely identify the row, so df.loc may return more than one row.

Therefore, if df does not have a unique index, you must make the index unique before proceeding as above. Depending on the DataFrame, sometimes you can use stack or set_index to make the index unique. Or, you can simply reset the index (so the rows become renumbered, starting at 0):

df = df.reset_index()

Pass variables to AngularJS controller, best practice?

You could create a basket service. And generally in JS you use objects instead of lots of parameters.

Here's an example: http://jsfiddle.net/2MbZY/

var app = angular.module('myApp', []);

app.factory('basket', function() {
    var items = [];
    var myBasketService = {};

    myBasketService.addItem = function(item) {
        items.push(item);
    };
    myBasketService.removeItem = function(item) {
        var index = items.indexOf(item);
        items.splice(index, 1);
    };
    myBasketService.items = function() {
        return items;
    };

    return myBasketService;
});

function MyCtrl($scope, basket) {
    $scope.newItem = {};
    $scope.basket = basket;    
}

Truncate number to two decimal places without rounding

Convert the number into a string, match the number up to the second decimal place:

_x000D_
_x000D_
function calc(theform) {_x000D_
    var num = theform.original.value, rounded = theform.rounded_x000D_
    var with2Decimals = num.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]_x000D_
    rounded.value = with2Decimals_x000D_
}
_x000D_
<form onsubmit="return calc(this)">_x000D_
Original number: <input name="original" type="text" onkeyup="calc(form)" onchange="calc(form)" />_x000D_
<br />"Rounded" number: <input name="rounded" type="text" placeholder="readonly" readonly>_x000D_
</form>
_x000D_
_x000D_
_x000D_

The toFixed method fails in some cases unlike toString, so be very careful with it.

How to send a model in jQuery $.ajax() post request to MVC controller method

I have an MVC page that submits JSON of selected values from a group of radio buttons.

I use:

var dataArray = $.makeArray($("input[type=radio]").serializeArray());

To make an array of their names and values. Then I convert it to JSON with:

var json = $.toJSON(dataArray)

and then post it with jQuery's ajax() to the MVC controller

$.ajax({
url: "/Rounding.aspx/Round/" + $("#OfferId").val(),
type: 'POST',
dataType: 'html',
data: json, 
contentType: 'application/json; charset=utf-8',
beforeSend: doSubmitBeforeSend,
complete: doSubmitComplete,
success: doSubmitSuccess});

Which sends the data across as native JSON data.

You can then capture the response stream and de-serialize it into the native C#/VB.net object and manipulate it in your controller.

To automate this process in a lovely, low maintenance way, I advise reading this entry that spells out most of native, automatic JSON de-serialization quite well.

Match your JSON object to match your model and the linked process below should automatically deserialize the data into your controller. It's works wonderfully for me.

Article on MVC JSON deserialization

Trying to handle "back" navigation button action in iOS

Swift

override func didMoveToParentViewController(parent: UIViewController?) {
    if parent == nil {
        //"Back pressed"
    }
}

How to get file extension from string in C++

Or you can use this:

    char *ExtractFileExt(char *FileName)
    {
        std::string s = FileName;
        int Len = s.length();
        while(TRUE)
        {
            if(FileName[Len] != '.')
                Len--;
            else
            {
                char *Ext = new char[s.length()-Len+1];
                for(int a=0; a<s.length()-Len; a++)
                    Ext[a] = FileName[s.length()-(s.length()-Len)+a];
                Ext[s.length()-Len] = '\0';
                return Ext;
            }
        }
    }

This code is cross-platform

How to know if docker is already logged in to a docker registry server

At least in "Docker for Windows" you can see if you are logged in to docker hub over the UI. Just right click the docker icon in the windows notification area: Docker Logged in

:last-child not working as expected?

The last-child selector is used to select the last child element of a parent. It cannot be used to select the last child element with a specific class under a given parent element.

The other part of the compound selector (which is attached before the :last-child) specifies extra conditions which the last child element must satisfy in-order for it to be selected. In the below snippet, you would see how the selected elements differ depending on the rest of the compound selector.

_x000D_
_x000D_
.parent :last-child{ /* this will select all elements which are last child of .parent */_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
.parent div:last-child{ /* this will select the last child of .parent only if it is a div*/_x000D_
  background: crimson;_x000D_
}_x000D_
_x000D_
.parent div.child-2:last-child{ /* this will select the last child of .parent only if it is a div and has the class child-2*/_x000D_
  color: beige;_x000D_
}
_x000D_
<div class='parent'>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div>Child w/o class</div>_x000D_
</div>_x000D_
<div class='parent'>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child-2'>Child w/o class</div>_x000D_
</div>_x000D_
<div class='parent'>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <p>Child w/o class</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_


To answer your question, the below would style the last child li element with background color as red.

li:last-child{
    background-color: red;
}

But the following selector would not work for your markup because the last-child does not have the class='complete' even though it is an li.

li.complete:last-child{
    background-color: green;
}

It would have worked if (and only if) the last li in your markup also had class='complete'.


To address your query in the comments:

@Harry I find it rather odd that: .complete:last-of-type does not work, yet .complete:first-of-type does work, regardless of it's position it's parents element. Thanks for your help.

The selector .complete:first-of-type works in the fiddle because it (that is, the element with class='complete') is still the first element of type li within the parent. Try to add <li>0</li> as the first element under the ul and you will find that first-of-type also flops. This is because the first-of-type and last-of-type selectors select the first/last element of each type under the parent.

Refer to the answer posted by BoltClock, in this thread for more details about how the selector works. That is as comprehensive as it gets :)

CSS for grabbing cursors (drag & drop)

CSS3 grab and grabbing are now allowed values for cursor. In order to provide several fallbacks for cross-browser compatibility3 including custom cursor files, a complete solution would look like this:

.draggable {
    cursor: move; /* fallback: no `url()` support or images disabled */
    cursor: url(images/grab.cur); /* fallback: Internet Explorer */
    cursor: -webkit-grab; /* Chrome 1-21, Safari 4+ */
    cursor:    -moz-grab; /* Firefox 1.5-26 */
    cursor:         grab; /* W3C standards syntax, should come least */
}

.draggable:active {
    cursor: url(images/grabbing.cur);
    cursor: -webkit-grabbing;
    cursor:    -moz-grabbing;
    cursor:         grabbing;
}

Update 2019-10-07:

.draggable {
    cursor: move; /* fallback: no `url()` support or images disabled */
    cursor: url(images/grab.cur); /* fallback: Chrome 1-21, Firefox 1.5-26, Safari 4+, IE, Edge 12-14, Android 2.1-4.4.4 */
    cursor: grab; /* W3C standards syntax, all modern browser */
}

.draggable:active {
    cursor: url(images/grabbing.cur);
    cursor: grabbing;
}

Google map V3 Set Center to specific Marker

This should do the trick!

google.maps.event.trigger(map, "resize");
map.panTo(marker.getPosition());
map.setZoom(14);

You will need to have your maps global

Migrating from VMWARE to VirtualBox

After many attempts I was finally able to get this working. Essentially what I did was download and use the vmware converter to merge the two disks into one. After that I was able to attach the newly created disk to VitrualBox.

The steps involved are very simple:

BEFORE YOU DO ANYTHING!

1) MAKE A BACKUP!!! Even if you follow these instruction, you could screw things up, so make a backup. Just shutdown the VM and then make a copy of the directory where VM resides.

2) Uninstall VMware Tools from the VM that you are going to convert. If for some reason you forget this step, you can still uninstall it after getting everything running under VirtualBox by following these steps. Do yourself the favor and just do it now.

NOW THE FUN PART!!!

1) Download and install the VMware Converter. I used 5.0.1 build-875114, just use the latest.

2) Download and install VirtualBox

3) Fire up VMWare convertor:

Fire up VMWare convertor

4) Click on Convert machine

6) Browse to the .vmx for your VM and click Next.

Convert machine

7) Give the new VM a name and select the location where you want to put it. Click Next

Give the new VM a name and select the location

8) Click Next on the Options screen. You shouldn't have to change anything here.

Click <code>Next</code> on the <code>Options</code> screen.

9) Click Finish on the Summary screen to begin the conversion.

Click <code>Finish</code> on the <code>Summary</code> screen

10) The conversion should start. This will take a LOOONG time so be patient.

The conversion should start.

11) Hopefully all went well, if it did, you should see that the conversion is completed:

conversion is completed

12) Now open up VirtualBox and click New.

open up VirtualBox and click <code>New</code>

13) Give your VM a name and select what Type and Version it is. Click Next.

Give your VM a name and select what <code>Type</code> and <code>Version</code> it is.

14) Select the size of the memory you want to give it. Click Next.

Select the size of the memory you want to give it.

15) For the Hard Drive, click Use and existing hard drive file and select the newly converted .vmdk file.

Use and existing hard drive file

16) Now Click Settings and select the Storage menu. The issue is that by default VirtualBox will add the drive as an IDE. This won't work and we need as we need to put it on a SCSI controller.

put it on a SCSI controller

17) Select the IDE controller and the Remove Controller button.

Select the IDE controller and the <code>Remove Controller</code> button.

18) Now click the Add Controller button and select Add SCSI Controller

Add SCSI Controller

19) Click the Add Hard Disk button.

Add Hard Disk

20) Click Choose existing disk

Choose existing disk

21) Select your .vmdk file. Click OK

Select your <code>.vmdk</code> file.

22) Select the System menu.

Select the <code>System</code> menu.

23) Click Enable IO APIC. Then click OK

Click <code>Enable IO APIC</code>.

24) Congrats!!! Your VM is now confgiured! Click Start to startup the VM!

Click <code>Start</code> to startup the VM!

Copy rows from one table to another, ignoring duplicates

insert into tbl2
select field1,field2,... from tbl1
where not exists 
    ( 
        select field1,field2,... 
        from person2
        where (tbl1.field1=tbl2.field1 and
        tbl1.field2=tbl2.field2 and .....)
    )

pandas loc vs. iloc vs. at vs. iat?

Let's start with this small df:

import pandas as pd
import time as tm
import numpy as np
n=10
a=np.arange(0,n**2)
df=pd.DataFrame(a.reshape(n,n))

We'll so have

df
Out[25]: 
        0   1   2   3   4   5   6   7   8   9
    0   0   1   2   3   4   5   6   7   8   9
    1  10  11  12  13  14  15  16  17  18  19
    2  20  21  22  23  24  25  26  27  28  29
    3  30  31  32  33  34  35  36  37  38  39
    4  40  41  42  43  44  45  46  47  48  49
    5  50  51  52  53  54  55  56  57  58  59
    6  60  61  62  63  64  65  66  67  68  69
    7  70  71  72  73  74  75  76  77  78  79
    8  80  81  82  83  84  85  86  87  88  89
    9  90  91  92  93  94  95  96  97  98  99

With this we have:

df.iloc[3,3]
Out[33]: 33

df.iat[3,3]
Out[34]: 33

df.iloc[:3,:3]
Out[35]: 
    0   1   2   3
0   0   1   2   3
1  10  11  12  13
2  20  21  22  23
3  30  31  32  33



df.iat[:3,:3]
Traceback (most recent call last):
   ... omissis ...
ValueError: At based indexing on an integer index can only have integer indexers

Thus we cannot use .iat for subset, where we must use .iloc only.

But let's try both to select from a larger df and let's check the speed ...

# -*- coding: utf-8 -*-
"""
Created on Wed Feb  7 09:58:39 2018

@author: Fabio Pomi
"""

import pandas as pd
import time as tm
import numpy as np
n=1000
a=np.arange(0,n**2)
df=pd.DataFrame(a.reshape(n,n))
t1=tm.time()
for j in df.index:
    for i in df.columns:
        a=df.iloc[j,i]
t2=tm.time()
for j in df.index:
    for i in df.columns:
        a=df.iat[j,i]
t3=tm.time()
loc=t2-t1
at=t3-t2
prc = loc/at *100
print('\nloc:%f at:%f prc:%f' %(loc,at,prc))

loc:10.485600 at:7.395423 prc:141.784987

So with .loc we can manage subsets and with .at only a single scalar, but .at is faster than .loc

:-)

How do I define global variables in CoffeeScript?

Ivo nailed it, but I'll mention that there is one dirty trick you can use, though I don't recommend it if you're going for style points: You can embed JavaScript code directly in your CoffeeScript by escaping it with backticks.

However, here's why this is usually a bad idea: The CoffeeScript compiler is unaware of those variables, which means they won't obey normal CoffeeScript scoping rules. So,

`foo = 'bar'`
foo = 'something else'

compiles to

foo = 'bar';
var foo = 'something else';

and now you've got yourself two foos in different scopes. There's no way to modify the global foo from CoffeeScript code without referencing the global object, as Ivy described.

Of course, this is only a problem if you make an assignment to foo in CoffeeScript—if foo became read-only after being given its initial value (i.e. it's a global constant), then the embedded JavaScript solution approach might be kinda sorta acceptable (though still not recommended).

"Uncaught Error: [$injector:unpr]" with angular after deployment

Ran into the same problem myself, but my controller definitions looked a little different than above. For controllers defined like this:

function MyController($scope, $http) {
    // ...
}

Just add a line after the declaration indicating which objects to inject when the controller is instantiated:

function MyController($scope, $http) {
    // ...
}
MyController.$inject = ['$scope', '$http'];

This makes it minification-safe.

How can I run a directive after the dom has finished rendering?

If you can't use $timeout due to external resources and cant use a directive due to a specific issue with timing, use broadcast.

Add $scope.$broadcast("variable_name_here"); after the desired external resource or long running controller/directive has completed.

Then add the below after your external resource has loaded.

$scope.$on("variable_name_here", function(){ 
   // DOM manipulation here
   jQuery('selector').height(); 
}

For example in the promise of a deferred HTTP request.

MyHttpService.then(function(data){
   $scope.MyHttpReturnedImage = data.image;
   $scope.$broadcast("imageLoaded");
});

$scope.$on("imageLoaded", function(){ 
   jQuery('img').height(80).width(80); 
}

Check if a value exists in ArrayList

Just use ArrayList.contains(desiredElement). For example, if you're looking for the conta1 account from your example, you could use something like:

if (lista.contains(conta1)) {
    System.out.println("Account found");
} else {
    System.out.println("Account not found");
}

Edit: Note that in order for this to work, you will need to properly override the equals() and hashCode() methods. If you are using Eclipse IDE, then you can have these methods generated by first opening the source file for your CurrentAccount object and the selecting Source > Generate hashCode() and equals()...

__init__ and arguments in Python

The fact that your method does not use the self argument (which is a reference to the instance that the method is attached to) doesn't mean you can leave it out. It always has to be there, because Python is always going to try to pass it in.

Why does Java have an "unreachable statement" compiler error?

It is certainly a good thing to complain the more stringent the compiler is the better, as far as it allows you to do what you need. Usually the small price to pay is to comment the code out, the gain is that when you compile your code works. A general example is Haskell about which people screams until they realize that their test/debugging is main test only and short one. I personally in Java do almost no debugging while being ( in fact on purpose) not attentive.

What does "hard coded" mean?

"hard coding" means putting something into your source code. If you are not hard coding, then you do something like prompting the user for the data, or allow the user to put the data on the command line, or something like that.

So, to hard code the location of the file as being on the C: drive, you would just put the pathname of the file all together in your source code.

Here is an example.

int main()
{
    const char *filename = "C:\\myfile.txt";

    printf("Filename is: %s\n", filename);
}

The file name is "hard coded" as: C:\myfile.txt

The reason the backslash is doubled is because backslashes are special in C strings.

HTML 5 input type="number" element for floating point numbers on Chrome

Try <input type="number" step="0.01" /> if you are targeting 2 decimal places :-).

How to find a hash key containing a matching value

According to ruby doc http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-key key(value) is the method to find the key on the base of value.

ROLE = {"customer" => 1, "designer" => 2, "admin" => 100}
ROLE.key(2)

it will return the "designer".

Sorting dictionary keys in python

[v[0] for v in sorted(foo.items(), key=lambda(k,v): (v,k))]

How to smooth a curve in the right way?

If you are plotting time series graph and if you have used mtplotlib for drawing graphs then use median method to smooth-en the graph

smotDeriv = timeseries.rolling(window=20, min_periods=5, center=True).median()

where timeseries is your set of data passed you can alter windowsize for more smoothining.

How to select true/false based on column value?

If the way you determine whether or not an entity has a profile is a deterministic function, and doesn't require any access to another table, you could write a stored function and define a computed, persisted field which would store that value for you and not have to re-compute it over and over again.

If you need to query a separate table (to e.g. check the existance of a row), you could still make this "HasProfile" a column in your entity table and just compute that field on a regular basis, e.g. every night or so. If you have the value stored as an atomic value, you don't need the computation every time. This works as long as that fact - has a profile or not - doesn't change too frequently.

To add a column to check whether or not EntityProfile is empty, do something like this:

CREATE FUNCTION CheckHasProfile(@Field VARCHAR(MAX))
RETURNS BIT
WITH SCHEMABINDING
AS BEGIN
    DECLARE @Result BIT

    IF @Field IS NULL OR LEN(@Field) <= 0
        SET @Result = 0
    ELSE
        SET @Result = 1

    RETURN @Result
END

and then add a new computed column to your table Entity:

ALTER TABLE dbo.Entity
   ADD HasProfile AS dbo.CheckHasProfile(EntityProfile) PERSISTED

Now you have a BIT column and it's persisted, e.g. doesn't get computed every time to access the row, and should perform just fine!

How to handle ETIMEDOUT error?

In case if you are using node js, then this could be the possible solution

const express = require("express");
const app = express();
const server = app.listen(8080);
server.keepAliveTimeout = 61 * 1000;

https://medium.com/hk01-tech/running-eks-in-production-for-2-years-the-kubernetes-journey-at-hk01-68130e603d76

best practice to generate random token for forgot password

The earlier version of the accepted answer (md5(uniqid(mt_rand(), true))) is insecure and only offers about 2^60 possible outputs -- well within the range of a brute force search in about a week's time for a low-budget attacker:

Since a 56-bit DES key can be brute-forced in about 24 hours, and an average case would have about 59 bits of entropy, we can calculate 2^59 / 2^56 = about 8 days. Depending on how this token verification is implemented, it might be possible to practically leak timing information and infer the first N bytes of a valid reset token.

Since the question is about "best practices" and opens with...

I want to generate identifier for forgot password

...we can infer that this token has implicit security requirements. And when you add security requirements to a random number generator, the best practice is to always use a cryptographically secure pseudorandom number generator (abbreviated CSPRNG).


Using a CSPRNG

In PHP 7, you can use bin2hex(random_bytes($n)) (where $n is an integer larger than 15).

In PHP 5, you can use random_compat to expose the same API.

Alternatively, bin2hex(mcrypt_create_iv($n, MCRYPT_DEV_URANDOM)) if you have ext/mcrypt installed. Another good one-liner is bin2hex(openssl_random_pseudo_bytes($n)).

Separating the Lookup from the Validator

Pulling from my previous work on secure "remember me" cookies in PHP, the only effective way to mitigate the aforementioned timing leak (typically introduced by the database query) is to separate the lookup from the validation.

If your table looks like this (MySQL)...

CREATE TABLE account_recovery (
    id INTEGER(11) UNSIGNED NOT NULL AUTO_INCREMENT 
    userid INTEGER(11) UNSIGNED NOT NULL,
    token CHAR(64),
    expires DATETIME,
    PRIMARY KEY(id)
);

... you need to add one more column, selector, like so:

CREATE TABLE account_recovery (
    id INTEGER(11) UNSIGNED NOT NULL AUTO_INCREMENT 
    userid INTEGER(11) UNSIGNED NOT NULL,
    selector CHAR(16),
    token CHAR(64),
    expires DATETIME,
    PRIMARY KEY(id),
    KEY(selector)
);

Use a CSPRNG When a password reset token is issued, send both values to the user, store the selector and a SHA-256 hash of the random token in the database. Use the selector to grab the hash and User ID, calculate the SHA-256 hash of the token the user provides with the one stored in the database using hash_equals().

Example Code

Generating a reset token in PHP 7 (or 5.6 with random_compat) with PDO:

$selector = bin2hex(random_bytes(8));
$token = random_bytes(32);

$urlToEmail = 'http://example.com/reset.php?'.http_build_query([
    'selector' => $selector,
    'validator' => bin2hex($token)
]);

$expires = new DateTime('NOW');
$expires->add(new DateInterval('PT01H')); // 1 hour

$stmt = $pdo->prepare("INSERT INTO account_recovery (userid, selector, token, expires) VALUES (:userid, :selector, :token, :expires);");
$stmt->execute([
    'userid' => $userId, // define this elsewhere!
    'selector' => $selector,
    'token' => hash('sha256', $token),
    'expires' => $expires->format('Y-m-d\TH:i:s')
]);

Verifying the user-provided reset token:

$stmt = $pdo->prepare("SELECT * FROM account_recovery WHERE selector = ? AND expires >= NOW()");
$stmt->execute([$selector]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (!empty($results)) {
    $calc = hash('sha256', hex2bin($validator));
    if (hash_equals($calc, $results[0]['token'])) {
        // The reset token is valid. Authenticate the user.
    }
    // Remove the token from the DB regardless of success or failure.
}

These code snippets are not complete solutions (I eschewed the input validation and framework integrations), but they should serve as an example of what to do.

Date formatting in WPF datagrid

Binding="{Binding YourColumn ,StringFormat='yyyy-MM-dd'}"

Adding placeholder text to textbox

Attached properties to the rescue:

public static class TextboxExtensions
{
    public static readonly DependencyProperty PlaceholderProperty = 
        DependencyProperty.RegisterAttached(
            "Placeholder", 
            typeof(string), 
            typeof(TextboxExtensions), 
            new PropertyMetadata(default(string), propertyChangedCallback: PlaceholderChanged)
            );

    private static void PlaceholderChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
    {
        var tb = dependencyObject as TextBox;

        if (tb == null)
            return;

        tb.LostFocus -= OnLostFocus;
        tb.GotFocus -= OnGotFocus;

        if (args.NewValue != null)
        {
            tb.GotFocus += OnGotFocus;
            tb.LostFocus += OnLostFocus;
        }

        SetPlaceholder(dependencyObject, args.NewValue as string);

        if (!tb.IsFocused)
            ShowPlaceholder(tb);
    }

    private static void OnLostFocus(object sender, RoutedEventArgs routedEventArgs)
    {
        ShowPlaceholder(sender as TextBox);
    }

    private static void OnGotFocus(object sender, RoutedEventArgs routedEventArgs)
    {
        HidePlaceholder(sender as TextBox);
    }

    [AttachedPropertyBrowsableForType(typeof(TextBox))]
    public static void SetPlaceholder(DependencyObject element, string value)
    {
        element.SetValue(PlaceholderProperty, value);
    }

    [AttachedPropertyBrowsableForType(typeof(TextBox))]
    public static string GetPlaceholder(DependencyObject element)
    {
        return (string)element.GetValue(PlaceholderProperty);
    }

    private static void ShowPlaceholder(TextBox textBox)
    {
        if (string.IsNullOrWhiteSpace(textBox.Text))
        {
            textBox.Text = GetPlaceholder(textBox);
        }
    }

    private static void HidePlaceholder(TextBox textBox)
    {
        string placeholderText = GetPlaceholder(textBox);

        if (textBox.Text == placeholderText)
            textBox.Text = string.Empty;
    }
}

Usage:

<TextBox Text="hi" local:TextboxExtensions.Placeholder="Hello there"></TextBox>

Dynamically Add Variable Name Value Pairs to JSON Object

You can achieve this using Lodash _.assign function.

_x000D_
_x000D_
var ipID = {};_x000D_
_.assign(ipID, {'name': "value"}, {'anotherName': "anotherValue"});_x000D_
console.log(ipID);
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?

In many applications, like MsOffice (until version 2000 or 2002), the maximum number of characters per cell was 255. Moving data from programs able of handling more than 255 characters per field to/from those applications was a nightmare. Currently, the limit is less and less hindering.

Send File Attachment from Form Using phpMailer and PHP

File could not be Attached from client PC (upload)

In the HTML form I have not added following line, so no attachment was going:

enctype="multipart/form-data"

After adding above line in form (as below), the attachment went perfect.

<form id="form1" name="form1" method="post" action="form_phpm_mailer.php"  enctype="multipart/form-data">

jquery fill dropdown with json data

In most of the companies they required a common functionality for multiple dropdownlist for all the pages. Just call the functions or pass your (DropDownID,JsonData,KeyValue,textValue)

    <script>

        $(document).ready(function(){

            GetData('DLState',data,'stateid','statename');
        });

        var data = [{"stateid" : "1","statename" : "Mumbai"},
                    {"stateid" : "2","statename" : "Panjab"},
                    {"stateid" : "3","statename" : "Pune"},
                     {"stateid" : "4","statename" : "Nagpur"},
                     {"stateid" : "5","statename" : "kanpur"}];

        var Did=document.getElementById("DLState");

        function GetData(Did,data,valkey,textkey){
          var str= "";
          for (var i = 0; i <data.length ; i++){

            console.log(data);


            str+= "<option value='" + data[i][valkey] + "'>" + data[i][textkey] + "</option>";

          }
          $("#"+Did).append(str);
        };    </script>

</head>
<body>
  <select id="DLState">
  </select>
</body>
</html>

AngularJS - $http.post send data as json

Consider explicitly setting the header in the $http.post (I put application/json, as I am not sure which of the two versions in your example is the working one, but you can use application/x-www-form-urlencoded if it's the other one):

$http.post("/customer/data/autocomplete", {term: searchString}, {headers: {'Content-Type': 'application/json'} })
        .then(function (response) {
            return response;
        });

Css pseudo classes input:not(disabled)not:[type="submit"]:focus

You have a few typos in your select. It should be: input:not([disabled]):not([type="submit"]):focus

See this jsFiddle for a proof of concept. On a sidenote, if I removed the "background-color" property, then the box shadow no longer works. Not sure why.

How do I rename a repository on GitHub?

  1. open this url (https://github.com/) from your browser

  2. Go to repositories at the Right end of the page

  3. Open the link of repository that you want to rename

  4. click Settings (you will find in the Navigation bar)

  5. At the top you will find a box Called (Repository name) where you write the new name

  6. Press Rename

adding child nodes in treeview

May i add to Stormenet example some KISS (Keep It Simple & Stupid):

If you already have a treeView or just created an instance of it: Let's populate with some data - Ex. One parent two child's :

            treeView1.Nodes.Add("ParentKey","Parent Text");
            treeView1.Nodes["ParentKey"].Nodes.Add("Child-1 Text");
            treeView1.Nodes["ParentKey"].Nodes.Add("Child-2 Text");

Another Ex. two parent's first have two child's second one child:

            treeView1.Nodes.Add("ParentKey1","Parent-1  Text");
            treeView1.Nodes.Add("ParentKey2","Parent-2 Text");
            treeView1.Nodes["ParentKey1"].Nodes.Add("Child-1 Text");
            treeView1.Nodes["ParentKey1"].Nodes.Add("Child-2 Text");
            treeView1.Nodes["ParentKey2"].Nodes.Add("Child-3 Text");

Take if farther - sub child of child 2:

            treeView1.Nodes.Add("ParentKey1","Parent-1  Text");
            treeView1.Nodes["ParentKey1"].Nodes.Add("Child-1 Text");
            treeView1.Nodes["ParentKey1"].Nodes.Add("ChildKey2","Child-2 Text");
            treeView1.Nodes["ParentKey1"].Nodes["ChildKey2"].Nodes.Add("Child-3 Text");

As you see you can have as many child's and parent's as you want and those can have sub child's of child's and so on.... Hope i help!

Simple Android RecyclerView example

implementation androidx.recyclerview:recyclerview:.... It is advised to update to the androidx libraries which are here:

https://developer.android.com/jetpack/androidx/releases/recyclerview

The layout file Widget XML tag then must be updated to: androidx.recyclerview.widget.RecyclerView

Tomcat: LifecycleException when deploying


Tomcat has different WAR deployment ways. Some work, some don't. Please try the following deployment methods :

  • Automatic: Copy-paste your WAR file into ${CATALINA_HOME}/webapps. A folder with the same name will appear if everything goes right.
  • Manager Application: Upload the WAR file
  • Manager Application: Locate the WAR file

In my case, using the Manager Application (local URL: http://localhost:8080/manager) worked. Whereas deploying using a copy-paste resulted in your error.

Check to see if cURL is installed locally?

Another way, say in CentOS, is:

$ yum list installed '*curl*'
Loaded plugins: aliases, changelog, fastestmirror, kabi, langpacks, priorities, tmprepo, verify,
              : versionlock
Loading support for Red Hat kernel ABI
Determining fastest mirrors
google-chrome                                                                                    3/3
152 packages excluded due to repository priority protections
Installed Packages
curl.x86_64                                        7.29.0-42.el7                                @base
libcurl.x86_64                                     7.29.0-42.el7                                @base
libcurl-devel.x86_64                               7.29.0-42.el7                                @base
python-pycurl.x86_64                               7.19.0-19.el7                                @base

Can I convert a C# string value to an escaped string literal

public static class StringEscape
{
  static char[] toEscape = "\0\x1\x2\x3\x4\x5\x6\a\b\t\n\v\f\r\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\"\\".ToCharArray();
  static string[] literals = @"\0,\x0001,\x0002,\x0003,\x0004,\x0005,\x0006,\a,\b,\t,\n,\v,\f,\r,\x000e,\x000f,\x0010,\x0011,\x0012,\x0013,\x0014,\x0015,\x0016,\x0017,\x0018,\x0019,\x001a,\x001b,\x001c,\x001d,\x001e,\x001f".Split(new char[] { ',' });

  public static string Escape(this string input)
  {
    int i = input.IndexOfAny(toEscape);
    if (i < 0) return input;

    var sb = new System.Text.StringBuilder(input.Length + 5);
    int j = 0;
    do
    {
      sb.Append(input, j, i - j);
      var c = input[i];
      if (c < 0x20) sb.Append(literals[c]); else sb.Append(@"\").Append(c);
    } while ((i = input.IndexOfAny(toEscape, j = ++i)) > 0);

    return sb.Append(input, j, input.Length - j).ToString();
  }
}

Java 8 NullPointerException in Collectors.toMap

NullPointerException is by far the most frequently encountered exception (at least in my case). To avoid this I go defensive and add bunch of null checks and I end up having bloated and ugly code. Java 8 introduces Optional to handle null references so you can define nullable and non-nullable values.

That said, I would wrap all the nullable references in Optional container. We should also not break backward compatibility as well. Here is the code.

class Answer {
    private int id;
    private Optional<Boolean> answer;

    Answer() {
    }

    Answer(int id, Boolean answer) {
        this.id = id;
        this.answer = Optional.ofNullable(answer);
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    /**
     * Gets the answer which can be a null value. Use {@link #getAnswerAsOptional()} instead.
     *
     * @return the answer which can be a null value
     */
    public Boolean getAnswer() {
        // What should be the default value? If we return null the callers will be at higher risk of having NPE
        return answer.orElse(null);
    }

    /**
     * Gets the optional answer.
     *
     * @return the answer which is contained in {@code Optional}.
     */
    public Optional<Boolean> getAnswerAsOptional() {
        return answer;
    }

    /**
     * Gets the answer or the supplied default value.
     *
     * @return the answer or the supplied default value.
     */
    public boolean getAnswerOrDefault(boolean defaultValue) {
        return answer.orElse(defaultValue);
    }

    public void setAnswer(Boolean answer) {
        this.answer = Optional.ofNullable(answer);
    }
}

public class Main {
    public static void main(String[] args) {
        List<Answer> answerList = new ArrayList<>();

        answerList.add(new Answer(1, true));
        answerList.add(new Answer(2, true));
        answerList.add(new Answer(3, null));

        // map with optional answers (i.e. with null)
        Map<Integer, Optional<Boolean>> answerMapWithOptionals = answerList.stream()
                .collect(Collectors.toMap(Answer::getId, Answer::getAnswerAsOptional));

        // map in which null values are removed
        Map<Integer, Boolean> answerMapWithoutNulls = answerList.stream()
                .filter(a -> a.getAnswerAsOptional().isPresent())
                .collect(Collectors.toMap(Answer::getId, Answer::getAnswer));

        // map in which null values are treated as false by default
        Map<Integer, Boolean> answerMapWithDefaults = answerList.stream()
                .collect(Collectors.toMap(a -> a.getId(), a -> a.getAnswerOrDefault(false)));

        System.out.println("With Optional: " + answerMapWithOptionals);
        System.out.println("Without Nulls: " + answerMapWithoutNulls);
        System.out.println("Wit Defaults: " + answerMapWithDefaults);
    }
}

add a temporary column with a value

I giving you an example in wich the TABLE registrofaena doesn't have the column called minutos. Minutos is created and it content is a result of divide demora/60, in other words, i created a column to show the values of the delay in minutes.

This is the query:

SELECT idfaena,fechahora,demora, demora/60 as minutos,comentario 
FROM registrofaena  
WHERE fecha>='2018-10-17' AND comentario <> '' 
ORDER BY idfaena ASC;

This is the view:

This is the result

Does functional programming replace GoF design patterns?

Brace yourselves.

It will aggravate many to hear me claim to have replaced design patterns and debunked SOLID and DRY. I'm nobody. Nevertheless, I correctly modeled collaborative (manufacturing) architecture and published the rules for building processes online along with the code and science behind it at my website http://www.powersemantics.com/.

My argument is that design patterns attempt to achieve what manufacturing calls "mass customization", a process form in which every step can be reshaped, recomposed and extended. You might think of such processes as uncompiled scripts. I'm not going to repeat my (online) argument here. In short, my mass customization architecture replaces design patterns by achieving that flexibility without any of the messy semantics. I was surprised my model worked so well, but the way programmers write code simply doesn't hold a candle to how manufacturing organizes collaborative work.

  • Manufacturing = each step interacts with one product
  • OOP = each step interacts with itself and other modules, passing the product around from point to point like useless office workers

This architecture never needs refactoring. There are also rules concerning centralization and distribution which affect complexity. But to answer your question, functional programming is another set of processing semantics, not an architecture for mass custom processes where 1) the source routing exists as a (script) document which the wielder can rewrite before firing and 2) modules can be easily and dynamically added or removed.

We could say OOP is the "hardcoded process" paradigm and that design patterns are ways to avoid that paradigm. But that's what mass customization is all about. Design patterns embody dynamic processes as messy hardcode. There's just no point. The fact that F# allows passing functions as a parameter means functional and OOP languages alike attempt to accomplish mass customization itself.

How confusing is that to the reader, hardcode which represents script? Not at all if you think your compiler's consumers pay for such features, but to me such features are semantic waste. They are pointless, because the point of mass customization is to make processes themselves dynamic, not just dynamic to the programmer wielding Visual Studio.

Razor If/Else conditional operator syntax

You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:

@(deletedView ? "Deleted" : "Created by")

Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.

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 };
        }
    }
}

Change Input to Upper Case

you can try this HTML

<input id="pan" onkeyup="inUpper()" />

javaScript

function _( x ) {
  return document.getElementById( x );
}
  // convert text in upper case
  function inUpper() {
    _('pan').value = _('pan').value.toUpperCase();
  }

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

Technically redirect should be used either if we need to transfer control to different domain or to achieve separation of task.

For example in the payment application we do the PaymentProcess first and then redirect to displayPaymentInfo. If the client refreshes the browser only the displayPaymentInfo will be done again and PaymentProcess will not be repeated. But if we use forward in this scenario, both PaymentProcess and displayPaymentInfo will be re-executed sequentially, which may result in incosistent data.

For other scenarios, forward is efficient to use since as it is faster than sendRedirect

Creating a PDF from a RDLC Report in the Background

You can use following code which generate pdf file in background as like on button click and then would popup in brwoser with SaveAs and cancel option.

Warning[] warnings;
        string[] streamIds;
        string mimeType = string.Empty;
        string encoding = string.Empty;`enter code here`
        string extension = string.Empty;
        DataSet dsGrpSum, dsActPlan, dsProfitDetails,
            dsProfitSum, dsSumHeader, dsDetailsHeader, dsBudCom = null;

    enter code here

//This is optional if you have parameter then you can add parameters as much as you want
ReportParameter[] param = new ReportParameter[5];
            param[0] = new ReportParameter("Report_Parameter_0", "1st Para", true);
            param[1] = new ReportParameter("Report_Parameter_1", "2nd Para", true);
            param[2] = new ReportParameter("Report_Parameter_2", "3rd Para", true);
            param[3] = new ReportParameter("Report_Parameter_3", "4th Para", true);
            param[4] = new ReportParameter("Report_Parameter_4", "5th Para");

            DataSet  dsData= "Fill this dataset with your data";
            ReportDataSource rdsAct = new ReportDataSource("RptActDataSet_usp_GroupAccntDetails", dsActPlan.Tables[0]);
            ReportViewer viewer = new ReportViewer();
            viewer.LocalReport.Refresh();
            viewer.LocalReport.ReportPath = "Reports/AcctPlan.rdlc"; //This is your rdlc name.
            viewer.LocalReport.SetParameters(param);
            viewer.LocalReport.DataSources.Add(rdsAct); // Add  datasource here         
            byte[] bytes = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
            // byte[] bytes = viewer.LocalReport.Render("Excel", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
            // Now that you have all the bytes representing the PDF report, buffer it and send it to the client.          
            // System.Web.HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Buffer = true;
            Response.Clear();
            Response.ContentType = mimeType;
            Response.AddHeader("content-disposition", "attachment; filename= filename" + "." + extension);
            Response.OutputStream.Write(bytes, 0, bytes.Length); // create the file  
            Response.Flush(); // send it to the client to download  
            Response.End();

How can I clear console

In Windows we have multiple options :

  1. clrscr() (Header File : conio.h)

  2. system("cls") (Header File : stdlib.h)

In Linux, use system("clear") (Header File : stdlib.h)

C# Set collection?

I use Iesi.Collections http://www.codeproject.com/KB/recipes/sets.aspx

It's used in lot of OSS projects, I first came across it in NHibernate

PHP fwrite new line

You append a newline to both the username and the password, i.e. the output would be something like

Sebastian
password
John
hfsjaijn

use fwrite($fh,$user." ".$password."\n"); instead to have them both on one line.
Or use fputcsv() to write the data and fgetcsv() to fetch it. This way you would at least avoid encoding problems like e.g. with $username='Charles, III';

...i.e. setting aside all the things that are wrong about storing plain passwords in plain files and using _GET for this type of operation (use _POST instead) ;-)

Get SELECT's value and text in jQuery

$("#yourdropdownid option:selected").text(); // selected option text
$("#yourdropdownid").val(); // selected option value

How to increase the max connections in postgres?

Just increasing max_connections is bad idea. You need to increase shared_buffers and kernel.shmmax as well.


Considerations

max_connections determines the maximum number of concurrent connections to the database server. The default is typically 100 connections.

Before increasing your connection count you might need to scale up your deployment. But before that, you should consider whether you really need an increased connection limit.

Each PostgreSQL connection consumes RAM for managing the connection or the client using it. The more connections you have, the more RAM you will be using that could instead be used to run the database.

A well-written app typically doesn't need a large number of connections. If you have an app that does need a large number of connections then consider using a tool such as pg_bouncer which can pool connections for you. As each connection consumes RAM, you should be looking to minimize their use.


How to increase max connections

1. Increase max_connection and shared_buffers

in /var/lib/pgsql/{version_number}/data/postgresql.conf

change

max_connections = 100
shared_buffers = 24MB

to

max_connections = 300
shared_buffers = 80MB

The shared_buffers configuration parameter determines how much memory is dedicated to PostgreSQL to use for caching data.

  • If you have a system with 1GB or more of RAM, a reasonable starting value for shared_buffers is 1/4 of the memory in your system.
  • it's unlikely you'll find using more than 40% of RAM to work better than a smaller amount (like 25%)
  • Be aware that if your system or PostgreSQL build is 32-bit, it might not be practical to set shared_buffers above 2 ~ 2.5GB.
  • Note that on Windows, large values for shared_buffers aren't as effective, and you may find better results keeping it relatively low and using the OS cache more instead. On Windows the useful range is 64MB to 512MB.

2. Change kernel.shmmax

You would need to increase kernel max segment size to be slightly larger than the shared_buffers.

In file /etc/sysctl.conf set the parameter as shown below. It will take effect when postgresql reboots (The following line makes the kernel max to 96Mb)

kernel.shmmax=100663296

References

Postgres Max Connections And Shared Buffers

Tuning Your PostgreSQL Server

Why can't Visual Studio find my DLL?

try "configuration properties -> debugging -> environment" and set the PATH variable in run-time

Forgot Oracle username and password, how to retrieve?

The usernames are shown in the dba_users's username column, there is a script you can run called:

alter user username identified by password

You can get more information here - https://community.oracle.com/thread/632617?tstart=0

How to run a command as a specific user in an init script?

On RHEL systems, the /etc/rc.d/init.d/functions script is intended to provide similar to what you want. If you source that at the top of your init script, all of it's functions become available.

The specific function provided to help with this is daemon. If you are intending to use it to start a daemon-like program, a simple usage would be:

daemon --user=username command

If that is too heavy-handed for what you need, there is runuser (see man runuser for full info; some versions may need -u prior to the username):

/sbin/runuser username -s /bin/bash -c "command(s) to run as user username"

jQuery .live() vs .on() method for adding a click event after loading dynamic html

Try this:

$('#parent').on('click', '#child', function() {
    // Code
});

From the $.on() documentation:

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().

Your #child element doesn't exist when you call $.on() on it, so the event isn't bound (unlike $.live()). #parent, however, does exist, so binding the event to that is fine.

The second argument in my code above acts as a 'filter' to only trigger if the event bubbled up to #parent from #child.

Fixed positioned div within a relative parent div

Try postion:sticky on parent element.

How to set x axis values in matplotlib python?

The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:

import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square') 
plt.xlabel('x')
plt.ylabel('y') 
plt.xticks(xi, x)
plt.title('compare')
plt.legend() 
plt.show()

SQL Left Join first match only

Try this

 SELECT *
 FROM people P 
 where P.IDNo in (SELECT DISTINCT IDNo
              FROM people)

What is java pojo class, java bean, normal class?

POJO = Plain Old Java Object. It has properties, getters and setters for respective properties. It may also override Object.toString() and Object.equals().

Java Beans : See Wiki link.

Normal Class : Any java Class.

Append Char To String in C?

In my case, this was the best solution I found:

snprintf(str, sizeof str, "%s%c", str, c);

Set form backcolor to custom color

With Winforms you can use Form.BackColor to do this.
From within the Form's code:

BackColor = Color.LightPink;

If you mean a WPF Window you can use the Background property.
From within the Window's code:

Background = Brushes.LightPink;

Convert JSON to Map

Try this code:

  public static Map<String, Object> convertJsonIntoMap(String jsonFile) {
        Map<String, Object> map = new HashMap<>();
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
            mapper.readValue(jsonFile, new TypeReference<Map<String, Object>>() {
            });
            map = mapper.readValue(jsonFile, new TypeReference<Map<String, String>>() {
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }

Node.js/Express routing with get params

Your route isn't ok, it should be like this (with ':')

app.get('/documents/:format/:type', function (req, res) {
   var format = req.params.format,
       type = req.params.type;
});

Also you cannot interchange parameter order unfortunately. For more information on req.params (and req.query) check out the api reference here.

How to call a function, PostgreSQL

We can have two ways of calling the functions written in pgadmin for postgre sql database.

Suppose we have defined the function as below:

CREATE OR REPLACE FUNCTION helloWorld(name text) RETURNS void AS $helloWorld$
DECLARE
BEGIN
    RAISE LOG 'Hello, %', name;
END;
$helloWorld$ LANGUAGE plpgsql;

We can call the function helloworld in one of the following way:

SELECT "helloworld"('myname');

SELECT public.helloworld('myname')

How to convert strings into integers in Python?

You can do this with a list comprehension:

T2 = [[int(column) for column in row] for row in T1]

The inner list comprehension ([int(column) for column in row]) builds a list of ints from a sequence of int-able objects, like decimal strings, in row. The outer list comprehension ([... for row in T1])) builds a list of the results of the inner list comprehension applied to each item in T1.

The code snippet will fail if any of the rows contain objects that can't be converted by int. You'll need a smarter function if you want to process rows containing non-decimal strings.

If you know the structure of the rows, you can replace the inner list comprehension with a call to a function of the row. Eg.

T2 = [parse_a_row_of_T1(row) for row in T1]

Rails DB Migration - How To Drop a Table?

Write your migration manually. E.g. run rails g migration DropUsers.

As for the code of the migration I'm just gonna quote Maxwell Holder's post Rails Migration Checklist

BAD - running rake db:migrate and then rake db:rollback will fail

class DropUsers < ActiveRecord::Migration
  def change
    drop_table :users
  end
end

GOOD - reveals intent that migration should not be reversible

class DropUsers < ActiveRecord::Migration
  def up
    drop_table :users
  end

  def down
    fail ActiveRecord::IrreversibleMigration
  end
end

BETTER - is actually reversible

class DropUsers < ActiveRecord::Migration
  def change
    drop_table :users do |t|
      t.string :email, null: false
      t.timestamps null: false
    end
  end
end

Animate an element's width from 0 to 100%, with it and it's wrapper being only as wide as they need to be, without a pre-set width, in CSS3 or jQuery

Got it to work by transitioning the padding as well as the width.

JSFiddle: http://jsfiddle.net/tuybk748/1/

<div class='label gray'>+
</div><!-- must be connected to prevent gap --><div class='contents-wrapper'>
    <div class="gray contents">These are the contents of this div</div>
</div>
.gray {
    background: #ddd;
}
.contents-wrapper, .label, .contents {
    display: inline-block;
}
.label, .contents {
    overflow: hidden; /* must be on both divs to prevent dropdown behavior */
    height: 20px;
}
.label {
    padding: 10px 10px 15px;
}
.contents {
    padding: 10px 0px 15px; /* no left-right padding at beginning */
    white-space: nowrap; /* keeps text all on same line */
    width: 0%;
    -webkit-transition: width 1s ease-in-out, padding-left 1s ease-in-out, 
        padding-right 1s ease-in-out;
    -moz-transition: width 1s ease-in-out, padding-left 1s ease-in-out, 
        padding-right 1s ease-in-out;
    -o-transition: width 1s ease-in-out, padding-left 1s ease-in-out, 
        padding-right 1s ease-in-out;
    transition: width 1s ease-in-out, padding-left 1s ease-in-out, 
        padding-right 1s ease-in-out;
}
.label:hover + .contents-wrapper .contents {
    width: 100%;
    padding-left: 10px;
    padding-right: 10px;
}

Go install fails with error: no install location for directory xxx outside GOPATH

I'm on Windows, and I got it by giving command go help gopath to cmd, and read the bold text in the instruction,

that is if code you wnat to install is at ..BaseDir...\SomeProject\src\basic\set, the GOPATH should not be the same location as code, it should be just Base Project DIR: ..BaseDir...\SomeProject.

The GOPATH environment variable lists places to look for Go code. On Unix, the value is a colon-separated string. On Windows, the value is a semicolon-separated string. On Plan 9, the value is a list.

If the environment variable is unset, GOPATH defaults to a subdirectory named "go" in the user's home directory ($HOME/go on Unix, %USERPROFILE%\go on Windows), unless that directory holds a Go distribution. Run "go env GOPATH" to see the current GOPATH.

See https://golang.org/wiki/SettingGOPATH to set a custom GOPATH.

Each directory listed in GOPATH must have a prescribed structure:

The src directory holds source code. The path below src determines the import path or executable name.

The pkg directory holds installed package objects. As in the Go tree, each target operating system and architecture pair has its own subdirectory of pkg (pkg/GOOS_GOARCH).

If DIR is a directory listed in the GOPATH, a package with source in DIR/src/foo/bar can be imported as "foo/bar" and has its compiled form installed to "DIR/pkg/GOOS_GOARCH/foo/bar.a".

The bin directory holds compiled commands. Each command is named for its source directory, but only the final element, not the entire path. That is, the command with source in DIR/src/foo/quux is installed into DIR/bin/quux, not DIR/bin/foo/quux. The "foo/" prefix is stripped so that you can add DIR/bin to your PATH to get at the installed commands. If the GOBIN environment variable is set, commands are installed to the directory it names instead of DIR/bin. GOBIN must be an absolute path.

Here's an example directory layout:

GOPATH=/home/user/go

/home/user/go/
    src/
        foo/
            bar/               (go code in package bar)
                x.go
            quux/              (go code in package main)
                y.go
    bin/
        quux                   (installed command)
    pkg/
        linux_amd64/
            foo/
                bar.a          (installed package object)

..........

if GOPATH has been set to Base Project DIR and still has this problem, in windows you can try to set GOBIN as Base Project DIR\bin or %GOPATH%\bin.

Difference between ProcessBuilder and Runtime.exec()

Look at how Runtime.getRuntime().exec() passes the String command to the ProcessBuilder. It uses a tokenizer and explodes the command into individual tokens, then invokes exec(String[] cmdarray, ......) which constructs a ProcessBuilder.

If you construct the ProcessBuilder with an array of strings instead of a single one, you'll get to the same result.

The ProcessBuilder constructor takes a String... vararg, so passing the whole command as a single String has the same effect as invoking that command in quotes in a terminal:

shell$ "command with args"

When to use LinkedList over ArrayList in Java?

Operation get(i) in ArrayList is faster than LinkedList, because:
ArrayList: Resizable-array implementation of the List interface
LinkedList: Doubly-linked list implementation of the List and Deque interfaces

Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.

Webpack - webpack-dev-server: command not found

I had the same issue but the below steps helped me to get out of it.

  1. Installing the 'webpack-dev-server' locally (In the project directory as it was not picking from the global installation)

    npm install --save webpack-dev-server

Can verify whether 'webpack-dev-server' folder exists inside node_modules.

  1. Running using npx for running directly

npx webpack-dev-server --mode development --config ./webpack.dev.js

npm run start also works fine where your entry in package.json scripts should be like the above like without npx.

How to only find files in a given directory, and ignore subdirectories using bash

This may do what you want:

find /dev \( ! -name /dev -prune \) -type f -print

Reset Entity-Framework Migrations

To fix this, You need to:

  1. Delete all *.cs files in the Migrations Folder.

  2. Delete the _MigrationHistory Table in the Database

  3. Run Enable-Migrations -EnableAutomaticMigrations -Force

  4. Run Add-Migration Reset

Then, in the public partial class Reset : DbMigration class, you need to comment all of the existing and current Tables:

public override void Up()
{
// CreateTable(
// "dbo.<EXISTING TABLE NAME IN DATABASE>
// ...
// }
...
}

If you miss this bit all will fail and you have to start again!

  1. Now Run Update-Database -verbose

This should be successful if you have done the above correctly, and now you can carry on as normal.

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

I got the same error because of a simple typo in vhost.conf. Remember to make sure you don't have any errors in the config files.

apachectl configtest

Get the cell value of a GridView row

Expanding on Dennis R answer above ... This will get the value based on the Heading Text (so you don't need to know what column...especially if its dynamic changing).

Example setting a session variable on SelectedIndexChange.

    protected void gvCustomer_SelectedIndexChanged(object sender, EventArgs e)
    {
        int iCustomerID = Convert.ToInt32(Library.gvGetVal(gvCustomer, "CustomerID"));
        Session[SSS.CustomerID] = iCustomerID;
    }

public class Library
{
    public static string gvGetVal(GridView gvGrid, string sHeaderText)
    {
        string sRetVal = string.Empty;
        if (gvGrid.Rows.Count > 0)
        {
            if (gvGrid.SelectedRow != null)
            {
                GridViewRow row = gvGrid.SelectedRow;
                int iCol = gvGetColumn(gvGrid, sHeaderText);
                if (iCol > -1)
                    sRetVal = row.Cells[iCol].Text;
            }
        }
        return sRetVal;
    }

    private static int gvGetColumn(GridView gvGrid, string sHeaderText)
    {
        int iRetVal = -1;
        for (int i = 0; i < gvGrid.Columns.Count; i++)
        {
            if (gvGrid.Columns[i].HeaderText.ToLower().Trim() == sHeaderText.ToLower().Trim())
            {
                iRetVal = i;
            }
        }
        return iRetVal;
    }
}

How to extract IP Address in Spring MVC Controller get call?

I am late here, but this might help someone looking for the answer. Typically servletRequest.getRemoteAddr() works.

In many cases your application users might be accessing your web server via a proxy server or maybe your application is behind a load balancer.

So you should access the X-Forwarded-For http header in such a case to get the user's IP address.

e.g. String ipAddress = request.getHeader("X-FORWARDED-FOR");

Hope this helps.

Skip first entry in for loop in python?

The other answers only work for a sequence.

For any iterable, to skip the first item:

itercars = iter(cars)
next(itercars)
for car in itercars:
    # do work

If you want to skip the last, you could do:

itercars = iter(cars)
# add 'next(itercars)' here if you also want to skip the first
prev = next(itercars)
for car in itercars:
    # do work on 'prev' not 'car'
    # at end of loop:
    prev = car
# now you can do whatever you want to do to the last one on 'prev'

How can I check if a jQuery plugin is loaded?

This sort of approach should work.

var plugin_exists = true;

try {
  // some code that requires that plugin here
} catch(err) {
  plugin_exists = false;
}

Renaming the current file in Vim

Vim does have a rename function, but unfortunately it does not retain the history.

The easiest OS agnostic way to rename a file without losing the history would be:

:saveas new_file_name
:call delete(expand('#:p'))

expand('#:p') returns the full path of the older file.

Use :bd # if you also want to delete the older file from the buffer list.

Or create a plugin

If you want to use a quick command to rename the file, add a new file under ~/.vim/plugin with the following contents:

function! s:rename_file(new_file_path)
  execute 'saveas ' . a:new_file_path
  call delete(expand('#:p'))
  bd #
endfunction

command! -nargs=1 -complete=file Rename call <SID>rename_file(<f-args>)

The command Rename will help you to quickly rename a file.

How to use index in select statement?

In general, the index will be used if the assumed cost of using the index, and then possibly having to perform further bookmark lookups is lower than the cost of just scanning the entire table.

If your query is of the form:

SELECT Name from Table where Name = 'Boris'

And 1 row out of 1000 has the name Boris, it will almost certainly be used. If everyone's name is Boris, it will probably resort to a table scan, since the index is unlikely to be a more efficient strategy to access the data.

If it's a wide table (lot's of columns) and you do:

SELECT * from Table where Name = 'Boris'

Then it may still choose to perform the table scan, if it's a reasonable assumption that it's going to take more time retrieving the other columns from the table than it will to just look up the name, or again, if it's likely to be retrieving a lot of rows anyway.

PHP: merge two arrays while keeping keys instead of reindexing?

Considering that you have

$replaced = array('1' => 'value1', '4' => 'value4');
$replacement = array('4' => 'value2', '6' => 'value3');

Doing $merge = $replacement + $replaced; will output:

Array('4' => 'value2', '6' => 'value3', '1' => 'value1');

The first array from sum will have values in the final output.

Doing $merge = $replaced + $replacement; will output:

Array('1' => 'value1', '4' => 'value4', '6' => 'value3');

How to resolve : Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

This should work

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

and moreover please let us know why are you importing all these class

<%@ page import="com.library.controller.*"%> 
<%@ page import="com.library.dao.*" %> 
<%@ page import="java.util.*" %> 
<%@ page import="java.lang.*" %> 
<%@ page import="java.util.Date" %>

We don't need to include java.lang as it is the default package.

How to select data where a field has a min value in MySQL?

Use HAVING MIN(...)

Something like:

SELECT MIN(price) AS price, pricegroup
FROM articles_prices
WHERE articleID=10
GROUP BY pricegroup
HAVING MIN(price) > 0;

Oracle query execution time

One can issue the SQL*Plus command SET TIMING ON to get wall-clock times, but one can't take, for example, fetch time out of that trivially.

The AUTOTRACE setting, when used as SET AUTOTRACE TRACEONLY will suppress output, but still perform all of the work to satisfy the query and send the results back to SQL*Plus, which will suppress it.

Lastly, one can trace the SQL*Plus session, and manually calculate the time spent waiting on events which are client waits, such as "SQL*Net message to client", "SQL*Net message from client".

Mouseover or hover vue.js

Please take a look at the vue-mouseover package if you are not satisfied how does this code look:

<div
    @mouseover="isMouseover = true"
    @mouseleave="isMouseover = false"
/>

vue-mouseover provides a v-mouseover directive that automaticaly updates the specified data context property when the cursor enters or leaves an HTML element the directive is attached to.

By default in the next example isMouseover property will be true when the cursor is over an HTML element and false otherwise:

<div v-mouseover="isMouseover" />

Also by default isMouseover will be initially assigned when v-mouseover is attached to the div element, so it will not remain unassigned before the first mouseenter/mouseleave event.

You can specify custom values via v-mouseover-value directive:

<div
    v-mouseover="isMouseover"
    v-mouseover-value="customMouseenterValue"/>

or

<div
    v-mouseover="isMouseover"
    v-mouseover-value="{
        mouseenter: customMouseenterValue,
        mouseleave: customMouseleaveValue
    }"
/>

Custom default values can be passed to the package via options object during setup.

MongoDB: How to find out if an array field contains an element?

[edit based on this now being possible in recent versions]

[Updated Answer] You can query the following way to get back the name of class and the student id only if they are already enrolled.

db.student.find({},
 {_id:0, name:1, students:{$elemMatch:{$eq:ObjectId("51780f796ec4051a536015cf")}}})

and you will get back what you expected:

{ "name" : "CS 101", "students" : [ ObjectId("51780f796ec4051a536015cf") ] }
{ "name" : "Literature" }
{ "name" : "Physics", "students" : [ ObjectId("51780f796ec4051a536015cf") ] }

[Original Answer] It's not possible to do what you want to do currently. This is unfortunate because you would be able to do this if the student was stored in the array as an object. In fact, I'm a little surprised you are using just ObjectId() as that will always require you to look up the students if you want to display a list of students enrolled in a particular course (look up list of Id's first then look up names in the students collection - two queries instead of one!)

If you were storing (as an example) an Id and name in the course array like this:

{
        "_id" : ObjectId("51780fb5c9c41825e3e21fc6"),
        "name" : "Physics",
        "students" : [
                {id: ObjectId("51780f796ec4051a536015cf"), name: "John"},
                {id: ObjectId("51780f796ec4051a536015d0"), name: "Sam"}
        ]
}

Your query then would simply be:

db.course.find( { }, 
                { students : 
                    { $elemMatch : 
                       { id : ObjectId("51780f796ec4051a536015d0"), 
                         name : "Sam" 
                       } 
                    } 
                } 
);

If that student was only enrolled in CS 101 you'd get back:

{ "name" : "Literature" }
{ "name" : "Physics" }
{
    "name" : "CS 101",
    "students" : [
        {
            "id" : ObjectId("51780f796ec4051a536015cf"),
            "name" : "John"
        }
    ]
}

How can I break up this long line in Python?

You can use textwrap module to break it in multiple lines

import textwrap
str="ABCDEFGHIJKLIMNO"
print("\n".join(textwrap.wrap(str,8)))

ABCDEFGH
IJKLIMNO

From the documentation:

textwrap.wrap(text[, width[, ...]])
Wraps the single paragraph in text (a string) so every line is at most width characters long. Returns a list of output lines, without final newlines.

Optional keyword arguments correspond to the instance attributes of TextWrapper, documented below. width defaults to 70.

See the TextWrapper.wrap() method for additional details on how wrap() behaves.

Generating matplotlib graphs without a running X server

You need to use the matplotlib API directly rather than going through the pylab interface. There's a good example here:

http://www.dalkescientific.com/writings/diary/archive/2005/04/23/matplotlib_without_gui.html

Can I assume (bool)true == (int)1 for any C++ compiler?

According to the standard, you should be safe with that assumption. The C++ bool type has two values - true and false with corresponding values 1 and 0.

The thing to watch about for is mixing bool expressions and variables with BOOL expression and variables. The latter is defined as FALSE = 0 and TRUE != FALSE, which quite often in practice means that any value different from 0 is considered TRUE.

A lot of modern compilers will actually issue a warning for any code that implicitly tries to cast from BOOL to bool if the BOOL value is different than 0 or 1.

Writing a dictionary to a csv file with one line for every 'key: value'

Just to give an option, writing a dictionary to csv file could also be done with the pandas package. With the given example it could be something like this:

mydict = {'key1': 'a', 'key2': 'b', 'key3': 'c'}

import pandas as pd

(pd.DataFrame.from_dict(data=mydict, orient='index')
   .to_csv('dict_file.csv', header=False))

The main thing to take into account is to set the 'orient' parameter to 'index' inside the from_dict method. This lets you choose if you want to write each dictionary key in a new row.

Additionaly, inside the to_csv method the header parameter is set to False just to have only the dictionary elements without annoying rows. You can always set column and index names inside the to_csv method.

Your output would look like this:

key1,a
key2,b
key3,c

If instead you want the keys to be the column's names, just use the default 'orient' parameter that is 'columns', as you could check in the documentation links.

C default arguments

Yes, with features of C99 you may do this. This works without defining new data structures or so and without the function having to decide at runtime how it was called, and without any computational overhead.

For a detailed explanation see my post at

http://gustedt.wordpress.com/2010/06/03/default-arguments-for-c99/

Jens

Limiting Python input strings to certain characters and lengths

We can use assert here.

def _input(inp_str:str):
    try:
        assert len(inp_str)<=15,print('More than 15 characters present')
        assert all('a'<=i<='z' for i in inp_str),print('Characters other than "a"-"z" are found')
        return inp_str
    except Exception as e:
        pass

_input('abcd')
#abcd
_input('abc d')
#Characters other than "a"-"z" are found
_input('abcdefghijklmnopqrst')
#More than 15 characters present

Force decimal point instead of comma in HTML5 number input (client-side)

With the step attribute specified to the precision of the decimals you want, and the lang attribute [which is set to a locale that formats decimals with period], your html5 numeric input will accept decimals. eg. to take values like 10.56; i mean 2 decimal place numbers, do this:

<input type="number" step="0.01" min="0" lang="en" value="1.99">

You can further specify the max attribute for the maximum allowable value.

Edit Add a lang attribute to the input element with a locale value that formats decimals with point instead of comma

Javascript: The prettiest way to compare one value against multiple values

Why not using indexOf from array like bellow?

if ([foo, bar].indexOf(foobar) !== -1) {
    // do something
}

Just plain Javascript, no frameworks or libraries but it will not work on IE < 9.

auto create database in Entity Framework Core

For EF Core 2.0+ I had to take a different approach because they changed the API. As of March 2019 Microsoft recommends you put your database migration code in your application entry class but outside of the WebHost build code.

public class Program
{
    public static void Main(string[] args)
    {
        var host = CreateWebHostBuilder(args).Build();
        using (var serviceScope = host.Services.CreateScope())
        {
            var context = serviceScope.ServiceProvider.GetRequiredService<PersonContext>();
            context.Database.Migrate();
        }
        host.Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

View list of all JavaScript variables in Google Chrome Console

When script execution is halted (e.g., on a breakpoint) you can simply view all globals in the right pane of the Developer Tools window:

chrome-globals

GIT: Checkout to a specific folder

I defined an git alias to achieve just this (before I found this question).

It's a short bash function which saves the current path, switch to the git repo, does a checkout and return where it started.

git checkto develop ~/my_project_git

This e.g. would checkout the develop branch into "~/my_project_git" directory.

This is the alias code inside ~/.gitconfig:

[alias]
    checkTo = "!f(){ [ -z \"$1\" ] && echo \"Need to specify branch.\" && \
               exit 1; [ -z \"$2\" ] && echo \"Need to specify target\
               dir\" && exit 2; cDir=\"$(pwd)\"; cd \"$2\"; \
               git checkout \"$1\"; cd \"$cDir\"; };f"

Ruby: Merging variables in to a string

["The", animal, action, "the", second_animal].join(" ")

is another way to do it.

How do I add a newline to a windows-forms TextBox?

make sure you textbox is set for multiline then you wont need any extra dims vbnewline will work just fine

Who sets response content-type in Spring MVC (@ResponseBody)

You can use produces to indicate the type of the response you are sending from the controller. This "produces" keyword will be most useful in ajax request and was very helpful in my project

@RequestMapping(value = "/aURLMapping.htm", method = RequestMethod.GET, produces = "text/html; charset=utf-8") 

public @ResponseBody String getMobileData() {

}

How do you determine what technology a website is built on?

Go to Netcraft and use the "What's that site running?" search box in the top left corner. Click here for the report on Stack Overflow. It won't necessarily be correct (e.g., there could be caching or load balancing in the way), but it often gives you the clue you need.

jquery, domain, get URL

You can use below codes for get different parameters of Current URL

alert("document.URL : "+document.URL);
alert("document.location.href : "+document.location.href);
alert("document.location.origin : "+document.location.origin);
alert("document.location.hostname : "+document.location.hostname);
alert("document.location.host : "+document.location.host);
alert("document.location.pathname : "+document.location.pathname);

Does PHP have threading?

Here is an example of what Wilco suggested:

$cmd = 'nohup nice -n 10 /usr/bin/php -c /path/to/php.ini -f /path/to/php/file.php action=generate var1_id=23 var2_id=35 gen_id=535 > /path/to/log/file.log & echo $!';
$pid = shell_exec($cmd);

Basically this executes the PHP script at the command line, but immediately returns the PID and then runs in the background. (The echo $! ensures nothing else is returned other than the PID.) This allows your PHP script to continue or quit if you want. When I have used this, I have redirected the user to another page, where every 5 to 60 seconds an AJAX call is made to check if the report is still running. (I have a table to store the gen_id and the user it's related to.) The check script runs the following:

exec('ps ' . $pid , $processState);
if (count($processState) < 2) {
     // less than 2 rows in the ps, therefore report is complete
}

There is a short post on this technique here: http://nsaunders.wordpress.com/2007/01/12/running-a-background-process-in-php/

How to debug stored procedures with print statements?

Before I get to my reiterated answer; I am confessing that the only answer I would accept here is this one by KM. above. I down voted the other answers because none of them actually answered the question asked or they were not adequate. PRINT output does indeed show up in the Message window, but that is not what was asked at all.

Why doesn't the PRINT statement output show during my Stored Procedure execution?
The short version of this answer is that you are sending your sproc's execution over to the SQL server and it isn't going to respond until it is finished with the whole transaction. Here is a better answer located at this external link.

  • For even more opinions/observations focus your attention on this SO post here.
  • Specifically look at this answer of the same post by Phil_factor (Ha ha! Love the SQL humor)
  • Regarding the suggestion of using RAISERROR WITH NOWAIT look at this answer of the same post by JimCarden

Don't do these things

  1. Some people are under the impression that they can just use a GO statement after their PRINT statement, but you CANNOT use the GO statement INSIDE of a sproc. So that solution is out.
  2. I don't recommend SELECT-ing your print statements because it is just going to muddy your result set with nonsense and if your sproc is supposed to be consumed by a program later, then you will have to know which result sets to skip when looping through the results from your data reader. This is just a bad idea, so don't do it.
  3. Another problem with SELECT-ING your print statements is that they don't always show up immediately. I have had different experiences with this for different executions, so don't expect any kind of consistency with this methodology.

Alternative to PRINT inside of a Stored Procedure
Really this is kind of an icky work around in my opinion because the syntax is confusing in the context that it is being used in, but who knows maybe it will be updated in the future by Microsoft. I just don't like the idea of raising an error for the sole purpose of printing out debug info...

It seems like the only way around this issue is to use, as has been explained numerous times already RAISERROR WITH NOWAIT. I am providing an example and pointing out a small problem with this approach:

ALTER
--CREATE 
    PROCEDURE [dbo].[PrintVsRaiseErrorSprocExample]
AS
BEGIN
    SET NOCOUNT ON;

    -- This will print immediately
    RAISERROR ('RE Start', 0, 1) WITH NOWAIT
    SELECT 1;

    -- Five second delay to simulate lengthy execution
    WAITFOR DELAY '00:00:05'

    -- This will print after the five second delay
    RAISERROR ('RE End', 0, 1) WITH NOWAIT
    SELECT 2;
END

GO

EXEC [dbo].[PrintVsRaiseErrorSprocExample]

Both SELECT statement results will only show after the execution is finished and the print statements will show in the order shown above.

Potential problem with this approach
Let's say you have both your PRINT statement and RAISERROR statement one after the other, then they both print. I'm sure this has something to do with buffering, but just be aware that this can happen.

ALTER
--CREATE 
    PROCEDURE [dbo].[PrintVsRaiseErrorSprocExample2]
AS
BEGIN
    SET NOCOUNT ON;

    -- Both the PRINT and RAISERROR statements will show
    PRINT 'P Start';
    RAISERROR ('RE Start', 0, 1) WITH NOWAIT
    SELECT 1;

    WAITFOR DELAY '00:00:05'

    -- Both the PRINT and RAISERROR statements will show
    PRINT 'P End'
    RAISERROR ('RE End', 0, 1) WITH NOWAIT
    SELECT 2;
END

GO

EXEC [dbo].[PrintVsRaiseErrorSprocExample2]

Therefore the work around here is, don't use both PRINT and RAISERROR, just choose one over the other. If you want your output to show during the execution of a sproc then use RAISERROR WITH NOWAIT.

Exclude subpackages from Spring autowiring?

For Spring 4 I use the following
(I am posting it as the question is 4 years old and more people use Spring 4 than Spring 3.1):

@Configuration
@ComponentScan(basePackages = "com.example", 
  excludeFilters = @Filter(type=FilterType.REGEX,pattern="com\\.example\\.ignore\\..*")) 
public class RootConfig {
    // ...
}

How to Verify if file exist with VB script

There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :

Option Explicit
DIM fso    
Set fso = CreateObject("Scripting.FileSystemObject")

If (fso.FileExists("C:\Program Files\conf")) Then
  WScript.Echo("File exists!")
  WScript.Quit()
Else
  WScript.Echo("File does not exist!")
End If

WScript.Quit()

Why does cURL return error "(23) Failed writing body"?

So it was a problem of encoding. Iconv solves the problem

curl 'http://www.multitran.ru/c/m.exe?CL=1&s=hello&l1=1' | iconv -f windows-1251 | tr -dc '[:print:]' | ...

WordPress: get author info from post id

<?php
  $field = 'display_name';
  the_author_meta($field);
?>

Valid values for the $field parameter include:

  • admin_color
  • aim
  • comment_shortcuts
  • description
  • display_name
  • first_name
  • ID
  • jabber
  • last_name
  • nickname
  • plugins_last_view
  • plugins_per_page
  • rich_editing
  • syntax_highlighting
  • user_activation_key
  • user_description
  • user_email
  • user_firstname
  • user_lastname
  • user_level
  • user_login
  • user_nicename
  • user_pass
  • user_registered
  • user_status
  • user_url
  • yim

What is causing the error `string.split is not a function`?

Change this...

var string = document.location;

to this...

var string = document.location + '';

This is because document.location is a Location object. The default .toString() returns the location in string form, so the concatenation will trigger that.


You could also use document.URL to get a string.

Attaching click event to a JQuery object not yet added to the DOM

Maybe bind() would help:

button.bind('click', function() {
  alert('User clicked');
});

WSDL/SOAP Test With soapui

definitions is a root element of WSDL so it looks like you are not loading WSDL.

Edit:

I tested it and it looks like the whole problem is with your web server. Your web server returns WSDL to browser but it doesn't return it to any tool because these tools are using very minimalistic HTTP requests without many HTTP headers. One of missing headers is Accept. Once this header is not included in the request your server throws HTTP 400 Bad request.

The easy approach to continue is opening WSDL in the browser, save the wsdl to a file and import that file to soapUI instead of the WSDL from URL.

What is the best way to seed a database in Rails?

Add it in database migrations, that way everyone gets it as they update. Handle all of your logic in the ruby/rails code, so you never have to mess with explicit ID settings.

Get element by id - Angular2

(<HTMLInputElement>document.getElementById('loginInput')).value = '123';

Angular cannot take HTML elements directly thereby you need to specify the element type by binding the above generic to it.

UPDATE::

This can also be done using ViewChild with #localvariable as shown here, as mentioned in here

<textarea  #someVar  id="tasknote"
                  name="tasknote"
                  [(ngModel)]="taskNote"
                  placeholder="{{ notePlaceholder }}"
                  style="background-color: pink"
                  (blur)="updateNote() ; noteEditMode = false " (click)="noteEditMode = false"> {{ todo.note }} 

</textarea>

import {ElementRef,Renderer2} from '@angular/core';
@ViewChild('someVar') el:ElementRef;

constructor(private rd: Renderer2) {}

ngAfterViewInit() {
      console.log(this.rd); 
      this.el.nativeElement.focus();      //<<<=====same as oldest way
}

C Programming: How to read the whole file contents into a buffer

Here is what I would recommend.

It should conform to C89, and be completely portable. In particular, it works also on pipes and sockets on POSIXy systems.

The idea is that we read the input in large-ish chunks (READALL_CHUNK), dynamically reallocating the buffer as we need it. We only use realloc(), fread(), ferror(), and free():

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

/* Size of each input chunk to be
   read and allocate for. */
#ifndef  READALL_CHUNK
#define  READALL_CHUNK  262144
#endif

#define  READALL_OK          0  /* Success */
#define  READALL_INVALID    -1  /* Invalid parameters */
#define  READALL_ERROR      -2  /* Stream error */
#define  READALL_TOOMUCH    -3  /* Too much input */
#define  READALL_NOMEM      -4  /* Out of memory */

/* This function returns one of the READALL_ constants above.
   If the return value is zero == READALL_OK, then:
     (*dataptr) points to a dynamically allocated buffer, with
     (*sizeptr) chars read from the file.
     The buffer is allocated for one extra char, which is NUL,
     and automatically appended after the data.
   Initial values of (*dataptr) and (*sizeptr) are ignored.
*/
int readall(FILE *in, char **dataptr, size_t *sizeptr)
{
    char  *data = NULL, *temp;
    size_t size = 0;
    size_t used = 0;
    size_t n;

    /* None of the parameters can be NULL. */
    if (in == NULL || dataptr == NULL || sizeptr == NULL)
        return READALL_INVALID;

    /* A read error already occurred? */
    if (ferror(in))
        return READALL_ERROR;

    while (1) {

        if (used + READALL_CHUNK + 1 > size) {
            size = used + READALL_CHUNK + 1;

            /* Overflow check. Some ANSI C compilers
               may optimize this away, though. */
            if (size <= used) {
                free(data);
                return READALL_TOOMUCH;
            }

            temp = realloc(data, size);
            if (temp == NULL) {
                free(data);
                return READALL_NOMEM;
            }
            data = temp;
        }

        n = fread(data + used, 1, READALL_CHUNK, in);
        if (n == 0)
            break;

        used += n;
    }

    if (ferror(in)) {
        free(data);
        return READALL_ERROR;
    }

    temp = realloc(data, used + 1);
    if (temp == NULL) {
        free(data);
        return READALL_NOMEM;
    }
    data = temp;
    data[used] = '\0';

    *dataptr = data;
    *sizeptr = used;

    return READALL_OK;
}

Above, I've used a constant chunk size, READALL_CHUNK == 262144 (256*1024). This means that in the worst case, up to 262145 chars are wasted (allocated but not used), but only temporarily. At the end, the function reallocates the buffer to the optimal size. Also, this means that we do four reallocations per megabyte of data read.

The 262144-byte default in the code above is a conservative value; it works well for even old minilaptops and Raspberry Pis and most embedded devices with at least a few megabytes of RAM available for the process. Yet, it is not so small that it slows down the operation (due to many read calls, and many buffer reallocations) on most systems.

For desktop machines at this time (2017), I recommend a much larger READALL_CHUNK, perhaps #define READALL_CHUNK 2097152 (2 MiB).

Because the definition of READALL_CHUNK is guarded (i.e., it is defined only if it is at that point in the code still undefined), you can override the default value at compile time, by using (in most C compilers) -DREADALL_CHUNK=2097152 command-line option -- but do check your compiler options for defining a preprocessor macro using command-line options.

Equivalent of LIMIT for DB2

@elcool's solution is a smart idea, but you need to know total number of rows (which can even change while you are executing the query!). So I propose a modified version, which unfortunately needs 3 subqueries instead of 2:

select * from (
    select * from (
        select * from MYLIB.MYTABLE
        order by MYID asc 
        fetch first {last} rows only 
        ) I 
    order by MYID desc
    fetch first {length} rows only
    ) II
order by MYID asc

where {last} should be replaced with row number of the last record I need and {length} should be replaced with the number of rows I need, calculated as last row - first row + 1.

E.g. if I want rows from 10 to 25 (totally 16 rows), {last} will be 25 and {length} will be 25-10+1=16.

HTML iframe - disable scroll

Add this styles..for your iframe tag..

overflow-x:hidden;
overflow-y:hidden;

Android: java.lang.SecurityException: Permission Denial: start Intent

In your Manifest file write this before </application >

<activity android:name="com.fsck.k9.activity.MessageList">
   <intent-filter>
      <action android:name="android.intent.action.MAIN">
      </action>
   </intent-filter>
</activity>

and tell me if it solves your issue :)

Global keyboard capture in C# application

private void buttonHook_Click(object sender, EventArgs e)
{
    // Hooks only into specified Keys (here "A" and "B").
    // (***) Use this constructor

    _globalKeyboardHook = new GlobalKeyboardHook(new Keys[] { Keys.A, Keys.B });

    // Hooks into all keys.
    // (***) Or this - not both

    _globalKeyboardHook = new GlobalKeyboardHook();
    _globalKeyboardHook.KeyboardPressed += OnKeyPressed;
}

And then is working fine.

How do you allow spaces to be entered using scanf?

Don't use scanf() to read strings without specifying a field width. You should also check the return values for errors:

#include <stdio.h>

#define NAME_MAX    80
#define NAME_MAX_S "80"

int main(void)
{
    static char name[NAME_MAX + 1]; // + 1 because of null
    if(scanf("%" NAME_MAX_S "[^\n]", name) != 1)
    {
        fputs("io error or premature end of line\n", stderr);
        return 1;
    }

    printf("Hello %s. Nice to meet you.\n", name);
}

Alternatively, use fgets():

#include <stdio.h>

#define NAME_MAX 80

int main(void)
{
    static char name[NAME_MAX + 2]; // + 2 because of newline and null
    if(!fgets(name, sizeof(name), stdin))
    {
        fputs("io error\n", stderr);
        return 1;
    }

    // don't print newline
    printf("Hello %.*s. Nice to meet you.\n", strlen(name) - 1, name);
}

Include CSS,javascript file in Yii Framework

There are many methods that we can include javascript, css into your Yii App. Today I will demonstrate three simple and helpul methods.

A simple way to add js, css by editing config/main.php

// application components
  'components'=>array(
         // ...
        'clientScript'=>array(
            'packages'=>array(
                'jquery'=>array(
                    'baseUrl'=>'//ajax.googleapis.com/ajax/libs/jquery/1/',
                    'js'=>array('jquery.min.js'),
                )
            ),
        ),
        // ...
  ),

Using getClientScript

Usually, We add in block of code into Controller or layout of your theme

$baseUrl = Yii::app()->baseUrl; 
$cs = Yii::app()->getClientScript();
$cs->registerScriptFile($baseUrl.'/js/yourscript.js');
$cs->registerCssFile($baseUrl.'/css/yourcss.css');

Or shorter:

Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/path/to/your/javascript/file',CClientScript::POS_END);
Yii::app()->clientScript->registerCssFile(Yii::app()->baseUrl.'/path/to/css/file');

Include core js files

Yii::app()->clientScript->registerCoreScript('jquery');     
Yii::app()->clientScript->registerCoreScript('jquery.ui');

Faster Yii API Document: http://yii.codexamples.com/

IOError: [Errno 32] Broken pipe: Python

I know this is not the "proper" way to do it, but if you are simply interested in getting rid of the error message, you could try this workaround:

python your_python_code.py 2> /dev/null | other_command

How to use vim in the terminal?

Run vim from the terminal. For the basics, you're advised to run the command vimtutor.

# On your terminal command line:
$ vim

If you have a specific file to edit, pass it as an argument.

$ vim yourfile.cpp

Likewise, launch the tutorial

$ vimtutor

How do I find and replace all occurrences (in all files) in Visual Studio Code?

Visual Studio Code: Version: 1.53.2


If you are looking for the answer in 2021 (like I was), the answer is here on the Microsoft website but honestly hard to follow.

Go to Edit > Replace in Files

enter image description here

From there it is similar to the search funtionality for a single file.

I changed the name of a class I was using across files and this worked perfectly.

Note: If you cannot find the Replace in Files option, first click on the Search icon (magnifying glass) and then it will appear.

How do you use the "WITH" clause in MySQL?

Mysql Developers Team announced that version 8.0 will have Common Table Expressions in MySQL (CTEs). So it will be possible to write queries like this:


WITH RECURSIVE my_cte AS
(
  SELECT 1 AS n
  UNION ALL
  SELECT 1+n FROM my_cte WHERE n<10
)
SELECT * FROM my_cte;
+------+
| n    |
+------+
|    1 |
|    2 |
|    3 |
|    4 |
|    5 |
|    6 |
|    7 |
|    8 |
|    9 |
|   10 |
+------+
10 rows in set (0,00 sec)

How to do a timer in Angular 5

This may be overkill for what you're looking for, but there is an npm package called marky that you can use to do this. It gives you a couple of extra features beyond just starting and stopping a timer. You just need to install it via npm and then import the dependency anywhere you'd like to use it. Here is a link to the npm package: https://www.npmjs.com/package/marky

An example of use after installing via npm would be as follows:

import * as _M from 'marky';

@Component({
 selector: 'app-test',
 templateUrl: './test.component.html',
 styleUrls: ['./test.component.scss']
})

export class TestComponent implements OnInit {
 Marky = _M;
}

constructor() {}

ngOnInit() {}

startTimer(key: string) {
 this.Marky.mark(key);
}

stopTimer(key: string) {
 this.Marky.stop(key);
}

key is simply a string which you are establishing to identify that particular measurement of time. You can have multiple measures which you can go back and reference your timer stats using the keys you create.

How to make an embedded video not autoplay

A couple of wires are crossed here. The various autoplay settings that you're working with only affect whether the SWF's root timeline starts out paused or not. So if your SWF had a timeline animation, or if it had an embedded video on the root timeline, then these settings would do what you're after.

However, the SWF you're working with almost certainly has only one frame on its timeline, so these settings won't affect playback at all. That one frame contains some flavor of video playback component, which contains ActionScript that controls how the video behaves. To get that player component to start of paused, you'll have to change the settings of the component itself.

Without knowing more about where the content came from it's hard to say more, but when one publishes from Flash, video player components normally include a parameter for whether to autoplay. If your SWF is being published by an application other than Flash (Captivate, I suppose, but I'm not up on that) then your best bet would be to check the settings for that app. Anyway it's not something you can control from the level of the HTML page. (Unless you were talking to the SWF from JavaScript, and for that to work the video component would have to be designed to allow it.)

System.Net.Http: missing from namespace? (using .net 4.5)

In Visual Studio you can use nuget to load the package

Microsoft.AspNet.WebApi.WebHost

Angular 2 Checkbox Two Way Data Binding

You can just use something like this to have two way data binding:

<input type="checkbox" [checked]="model.property" (change)="model.property = !model.consent_obtained_ind">

Html.fromHtml deprecated in Android N

If you're using Kotlin, I achieved this by using a Kotlin extension:

fun TextView.htmlText(text: String){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        setText(Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY))
    } else {
        setText(Html.fromHtml(text))
    }
}

Then call it like:

textView.htmlText(yourHtmlText)

UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 0: invalid start byte

On read csv, I added an encoding method:

import pandas as pd
dataset = pd.read_csv('sample_data.csv', header= 0,
                        encoding= 'unicode_escape')

EF 5 Enable-Migrations : No context type was found in the assembly

This error getting because of the compiler not getting 'Context' class in your application. So, you can add it manually by Add --> Class and inherit it with 'DbContext' Class For Example :

public class MyDbContext : DbContext
    {
        public DbSet<Customer> Customer { get; set; }
        public MyDbContext()
        {
        }
    }

Converting a string to a date in a cell

To accomodate both data scenarios you have, you will want to use this:

datevalue(text(a2,"mm/dd/yyyy"))

That will give you the date number representation for a cell that Excel has in date, or in text datatype.

Javascript: Call a function after specific time period

Timeout:

setTimeout(() => {
   console.log('Hello Timeout!')
}, 3000);

Interval:

setInterval(() => {
   console.log('Hello Interval!')
}, 2000);