Programs & Examples On #Distributed

Multiple computers working together, using a network to communicate

How to develop Android app completely using python?

There are two primary contenders for python apps on Android

Chaquopy

https://chaquo.com/chaquopy/

This integrates with the Android build system, it provides a Python API for all android features. To quote the site "The complete Android API and user interface toolkit are directly at your disposal."

Beeware (Toga widget toolkit)

https://pybee.org/

This provides a multi target transpiler, supports many targets such as Android and iOS. It uses a generic widget toolkit (toga) that maps to the host interface calls.

Which One?

Both are active projects and their github accounts shows a fair amount of recent activity.

Beeware Toga like all widget libraries is good for getting the basics out to multiple platforms. If you have basic designs, and a desire to expand to other platforms this should work out well for you.

On the other hand, Chaquopy is a much more precise in its mapping of the python API to Android. It also allows you to mix in Java, useful if you want to use existing code from other resources. If you have strict design targets, and predominantly want to target Android this is a much better resource.

How to get current available GPUs in tensorflow?

I am working on TF-2.1 and torch, so I don't want to specific this automacit choosing in any ML frame. I just use original nvidia-smi and os.environ to get a vacant gpu.

def auto_gpu_selection(usage_max=0.01, mem_max=0.05):
"""Auto set CUDA_VISIBLE_DEVICES for gpu

:param mem_max: max percentage of GPU utility
:param usage_max: max percentage of GPU memory
:return:
"""
os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
log = str(subprocess.check_output("nvidia-smi", shell=True)).split(r"\n")[6:-1]
gpu = 0

# Maximum of GPUS, 8 is enough for most
for i in range(8):
    idx = i*3 + 2
    if idx > log.__len__()-1:
        break
    inf = log[idx].split("|")
    if inf.__len__() < 3:
        break
    usage = int(inf[3].split("%")[0].strip())
    mem_now = int(str(inf[2].split("/")[0]).strip()[:-3])
    mem_all = int(str(inf[2].split("/")[1]).strip()[:-3])
    # print("GPU-%d : Usage:[%d%%]" % (gpu, usage))
    if usage < 100*usage_max and mem_now < mem_max*mem_all:
        os.environ["CUDA_VISIBLE_EVICES"] = str(gpu)
        print("\nAuto choosing vacant GPU-%d : Memory:[%dMiB/%dMiB] , GPU-Util:[%d%%]\n" %
              (gpu, mem_now, mem_all, usage))
        return
    print("GPU-%d is busy: Memory:[%dMiB/%dMiB] , GPU-Util:[%d%%]" %
          (gpu, mem_now, mem_all, usage))
    gpu += 1
print("\nNo vacant GPU, use CPU instead\n")
os.environ["CUDA_VISIBLE_EVICES"] = "-1"

If I can get any GPU, it will set CUDA_VISIBLE_EVICES to BUSID of that gpu :

GPU-0 is busy: Memory:[5738MiB/11019MiB] , GPU-Util:[60%]
GPU-1 is busy: Memory:[9688MiB/11019MiB] , GPU-Util:[78%]

Auto choosing vacant GPU-2 : Memory:[1MiB/11019MiB] , GPU-Util:[0%]

else, set to -1 to use CPU:

GPU-0 is busy: Memory:[8900MiB/11019MiB] , GPU-Util:[95%]
GPU-1 is busy: Memory:[4674MiB/11019MiB] , GPU-Util:[35%]
GPU-2 is busy: Memory:[9784MiB/11016MiB] , GPU-Util:[74%]

No vacant GPU, use CPU instead

Note: Use this function before you import any ML frame that require a GPU, then it can automatically choose a gpu. Besides, it's easy for you to set multiple tasks.

Add jars to a Spark Job - spark-submit

When using spark-submit with --master yarn-cluster, the application jar along with any jars included with the --jars option will be automatically transferred to the cluster. URLs supplied after --jars must be separated by commas. That list is included in the driver and executor classpaths

Example :

spark-submit --master yarn-cluster --jars ../lib/misc.jar, ../lib/test.jar --class MainClass MainApp.jar

https://spark.apache.org/docs/latest/submitting-applications.html

Change the location of the ~ directory in a Windows install of Git Bash

Instead of modifying the global profile you could create the .bash_profile in your default $HOME directory (e.g. C:\Users\WhateverUser\.bash_profile) with the following contents:

export HOME="C:\my\projects\dir"
cd "$HOME" # if you'd like it to be the starting dir of the git shell

Hadoop cluster setup - java.net.ConnectException: Connection refused

I was getting the same issue and found that OpenSSH service was not running and it was causing the issue. After starting the SSH service it worked.

To check if SSH service is running or not:

ssh localhost

To start the service, if OpenSSH is already installed:

sudo /etc/init.d/ssh start

How to analyze disk usage of a Docker container

After 1.13.0, Docker includes a new command docker system df to show docker disk usage.

$ docker system df
TYPE            TOTAL        ACTIVE     SIZE        RECLAIMABLE
Images          5            1          2.777 GB    2.647 GB (95%)
Containers      1            1          0 B         0B
Local Volumes   4            1          3.207 GB    2.261 (70%)

To show more detailed information on space usage:

$ docker system df --verbose

The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"

In our case, it helped to add a parameter for SQL Server service:

  1. Go to Services.msc, select SQL Server Service and open Properties.
  2. Choose Startup Parameters and add new parameter –g512
  3. Restart SQL server service.

How to turn off INFO logging in Spark?

For PySpark, you can also set the log level in your scripts with sc.setLogLevel("FATAL"). From the docs:

Control our logLevel. This overrides any user-defined log settings. Valid log levels include: ALL, DEBUG, ERROR, FATAL, INFO, OFF, TRACE, WARN

Generate random array of floats between a range

Why not to combine random.uniform with a list comprehension?

>>> def random_floats(low, high, size):
...    return [random.uniform(low, high) for _ in xrange(size)]
... 
>>> random_floats(0.5, 2.8, 5)
[2.366910411506704, 1.878800401620107, 1.0145196974227986, 2.332600336488709, 1.945869474662082]

Import Excel Spreadsheet Data to an EXISTING sql table?

Saudate, I ran across this looking for a different problem. You most definitely can use the Sql Server Import wizard to import data into a new table. Of course, you do not wish to leave that table in the database, so my suggesting is that you import into a new table, then script the data in query manager to insert into the existing table. You can add a line to drop the temp table created by the import wizard as the last step upon successful completion of the script.

I believe your original issue is in fact related to Sql Server 64 bit and is due to your having a 32 bit Excel and these drivers don't play well together. I did run into a very similar issue when first using 64 bit excel.

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

Below worked for me:

When you come to Server Configuration Screen, Change the Account Name of Database Engine Service to NT AUTHORITY\NETWORK SERVICE and continue installation and it will successfully install all components without any error. - See more at: https://superpctricks.com/sql-install-error-database-engine-recovery-handle-failed/

Center a column using Twitter Bootstrap 3

This is probably not the best answer, but there is one more creative solution to this. As pointed out by koala_dev the column offsetting works only for even column sizes. However, by nesting rows you can achieve centering uneven columns as well.

To stick with the original question where you want to center a column of 1 inside a grid of 12.

  1. Center a column of 2 by offsetting it 5
  2. Make a nested row, so you get a new 12 columns inside your 2 columns.
  3. Since you want to center a column of 1, and 1 is "half" of 2 (what we centered in step 1), you now need to center a column of 6 in your nested row, which is easily done by offsetting it 3.

For example:

<div class="container">
  <div class="row">
    <div class="col-md-offset-5 col-md-2">
      <div class="row">
        <div class="col-md-offset-3 col-md-6">
          centered column with that has an "original width" of 1 col
        </div>
      </div>
    </div>
  </div>
</div>

See this fiddle, please note that you have to increase the size of the output window in order too see the result, otherwise the columns will wrap.

What is difference between cacerts and keystore?

Check your JAVA_HOME path. As systems looks for a java.policy file which is located in JAVA_HOME/jre/lib/security. Your JAVA_HOME should always be ../JAVA/JDK.

How to enable Ad Hoc Distributed Queries

You may check the following command

sp_configure 'show advanced options', 1;
RECONFIGURE;
GO  --Added        
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO

SELECT a.*
FROM OPENROWSET('SQLNCLI', 'Server=Seattle1;Trusted_Connection=yes;',
     'SELECT GroupName, Name, DepartmentID
      FROM AdventureWorks2012.HumanResources.Department
      ORDER BY GroupName, Name') AS a;
GO

Or this documentation link

"Large data" workflows using pandas

I'd like to point out the Vaex package.

Vaex is a python library for lazy Out-of-Core DataFrames (similar to Pandas), to visualize and explore big tabular datasets. It can calculate statistics such as mean, sum, count, standard deviation etc, on an N-dimensional grid up to a billion (109) objects/rows per second. Visualization is done using histograms, density plots and 3d volume rendering, allowing interactive exploration of big data. Vaex uses memory mapping, zero memory copy policy and lazy computations for best performance (no memory wasted).

Have a look at the documentation: https://vaex.readthedocs.io/en/latest/ The API is very close to the API of pandas.

OPENSSL file_get_contents(): Failed to enable crypto

Ok I have found a solution. The problem is that the site uses SSLv3. And I know that there are some problems in the openssl module. Some time ago I had the same problem with the SSL versions.

<?php
function getSSLPage($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSLVERSION,3); 
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

var_dump(getSSLPage("https://eresearch.fidelity.com/eresearch/evaluate/analystsOpinionsReport.jhtml?symbols=api"));
?>

When you set the SSL Version with curl to v3 then it works.

Edit:

Another problem under Windows is that you don't have access to the certificates. So put the root certificates directly to curl.

http://curl.haxx.se/docs/caextract.html

here you can download the root certificates.

curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/certs/cacert.pem");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

Then you can use the CURLOPT_SSL_VERIFYPEER option with true otherwise you get an error.

Convert UNIX epoch to Date object

With library(lubridate), numeric representations of date and time saved as the number of seconds since 1970-01-01 00:00:00 UTC, can be coerced into dates with as_datetime():

lubridate::as_datetime(1352068320)

[1] "2012-11-04 22:32:00 UTC"

Permission denied at hdfs

You are experiencing two separate problems here:


hduser@ubuntu:/usr/local/hadoop$ hadoop fs -put /usr/local/input-data/ /input put: /usr/local/input-data (Permission denied)

Here, the user hduser does not have access to the local directory /usr/local/input-data. That is, your local permissions are too restrictive. You should change it.


hduser@ubuntu:/usr/local/hadoop$ sudo bin/hadoop fs -put /usr/local/input-data/ /inwe put: org.apache.hadoop.security.AccessControlException: Permission denied: user=root, access=WRITE, inode="":hduser:supergroup:rwxr-xr-x

Here, the user root (since you are using sudo) does not have access to the HDFS directory /input. As you can see: hduser:supergroup:rwxr-xr-x says only hduser has write access. Hadoop doesn't really respect root as a special user.


To fix this, I suggest you change the permissions on the local data:

sudo chmod -R og+rx /usr/local/input-data/

Then, try the put command again as hduser.

How to programmatically set the SSLContext of a JAX-WS client?

For those trying and still not getting it to work, this did it for me with Wildfly 8, using the dynamic Dispatcher:

bindingProvider.getRequestContext().put("com.sun.xml.ws.transport.https.client.SSLSocketFactory", yourSslSocketFactory);

Note that the internal part from the Property key is gone here.

Error message "Forbidden You don't have permission to access / on this server"

This is pretty ridiculous, but I got the 403 Forbidden when the file I was trying to download wasn't there on the filesystem. The apache error is not very accurate in this case, and the whole thing worked after I simply put the file where it was supposed to be.

Two-way SSL clarification

In two way ssl the client asks for servers digital certificate and server ask for the same from the client. It is more secured as it is both ways, although its bit slow. Generally we dont follow it as the server doesnt care about the identity of the client, but a client needs to make sure about the integrity of server it is connecting to.

Evenly distributing n points on a sphere

The Fibonacci sphere algorithm is great for this. It is fast and gives results that at a glance will easily fool the human eye. You can see an example done with processing which will show the result over time as points are added. Here's another great interactive example made by @gman. And here's a simple implementation in python.

import math


def fibonacci_sphere(samples=1):

    points = []
    phi = math.pi * (3. - math.sqrt(5.))  # golden angle in radians

    for i in range(samples):
        y = 1 - (i / float(samples - 1)) * 2  # y goes from 1 to -1
        radius = math.sqrt(1 - y * y)  # radius at y

        theta = phi * i  # golden angle increment

        x = math.cos(theta) * radius
        z = math.sin(theta) * radius

        points.append((x, y, z))

    return points

1000 samples gives you this:

enter image description here

How to close off a Git Branch?

Yes, just delete the branch by running git push origin :branchname. To fix a new issue later, branch off from master again.

Namenode not getting started

After deleting a resource managers' data folder, the problem is gone.
Even if you have formatting cannot solve this problem.

Downloading all maven dependencies to a directory NOT in repository?

I found the next command

mvn dependency:copy-dependencies -Dclassifier=sources

here maven.apache.org

Seeing if data is normally distributed in R

when you perform a test, you ever have the probabilty to reject the null hypothesis when it is true.

See the nextt R code:

p=function(n){
  x=rnorm(n,0,1)
  s=shapiro.test(x)
  s$p.value
}

rep1=replicate(1000,p(5))
rep2=replicate(1000,p(100))
plot(density(rep1))
lines(density(rep2),col="blue")
abline(v=0.05,lty=3)

The graph shows that whether you have a sample size small or big a 5% of the times you have a chance to reject the null hypothesis when it s true (a Type-I error)

Cannot assign requested address - possible causes?

sysctl -w net.ipv4.tcp_timestamps=1
sysctl -w net.ipv4.tcp_tw_recycle=1

Unable to begin a distributed transaction

Apart from the security settings, I had to open some ports on both servers for the transaction to run. I had to open port 59640 but according to the following suggestion, port 135 has to be open. http://support.microsoft.com/kb/839279

No module named pkg_resources

For me, it turned out to be a permissions problem on site-packages. Since it's only my dev environment, I raised the permissions and everything is working again:

sudo chmod -R a+rwx /path/to/my/venv/lib/python2.7/site-packages/

Re-sign IPA (iPhone)

If you have an app with extensions and/or a watch app and you have multiple provisioning profiles for each extension/watch app then you should use this script to re-sign the ipa file.

Re-signing script at Github

Here is an example of how to use this script:

./resign.sh YourApp.ipa "iPhone Distribution: YourCompanyOrDeveloperName" -p <path_to_provisioning_profile_for_app>.mobileprovision -p <path_to_provisioning_profile_for_watchkitextension>.mobileprovision -p <path_to_provisioning_profile_for_watchkitapp>.mobileprovision -p <path_to_provisioning_profile_for_todayextension>.mobileprovision  resignedYourApp.ipa

You can include other extension provisioning profiles too by adding it with yet another -p option.

For me - all the provisioning profiles were signed by the same certificate/signing identity.

javac option to compile all java files under a given directory recursively

I've been using this in an Xcode JNI project to recursively build my test classes:

find ${PROJECT_DIR} -name "*.java" -print | xargs javac -g -classpath ${BUILT_PRODUCTS_DIR} -d ${BUILT_PRODUCTS_DIR}

Git Server Like GitHub?

To add to what Chris has said, you can use gitosis (http://eagain.net/gitweb/?p=gitosis.git) to control who can actually access the repo.

Depending on your usage, you can also use hooks (in the .git/hooks folder) so that your code will automatically be pulled into the server's filesystem when you push from your local machine. Here's a popular script for doing that: http://utsl.gen.nz/git/post-update. This won't be necessary in all cases though.

Change the mouse pointer using JavaScript

With regards to @CrazyJugglerDrummer second method it would be:

elementsToChange.style.cursor = "http://wiki-devel.sugarlabs.org/images/e/e2/Arrow.cur";

Copy files without overwrite

For %F In ("C:\From\*.*") Do If Not Exist "C:\To\%~nxF" Copy "%F" "C:\To\%~nxF"

How to set level logging to DEBUG in Tomcat?

JULI logging levels for Tomcat

SEVERE - Serious failures

WARNING - Potential problems

INFO - Informational messages

CONFIG - Static configuration messages

FINE - Trace messages

FINER - Detailed trace messages

FINEST - Highly detailed trace messages

You can find here more https://documentation.progress.com/output/ua/OpenEdge_latest/index.html#page/pasoe-admin/tomcat-logging.html

How to atomically delete keys matching a pattern using Redis

I just had the same problem. I stored session data for a user in the format:

session:sessionid:key-x - value of x
session:sessionid:key-y - value of y
session:sessionid:key-z - value of z

So, each entry was a seperate key-value pair. When the session is destroyed, I wanted to remove all session data by deleting keys with the pattern session:sessionid:* - but redis does not have such a function.

What I did: store the session data within a hash. I just create a hash with the hash id of session:sessionid and then I push key-x, key-y, key-z in that hash (order did not matter to me) and if I dont need that hash anymore I just do a DEL session:sessionid and all data associated with that hash id is gone. DEL is atomic and accessing data/writing data to the hash is O(1).

Design Patterns web based applications

IMHO, there is not much difference in case of web application if you look at it from the angle of responsibility assignment. However, keep the clarity in the layer. Keep anything purely for the presentation purpose in the presentation layer, like the control and code specific to the web controls. Just keep your entities in the business layer and all features (like add, edit, delete) etc in the business layer. However rendering them onto the browser to be handled in the presentation layer. For .Net, the ASP.NET MVC pattern is very good in terms of keeping the layers separated. Look into the MVC pattern.

is it possible to evenly distribute buttons across the width of an android linearlayout

In linearLayout Instead of giving weight to Button itself , set the weight to <Space> View this won't stretch the Button.

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="4"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.955">

        <Space
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="1" />

        <Button
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:background="@drawable/ic_baseline_arrow_back_24" />

        <Space
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="1" />

        <Button
            android:id="@+id/captureButton"
            android:layout_width="72dp"
            android:layout_height="72dp"
            android:background="@drawable/ic_round_camera_24" />

        <Space
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="1" />

        <Button
            android:id="@+id/cameraChangerBtn"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:background="@drawable/ic_round_switch_camera_24" />

        <Space
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="1" />
    </LinearLayout>

    </androidx.constraintlayout.widget.ConstraintLayout>

as I am using 4 <Space> I set the android:weightSum="4" In linear layout also this is the result ::

layout preview

How to specify maven's distributionManagement organisation wide?

There's no need for a parent POM.

You can omit the distributionManagement part entirely in your poms and set it either on your build server or in settings.xml.

To do it on the build server, just pass to the mvn command:

-DaltSnapshotDeploymentRepository=snapshots::default::https://YOUR_NEXUS_URL/snapshots
-DaltReleaseDeploymentRepository=releases::default::https://YOUR_NEXUS_URL/releases

See https://maven.apache.org/plugins/maven-deploy-plugin/deploy-mojo.html for details which options can be set.

It's also possible to set this in your settings.xml.

Just create a profile there which is enabled and contains the property.

Example settings.xml:

<settings>
[...]
  <profiles>
    <profile>
      <id>nexus</id>
      <properties>
        <altSnapshotDeploymentRepository>snapshots::default::https://YOUR_NEXUS_URL/snapshots</altSnapshotDeploymentRepository>
        <altReleaseDeploymentRepository>releases::default::https://YOUR_NEXUS_URL/releases</altReleaseDeploymentRepository>
      </properties>
    </profile>
  </profiles>

  <activeProfiles>
    <activeProfile>nexus</activeProfile>
  </activeProfiles>

</settings>

Make sure that credentials for "snapshots" and "releases" are in the <servers> section of your settings.xml

The properties altSnapshotDeploymentRepository and altReleaseDeploymentRepository are introduced with maven-deploy-plugin version 2.8. Older versions will fail with the error message

Deployment failed: repository element was not specified in the POM inside distributionManagement element or in -DaltDeploymentRepository=id::layout::url parameter

To fix this, you can enforce a newer version of the plug-in:

        <build>
          <pluginManagement>
            <plugins>
              <plugin>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>2.8</version>
              </plugin>
            </plugins>
          </pluginManagement>
        </build>

Compiled vs. Interpreted Languages

A compiled language is one where the program, once compiled, is expressed in the instructions of the target machine. For example, an addition "+" operation in your source code could be translated directly to the "ADD" instruction in machine code.

An interpreted language is one where the instructions are not directly executed by the target machine, but instead read and executed by some other program (which normally is written in the language of the native machine). For example, the same "+" operation would be recognised by the interpreter at run time, which would then call its own "add(a,b)" function with the appropriate arguments, which would then execute the machine code "ADD" instruction.

You can do anything that you can do in an interpreted language in a compiled language and vice-versa - they are both Turing complete. Both however have advantages and disadvantages for implementation and use.

I'm going to completely generalise (purists forgive me!) but, roughly, here are the advantages of compiled languages:

  • Faster performance by directly using the native code of the target machine
  • Opportunity to apply quite powerful optimisations during the compile stage

And here are the advantages of interpreted languages:

  • Easier to implement (writing good compilers is very hard!!)
  • No need to run a compilation stage: can execute code directly "on the fly"
  • Can be more convenient for dynamic languages

Note that modern techniques such as bytecode compilation add some extra complexity - what happens here is that the compiler targets a "virtual machine" which is not the same as the underlying hardware. These virtual machine instructions can then be compiled again at a later stage to get native code (e.g. as done by the Java JVM JIT compiler).

Xcode "Build and Archive" from command line

You mean the validate/share/submit options? I think those are specific to Xcode, and not suited for a command-line build tool.

With some cleverness, I bet you could make a script to do it for you. It looks like they're just stored in ~/Library/MobileDevice/Archived Applications/ with a UUDI and a plist. I can't imagine it would be that hard to reverse engineer the validator either.

The process I'm interested automating is sending builds to beta testers. (Since App Store submission happens infrequently, I don't mind doing it manually, especially since I often need to add new description text.) By doing a pseudo Build+Archive using Xcode's CLI, I can trigger automatic builds from every code commit, create IPA files with embedded provisioning profiles, and email it to testers.

Is there a way to specify a default property value in Spring XML?

The default value can be followed with a : after the property key, e.g.

<property name="port" value="${my.server.port:8080}" />

Or in java code:

@Value("${my.server.port:8080}")
private String myServerPort;

See:

BTW, the Elvis Operator is only available within Spring Expression Language (SpEL),
e.g.: https://stackoverflow.com/a/37706167/537554

How do I compare two Integers?

"equals" is it. To be on the safe side, you should test for null-ness:

x == y || (x != null && x.equals(y))

the x==y tests for null==null, which IMHO should be true.

The code will be inlined by the JIT if it is called often enough, so performance considerations should not matter.

Of course, avoiding "Integer" in favor of plain "int" is the best way, if you can.

[Added]

Also, the null-check is needed to guarantee that the equality test is symmetric -- x.equals(y) should by the same as y.equals(x), but isn't if one of them is null.

What causes and what are the differences between NoClassDefFoundError and ClassNotFoundException?

Given the Class loader sussystem actions:

http://www.artima.com/insidejvm/ed2/images/fig7-1.gif

This is an article that helped me a lot to understand the difference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-5.html

If an error occurs during class loading, then an instance of a subclass of LinkageError must be thrown at a point in the program that (directly or indirectly) uses the class or interface being loaded.

If the Java Virtual Machine ever attempts to load a class C during verification (§5.4.1) or resolution (§5.4.3) (but not initialization (§5.5)), and the class loader that is used to initiate loading of C throws an instance of ClassNotFoundException, then the Java Virtual Machine must throw an instance of NoClassDefFoundError whose cause is the instance of ClassNotFoundException.

So a ClassNotFoundException is a root cause of NoClassDefFoundError.
And a NoClassDefFoundError is a special case of type loading error, that occurs at Linking step.

How do you generate a random double uniformly distributed between 0 and 1 from C++?

In C++11 and C++14 we have much better options with the random header. The presentation rand() Considered Harmful by Stephan T. Lavavej explains why we should eschew the use of rand() in C++ in favor of the random header and N3924: Discouraging rand() in C++14 further reinforces this point.

The example below is a modified version of the sample code on the cppreference site and uses the std::mersenne_twister_engine engine and the std::uniform_real_distribution which generates numbers in the [0,1) range (see it live):

#include <iostream>
#include <iomanip>
#include <map>
#include <random>

int main()
{
    std::random_device rd;


    std::mt19937 e2(rd());

    std::uniform_real_distribution<> dist(0, 1);

    std::map<int, int> hist;
    for (int n = 0; n < 10000; ++n) {
        ++hist[std::round(dist(e2))];
    }

    for (auto p : hist) {
        std::cout << std::fixed << std::setprecision(1) << std::setw(2)
                  << p.first << ' ' << std::string(p.second/200, '*') << '\n';
    }
}

output will be similar to the following:

0 ************************
1 *************************

Since the post mentioned that speed was important then we should consider the cppreference section that describes the different random number engines (emphasis mine):

The choice of which engine to use involves a number of tradeoffs*: the **linear congruential engine is moderately fast and has a very small storage requirement for state. The lagged Fibonacci generators are very fast even on processors without advanced arithmetic instruction sets, at the expense of greater state storage and sometimes less desirable spectral characteristics. The Mersenne twister is slower and has greater state storage requirements but with the right parameters has the longest non-repeating sequence with the most desirable spectral characteristics (for a given definition of desirable).

So if there is a desire for a faster generator perhaps ranlux24_base or ranlux48_base are better choices over mt19937.

rand()

If you forced to use rand() then the C FAQ for a guide on How can I generate floating-point random numbers?, gives us an example similar to this for generating an on the interval [0,1):

#include <stdlib.h>

double randZeroToOne()
{
    return rand() / (RAND_MAX + 1.);
}

and to generate a random number in the range from [M,N):

double randMToN(double M, double N)
{
    return M + (rand() / ( RAND_MAX / (N-M) ) ) ;  
}

How to avoid installing "Unlimited Strength" JCE policy files when deploying an application?

You could use method

javax.crypto.Cipher.getMaxAllowedKeyLength(String transformation)

to test the available key length, use that and inform the user about what is going on. Something stating that your application is falling back to 128 bit keys due to the policy files not being installed, for example. Security conscious users will install the policy files, others will continue using weaker keys.

What is the difference between Cloud Computing and Grid Computing?

I would say that the basic difference is this:

Grids are used as computing/storage platform.

We start talking about cloud computing when it offers services. I would almost say that cloud computing is higher-level grid. Now I know these are not definitions, but maybe it will make it more clear.

As far as application domains go, grids require users (developers mostly) to actually create services from low-level functions that grid offers. Cloud will offer complete blocks of functionality that you can use in your application.

Example (you want to create physical simulation of ball dropping from certain height): Grid: Study how to compute physics on a computer, create appropriate code, optimize it for certain hardware, think about paralellization, set inputs send application to grid and wait for answer

Cloud: Set diameter of a ball, material from pre-set types, height from which the ball is dropping, etc and ask for results

I would say that if you created OS for grid, you would actually create cloud OS.

What is the difference between Serialization and Marshaling?

Here's more specific examples of both:

Serialization Example:

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

typedef struct {
    char value[11];
} SerializedInt32;

SerializedInt32 SerializeInt32(int32_t x) 
{
    SerializedInt32 result;

    itoa(x, result.value, 10);

    return result;
}

int32_t DeserializeInt32(SerializedInt32 x) 
{
    int32_t result;

    result = atoi(x.value);

    return result;
}

int main(int argc, char **argv)
{    
    int x;   
    SerializedInt32 data;
    int32_t result;

    x = -268435455;

    data = SerializeInt32(x);
    result = DeserializeInt32(data);

    printf("x = %s.\n", data.value);

    return result;
}

In serialization, data is flattened in a way that can be stored and unflattened later.

Marshalling Demo:

(MarshalDemoLib.cpp)

#include <iostream>
#include <string>

extern "C"
__declspec(dllexport)
void *StdCoutStdString(void *s)
{
    std::string *str = (std::string *)s;
    std::cout << *str;
}

extern "C"
__declspec(dllexport)
void *MarshalCStringToStdString(char *s)
{
    std::string *str(new std::string(s));

    std::cout << "string was successfully constructed.\n";

    return str;
}

extern "C"
__declspec(dllexport)
void DestroyStdString(void *s)
{
    std::string *str((std::string *)s);
    delete str;

    std::cout << "string was successfully destroyed.\n";
}

(MarshalDemo.c)

#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

int main(int argc, char **argv)
{
    void *myStdString;

    LoadLibrary("MarshalDemoLib");

    myStdString = ((void *(*)(char *))GetProcAddress (
        GetModuleHandleA("MarshalDemoLib"),
        "MarshalCStringToStdString"
    ))("Hello, World!\n");

    ((void (*)(void *))GetProcAddress (
        GetModuleHandleA("MarshalDemoLib"),
        "StdCoutStdString"
    ))(myStdString);

    ((void (*)(void *))GetProcAddress (
        GetModuleHandleA("MarshalDemoLib"),
        "DestroyStdString"
    ))(myStdString);    
}

In marshaling, data does not necessarily need to be flattened, but it needs to be transformed to another alternative representation. all casting is marshaling, but not all marshaling is casting.

Marshaling doesn't require dynamic allocation to be involved, it can also just be transformation between structs. For example, you might have a pair, but the function expects the pair's first and second elements to be other way around; you casting/memcpy one pair to another won't do the job because fst and snd will get flipped.

#include <stdio.h>

typedef struct {
    int fst;
    int snd;
} pair1;

typedef struct {
    int snd;
    int fst;
} pair2;

void pair2_dump(pair2 p)
{
    printf("%d %d\n", p.fst, p.snd);
}

pair2 marshal_pair1_to_pair2(pair1 p)
{
    pair2 result;
    result.fst = p.fst;
    result.snd = p.snd;
    return result;
}

pair1 given = {3, 7};

int main(int argc, char **argv)
{    
    pair2_dump(marshal_pair1_to_pair2(given));

    return 0;
}

The concept of marshaling becomes especially important when you start dealing with tagged unions of many types. For example, you might find it difficult to get a JavaScript engine to print a "c string" for you, but you can ask it to print a wrapped c string for you. Or if you want to print a string from JavaScript runtime in a Lua or Python runtime. They are all strings, but often won't get along without marshaling.

An annoyance I had recently was that JScript arrays marshal to C# as "__ComObject", and has no documented way to play with this object. I can find the address of where it is, but I really don't know anything else about it, so the only way to really figure it out is to poke at it in any way possible and hopefully find useful information about it. So it becomes easier to create a new object with a friendlier interface like Scripting.Dictionary, copy the data from the JScript array object into it, and pass that object to C# instead of JScript's default array.

test.js:

var x = new ActiveXObject("Dmitry.YetAnotherTestObject.YetAnotherTestObject");

x.send([1, 2, 3, 4]);

YetAnotherTestObject.cs

using System;
using System.Runtime.InteropServices;

namespace Dmitry.YetAnotherTestObject
{
    [Guid("C612BD9B-74E0-4176-AAB8-C53EB24C2B29"), ComVisible(true)]
    public class YetAnotherTestObject
    {
        public void send(object x)
        {
            System.Console.WriteLine(x.GetType().Name);
        }
    }
}

above prints "__ComObject", which is somewhat of a black box from the point of view of C#.

Another interesting concept is that you might have the understanding how to write code, and a computer that knows how to execute instructions, so as a programmer, you are effectively marshaling the concept of what you want the computer to do from your brain to the program image. If we had good enough marshallers, we could just think of what we want to do/change, and the program would change that way without typing on the keyboard. So, if you could have a way to store all the physical changes in your brain for the few seconds where you really want to write a semicolon, you could marshal that data into a signal to print a semicolon, but that's an extreme.

How to create a GUID/UUID using iOS

In Swift 3.0

var uuid = UUID().uuidString

A beginner's guide to SQL database design

I started out with this article

http://en.tekstenuitleg.net/articles/software/database-design-tutorial/intro.html

It's pretty concise compared to reading an entire book and it explains the basics of database design (normalization, types of relationships) very well.

Git for beginners: The definitive practical guide

How do you branch?

The default branch in a git repository is called master.

To create a new branch use

git branch <branch-name>

To see a list of all branches in the current repository type

git branch

If you want to switch to another branch you can use

git checkout <branch-name>

To create a new branch and switch to it in one step

git checkout -b <branch-name>

To delete a branch, use

git branch -d <branch-name>

To create a branch with the changes from the current branch, do

git stash
git stash branch <branch-name>

Generate random numbers uniformly over an entire range

If you are concerned about randomness and not about speed, you should use a secure random number generation method. There are several ways to do this... The easiest one being to use OpenSSL's Random Number Generator.

You can also write your own using an encryption algorithm (like AES). By picking a seed and an IV and then continuously re-encrypting the output of the encryption function. Using OpenSSL is easier, but less manly.

How do I protect Python code?

Though there's no perfect solution, the following can be done:

  1. Move some critical piece of startup code into a native library.
  2. Enforce the license check in the native library.

If the call to the native code were to be removed, the program wouldn't start anyway. If it's not removed then the license will be enforced.

Though this is not a cross-platform or a pure-Python solution, it will work.

Should I use SVN or Git?

The main point is, that Git is a distributed VCS and Subversion a centralized one. Distributed VCSs are a little bit more difficult to understand, but have many advantages. If you don't need this advantages, Subversion may the better choice.

Another question is tool-support. Which VCS is better supported by the tools you plan to use?

EDIT: Three years ago I answered this way:

And Git works on Windows at the moment only via Cygwin or MSYS. Subversion supported Windows from the beginning. As the git-solutions for windows may work for you, there may be problems, as the most developers of Git work with Linux and didn't have portability in the mind from the beginning. At the moment I would prefer Subversion for development under Windows. In a few years this may be irrelevant.

Now the world has changed a little bit. Git has a good implementation on windows now. Although I tested not thouroughly on windows (as I no longer use this system), I'm quite confident, that all the major VCS (SVN, Git, Mercurial, Bazaar) have proper Windows-implementation now. This advantage for SVN is gone. The other points (Centralized vs. Distributed and the check for tool support) stay valid.

What is the Difference Between Mercurial and Git?

I'm currently in the process of migrating from SVN to a DVCS (while blogging about my findings, my first real blogging effort...), and I've done a bit of research (=googling). As far as I can see you can do most of the things with both packages. It seems like git has a few more or better implemented advanced features, I do feel that the integration with windows is a bit better for mercurial, with TortoiseHg. I know there's Git Cheetah as well (I tried both), but the mercurial solution just feels more robust.

Seeing how they're both open-source (right?) I don't think either will be lacking important features. If something is important, people will ask for it, people will code it.

I think that for common practices, Git and Mercurial are more than sufficient. They both have big projects that use them (Git -> linux kernel, Mercurial -> Mozilla foundation projects, both among others of course), so I don't think either are really lacking something.

That being said, I am interested in what other people say about this, as it would make a great source for my blogging efforts ;-)

How do I enable MSDTC on SQL Server?

MSDTC must be enabled on both systems, both server and client.
Also, make sure that there isn't a firewall between the systems that blocks RPC.
DTCTest is a nice litt app that helps you to troubleshoot any other problems.

Why is Git better than Subversion?

Well, it's distributed. Benchmarks indicate that it's considerably faster (given its distributed nature, operations like diffs and logs are all local so of course it's blazingly faster in this case), and working folders are smaller (which still blows my mind).

When you're working on subversion, or any other client/server revision control system, you essentially create working copies on your machine by checking-out revisions. This represents a snapshot in time of what the repository looks like. You update your working copy via updates, and you update the repository via commits.

With a distributed version control, you don't have a snapshot, but rather the entire codebase. Wanna do a diff with a 3 month old version? No problem, the 3 month old version is still on your computer. This doesn't only mean things are way faster, but if you're disconnected from your central server, you can still do many of the operations you're used to. In other words, you don't just have a snapshot of a given revision, but the entire codebase.

You'd think that Git would take up a bunch of space on your harddrive, but from a couple benchmarks I've seen, it actually takes less. Don't ask me how. I mean, it was built by Linus, he knows a thing or two about filesystems I guess.

Uninstall Eclipse under OSX?

Actually Eclipse does create some other files not within it's directory which survive deleting it's directory.

In Snow Leopard, look in your user's account under:

  • ~/Library/Caches/org.eclipse.eclipse
  • ~/Library/Preferences/org.eclipse.eclipse.plist

Not sure if you need to turn on viewing of hidden files to see those.

onClick function of an input type="button" not working

You have to change the ID of the button to be different from the function name JSFiddle

_x000D_
_x000D_
var counter = 0;_x000D_
_x000D_
_x000D_
function moreFields() {_x000D_
  counter++;_x000D_
  var newFields = document.getElementById('readroot').cloneNode(true);_x000D_
  newFields.id = '';_x000D_
  newFields.style.display = 'block';_x000D_
  var newField = newFields.childNodes;_x000D_
  for (var i = 0; i < newField.length; i++) {_x000D_
    var theName = newField[i].name_x000D_
    if (theName) newField[i].name = theName + counter;_x000D_
  }_x000D_
  var insertHere = document.getElementById('writeroot');_x000D_
  insertHere.parentNode.insertBefore(newFields, insertHere);_x000D_
}_x000D_
_x000D_
window.onload = moreFields();
_x000D_
<div id="readroot" style="display: none">_x000D_
  <input type="button" value="Remove review" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />_x000D_
  <br />_x000D_
  <br />_x000D_
  <input name="cd" value="title" />_x000D_
  <select name="rankingsel">_x000D_
    <option>Rating</option>_x000D_
    <option value="excellent">Excellent</option>_x000D_
    <option value="good">Good</option>_x000D_
    <option value="ok">OK</option>_x000D_
    <option value="poor">Poor</option>_x000D_
    <option value="bad">Bad</option>_x000D_
  </select>_x000D_
  <br />_x000D_
  <br />_x000D_
  <textarea rows="5" cols="20" name="review">Short review</textarea>_x000D_
  <br />Radio buttons included to test them in Explorer:_x000D_
  <br />_x000D_
  <input type="radio" name="something" value="test1" />Test 1_x000D_
  <br />_x000D_
  <input type="radio" name="something" value="test2" />Test 2</div>_x000D_
<form method="post" action="index1.php"> <span id="writeroot"></span>_x000D_
_x000D_
  <input type="button" onclick="moreFields();" id="moreFieldsButton" value="Give me more fields!" />_x000D_
  <input type="submit" value="Send form" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

New self vs. new static

will I get the same results?

Not really. I don't know of a workaround for PHP 5.2, though.

What is the difference between new self and new static?

self refers to the same class in which the new keyword is actually written.

static, in PHP 5.3's late static bindings, refers to whatever class in the hierarchy you called the method on.

In the following example, B inherits both methods from A. The self invocation is bound to A because it's defined in A's implementation of the first method, whereas static is bound to the called class (also see get_called_class()).

class A {
    public static function get_self() {
        return new self();
    }

    public static function get_static() {
        return new static();
    }
}

class B extends A {}

echo get_class(B::get_self());  // A
echo get_class(B::get_static()); // B
echo get_class(A::get_self()); // A
echo get_class(A::get_static()); // A

Is it possible to capture the stdout from the sh DSL command in the pipeline

Try this:

def get_git_sha(git_dir='') {
    dir(git_dir) {
        return sh(returnStdout: true, script: 'git rev-parse HEAD').trim()
    }
}

node(BUILD_NODE) {
    ...
    repo_SHA = get_git_sha('src/FooBar.git')
    echo repo_SHA
    ...
}

Tested on:

  • Jenkins ver. 2.19.1
  • Pipeline 2.4

Tips for debugging .htaccess rewrite rules

Some mistakes I observed happens when writing .htaccess

Using of ^(.*)$ repetitively in multiple rules, using ^(.*)$ causes other rules to be impotent in most cases, because it matches all of the url in single hit.

So, if we are using rule for this url sapmle/url it will also consume this url sapmle/url/string.


[L] flag should be used to ensure our rule has done processing.


Should know about:

Difference in %n and $n

%n is matched during %{RewriteCond} part and $n is matches on %{RewriteRule} part.

Working of RewriteBase

The RewriteBase directive specifies the URL prefix to be used for per-directory (htaccess) RewriteRule directives that substitute a relative path.

This directive is required when you use a relative path in a substitution in per-directory (htaccess) context unless any of the following conditions are true:

The original request, and the substitution, are underneath the DocumentRoot (as opposed to reachable by other means, such as Alias). The filesystem path to the directory containing the RewriteRule, suffixed by the relative substitution is also valid as a URL path on the server (this is rare). In Apache HTTP Server 2.4.16 and later, this directive may be omitted when the request is mapped via Alias or mod_userdir.

Use -notlike to filter out multiple strings in PowerShell

$listOfUsernames = @("user1", "user2", "etc", "and so on")
Get-EventLog -LogName Security | 
    where { $_.Username -notmatch (
        '(' + [string]::Join(')|(', $listOfUsernames) + ')') }

It's a little crazy I'll grant you, and it fails to escape the usernames (in the unprobable case a username uses a Regex escape character like '\' or '(' ), but it works.

As "slipsec" mentioned above, use -notcontains if possible.

ListAGG in SQLSERVER

In SQL Server 2017 STRING_AGG is added:

SELECT t.name,STRING_AGG (c.name, ',') AS csv
FROM sys.tables t
JOIN sys.columns c on t.object_id = c.object_id
GROUP BY t.name
ORDER BY 1

Also, STRING_SPLIT is usefull for the opposite case and available in SQL Server 2016

Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...

This is what I went with. Its a modified version of Abbbas khan's post:

<?php

  function calculate_time_span($post_time)
  {  
  $seconds = time() - strtotime($post);
  $year = floor($seconds /31556926);
  $months = floor($seconds /2629743);
  $week=floor($seconds /604800);
  $day = floor($seconds /86400); 
  $hours = floor($seconds / 3600);
  $mins = floor(($seconds - ($hours*3600)) / 60); 
  $secs = floor($seconds % 60);
  if($seconds < 60) $time = $secs." seconds ago";
  else if($seconds < 3600 ) $time =($mins==1)?$mins."now":$mins." mins ago";
  else if($seconds < 86400) $time = ($hours==1)?$hours." hour ago":$hours." hours ago";
  else if($seconds < 604800) $time = ($day==1)?$day." day ago":$day." days ago";
  else if($seconds < 2629743) $time = ($week==1)?$week." week ago":$week." weeks ago";
  else if($seconds < 31556926) $time =($months==1)? $months." month ago":$months." months ago";
  else $time = ($year==1)? $year." year ago":$year." years ago";
  return $time; 
  }  



 // uses
 // $post_time="2017-12-05 02:05:12";
 // echo calculate_time_span($post_time); 

NullPointerException in Java with no StackTrace

This will output the Exception, use only to debug you should handle you exceptions better.

import java.io.PrintWriter;
import java.io.StringWriter;
    public static String getStackTrace(Throwable t)
    {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        t.printStackTrace(pw);
        pw.flush();
        sw.flush();
        return sw.toString();
    }

Google maps responsive resize

Move your map variable into a scope where the event listener can use it. You are creating the map inside your initialize() function and nothing else can use it when created that way.

var map; //<-- This is now available to both event listeners and the initialize() function
function initialize() {
  var mapOptions = {
   center: new google.maps.LatLng(40.5472,12.282715),
   zoom: 6,
   mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("map-canvas"),
            mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
 var center = map.getCenter();
 google.maps.event.trigger(map, "resize");
 map.setCenter(center); 
});

Show a div as a modal pop up

A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:

  • 1. Create a div with semi transparent background & show it on top of your content page on click.
  • 2. Show your pop up div or alert div on top of the semi transparent dimming/hiding div.
  • So we need three divs:

  • content(main content of the site).
  • hider(To dim the content).
  • popup_box(the modal div to display).

    First let us define the CSS:

        #hider
        {
            position:absolute;
            top: 0%;
            left: 0%;
            width:1600px;
            height:2000px;
            margin-top: -800px; /*set to a negative number 1/2 of your height*/
            margin-left: -500px; /*set to a negative number 1/2 of your width*/
            /*
            z- index must be lower than pop up box
           */
            z-index: 99;
           background-color:Black;
           //for transparency
           opacity:0.6;
        }
    
        #popup_box  
        {
    
        position:absolute;
            top: 50%;
            left: 50%;
            width:10em;
            height:10em;
            margin-top: -5em; /*set to a negative number 1/2 of your height*/
            margin-left: -5em; /*set to a negative number 1/2 of your width*/
            border: 1px solid #ccc;
            border:  2px solid black;
            z-index:100; 
    
        }
    

    It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
    Here comes the java Script:

            $(document).ready(function () {
            //hide hider and popup_box
            $("#hider").hide();
            $("#popup_box").hide();
    
            //on click show the hider div and the message
            $("#showpopup").click(function () {
                $("#hider").fadeIn("slow");
                $('#popup_box').fadeIn("slow");
            });
            //on click hide the message and the
            $("#buttonClose").click(function () {
    
                $("#hider").fadeOut("slow");
                $('#popup_box').fadeOut("slow");
            });
    
            });
    

    And finally the HTML:

    <div id="hider"></div>
    <div id="popup_box">
        Message<br />
        <a id="buttonClose">Close</a>
    </div>    
    <div id="content">
        Page's main content.<br />
        <a id="showpopup">ClickMe</a>
    </div>
    

    I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.

  • How do I generate a random integer between min and max in Java?

    Construct a Random object at application startup:

    Random random = new Random();
    

    Then use Random.nextInt(int):

    int randomNumber = random.nextInt(max + 1 - min) + min;
    

    Note that the both lower and upper limits are inclusive.

    Waiting till the async task finish its work

    In your AsyncTask add one ProgressDialog like:

    private final ProgressDialog dialog = new ProgressDialog(YourActivity.this);
    

    you can setMessage in onPreExecute() method like:

    this.dialog.setMessage("Processing..."); 
    this.dialog.show();
    

    and in your onPostExecute(Void result) method dismiss your ProgressDialog.

    Make anchor link go some pixels above where it's linked to

    I just found an easy solution for myself. Had an margin-top of 15px

    HTML

    <h2 id="Anchor">Anchor</h2>
    

    CSS

    h2{margin-top:-60px; padding-top:75px;}
    

    git push >> fatal: no configured push destination

    The command (or the URL in it) to add the github repository as a remote isn't quite correct. If I understand your repository name correctly, it should be;

    git remote add demo_app '[email protected]:levelone/demo_app.git'
    

    How to insert double and float values to sqlite?

    actually I think your code is just fine.. you can save those values as strings (TEXT) just like you did.. (if you want to)

    and you probably get the error for the System.currentTimeMillis() that might be too big for INTEGER

    How to bind inverse boolean properties in WPF?

    I wanted my XAML to remain as elegant as possible so I created a class to wrap the bool which resides in one of my shared libraries, the implicit operators allow the class to be used as a bool in code-behind seamlessly

    public class InvertableBool
    {
        private bool value = false;
    
        public bool Value { get { return value; } }
        public bool Invert { get { return !value; } }
    
        public InvertableBool(bool b)
        {
            value = b;
        }
    
        public static implicit operator InvertableBool(bool b)
        {
            return new InvertableBool(b);
        }
    
        public static implicit operator bool(InvertableBool b)
        {
            return b.value;
        }
    
    }
    

    The only changes needed to your project are to make the property you want to invert return this instead of bool

        public InvertableBool IsActive 
        { 
            get 
            { 
                return true; 
            } 
        }
    

    And in the XAML postfix the binding with either Value or Invert

    IsEnabled="{Binding IsActive.Value}"
    
    IsEnabled="{Binding IsActive.Invert}"
    

    How to get current location in Android

    First you need to define a LocationListener to handle location changes.

    private final LocationListener mLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(final Location location) {
            //your code here
        }
    };
    

    Then get the LocationManager and ask for location updates

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME,
                LOCATION_REFRESH_DISTANCE, mLocationListener);
    }
    

    And finally make sure that you have added the permission on the Manifest,

    For using only network based location use this one

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    

    For GPS based location, this one

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    

    What is a Question Mark "?" and Colon ":" Operator Used for?

    it is a ternary operator and in simple english it states "if row%2 is equal to 1 then return < else return /r"

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

    I also use this

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

    but I don't get any error.

    Did you include the jstl.jar in your library? If not maybe this causing the problem. And also the 'tld' folder do you have it? And how about your web.xml did you map it?

    Have a look on the info about jstl for other information.

    c++ compile error: ISO C++ forbids comparison between pointer and integer

    A string literal is delimited by quotation marks and is of type char* not char.

    Example: "hello"

    So when you compare a char to a char* you will get that same compiling error.

    char c = 'c';
    char *p = "hello";
    
    if(c==p)//compiling error
    {
    } 
    

    To fix use a char literal which is delimited by single quotes.

    Example: 'c'

    Omitting one Setter/Getter in Lombok

    According to @Data description you can use:

    All generated getters and setters will be public. To override the access level, annotate the field or class with an explicit @Setter and/or @Getter annotation. You can also use this annotation (by combining it with AccessLevel.NONE) to suppress generating a getter and/or setter altogether.

    Find all storage devices attached to a Linux machine

    You can always do fdisk -l which seems to work pretty well, even on strange setups such as EC2 xvda devices.

    Here is a dump for a m1.large instance:

    root@ip-10-126-247-82:~# fdisk -l
    
    Disk /dev/xvda1: 10.7 GB, 10737418240 bytes
    255 heads, 63 sectors/track, 1305 cylinders, total 20971520 sectors
    Units = sectors of 1 * 512 = 512 bytes
    Sector size (logical/physical): 512 bytes / 512 bytes
    I/O size (minimum/optimal): 512 bytes / 512 bytes
    Disk identifier: 0x00000000
    
    Disk /dev/xvda1 doesn't contain a valid partition table
    
    Disk /dev/xvda2: 365.0 GB, 365041287168 bytes
    255 heads, 63 sectors/track, 44380 cylinders, total 712971264 sectors
    Units = sectors of 1 * 512 = 512 bytes
    Sector size (logical/physical): 512 bytes / 512 bytes
    I/O size (minimum/optimal): 512 bytes / 512 bytes
    Disk identifier: 0x00000000
    
    Disk /dev/xvda2 doesn't contain a valid partition table
    
    Disk /dev/xvda3: 939 MB, 939524096 bytes
    255 heads, 63 sectors/track, 114 cylinders, total 1835008 sectors
    Units = sectors of 1 * 512 = 512 bytes
    Sector size (logical/physical): 512 bytes / 512 bytes
    I/O size (minimum/optimal): 512 bytes / 512 bytes
    Disk identifier: 0x00000000
    
    Disk /dev/xvda3 doesn't contain a valid partition table
    

    While mount says:

    root@ip-10-126-247-82:~# mount
    /dev/xvda1 on / type ext4 (rw)
    proc on /proc type proc (rw,noexec,nosuid,nodev)
    sysfs on /sys type sysfs (rw,noexec,nosuid,nodev)
    fusectl on /sys/fs/fuse/connections type fusectl (rw)
    none on /sys/kernel/debug type debugfs (rw)
    none on /sys/kernel/security type securityfs (rw)
    udev on /dev type devtmpfs (rw,mode=0755)
    devpts on /dev/pts type devpts (rw,noexec,nosuid,gid=5,mode=0620)
    tmpfs on /run type tmpfs (rw,noexec,nosuid,size=10%,mode=0755)
    none on /run/lock type tmpfs (rw,noexec,nosuid,nodev,size=5242880)
    none on /run/shm type tmpfs (rw,nosuid,nodev)
    /dev/xvda2 on /mnt type ext3 (rw)
    

    And /proc/partitions says:

    root@ip-10-126-247-82:~# cat /proc/partitions
    major minor  #blocks  name
    
     202        1   10485760 xvda1
     202        2  356485632 xvda2
     202        3     917504 xvda3
    

    Side Note

    How fdisk -l works is something I would love to know myself.

    Android: How to rotate a bitmap on a center point

    I came back to this problem now that we are finalizing the game and I just thought to post what worked for me.

    This is the method for rotating the Matrix:

    this.matrix.reset();
    this.matrix.setTranslate(this.floatXpos, this.floatYpos);
    this.matrix.postRotate((float)this.direction, this.getCenterX(), this.getCenterY()); 
    

    (this.getCenterX() is basically the bitmaps X position + the bitmaps width / 2)

    And the method for Drawing the bitmap (called via a RenderManager Class):

    canvas.drawBitmap(this.bitmap, this.matrix, null);

    So it is prettey straight forward but I find it abit strange that I couldn't get it to work by setRotate followed by postTranslate. Maybe some knows why this doesn't work? Now all the bitmaps rotate properly but it is not without some minor decrease in bitmap quality :/

    Anyways, thanks for your help!

    Pretty-Print JSON Data to a File using Python

    You could redirect a file to python and open using the tool and to read it use more.

    The sample code will be,

    cat filename.json | python -m json.tool | more
    

    Eclipse error: "The import XXX cannot be resolved"

    If you're developing plugins in eclipse and you're using a target platform (which was my case) you need to make sure you check the target's platform configuration from Window->Preferences->Plug-in Development->Target Platform and make sure your target platform is checked and configured. Hope this helps.

    Is it possible to run one logrotate check manually?

    logrotate -d [your_config_file] invokes debug mode, giving you a verbose description of what would happen, but leaving the log files untouched.

    Why is Maven downloading the maven-metadata.xml every time?

    It is possibly to use the flag -o,--offline "Work offline" to prevent that.

    Like this:

    maven compile -o

    Setting PHP tmp dir - PHP upload not working

    The problem described here was solved by me quite a long time ago but I don't really remember what was the main reason that uploads weren't working. There were multiple things that needed fixing so the upload could work. I have created checklist that might help others having similar problems and I will edit it to make it as helpful as possible. As I said before on chat, I was working on embedded system, so some points may be skipped on non-embedded systems.

    • Check upload_tmp_dir in php.ini. This is directory where PHP stores temporary files while uploading.

    • Check open_basedir in php.ini. If defined it limits PHP read/write rights to specified path and its subdirectories. Ensure that upload_tmp_dir is inside this path.

    • Check post_max_size in php.ini. If you want to upload 20 Mbyte files, try something a little bigger, like post_max_size = 21M. This defines largest size of POST message which you are probably using during upload.

    • Check upload_max_filesize in php.ini. This specifies biggest file that can be uploaded.

    • Check memory_limit in php.ini. That's the maximum amount of memory a script may consume. It's quite obvious that it can't be lower than upload size (to be honest I'm not quite sure about it-PHP is probably buffering while copying temporary files).

    • Ensure that you're checking the right php.ini file that is one used by PHP on your webserver. The best solution is to execute script with directive described here http://php.net/manual/en/function.php-ini-loaded-file.php (php_ini_loaded_file function)

    • Check what user php runs as (See here how to do it: How to check what user php is running as? ). I have worked on different distros and servers. Sometimes it is apache, but sometimes it can be root. Anyway, check that this user has rights for reading and writing in the temporary directory and directory that you're uploading into. Check all directories in the path in case you're uploading into subdirectory (for example /dir1/dir2/-check both dir1 and dir2.

    • On embedded platforms you sometimes need to restrict writing to root filesystem because it is stored on flash card and this helps to extend life of this card. If you are using scripts to enable/disable file writes, ensure that you enable writing before uploading.

    • I had serious problems with PHP >5.4 upload monitoring based on sessions (as described here http://phpmaster.com/tracking-upload-progress-with-php-and-javascript/ ) on some platforms. Try something simple at first (like here: http://www.dzone.com/snippets/very-simple-php-file-upload ). If it works, you can try more sophisticated mechanisms.

    • If you make any changes in php.ini remember to restart server so the configuration will be reloaded.

    android layout with visibility GONE

    Done by having it like that:

    view = inflater.inflate(R.layout.entry_detail, container, false);
    TextView tp1= (TextView) view.findViewById(R.id.tp1);
    LinearLayout layone= (LinearLayout) view.findViewById(R.id.layone);
    tp1.setVisibility(View.VISIBLE);
    layone.setVisibility(View.VISIBLE);
    

    Php $_POST method to get textarea value

    //My Form
    <form id="someform">
            <div class="input-group">
                <textarea placeholder="Post your Comment Here ..." name="post" class="form-control custom-control" rows="3" style="resize:none"></textarea> 
                <span class="input-group-addon">                                            
                    <button type="submit" name="post_comment" class="btn btn-primary">
                        Post
                    </button>
                </span>
            </div>
        </form>
    
    //your text area get value to URL
    <?php
            if(isset($_POST['post_comment']))
            {
                echo htmlspecialchars($_POST['post']);
            }
    
        ?>
    
    //print the value using get
    echo $_GET['post'];
    
    //url must be like this
    http://localhost/blog/home.php?post=asdasdsad&post_comment=
    
    //post value has asdasdsad so it will print to your page
    

    Determine if $.ajax error is a timeout

    If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.

    Per the jQuery documentation:

    Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

    You can handle your error accordingly then.

    I created this fiddle that demonstrates this.

    $.ajax({
        url: "/ajax_json_echo/",
        type: "GET",
        dataType: "json",
        timeout: 1000,
        success: function(response) { alert(response); },
        error: function(xmlhttprequest, textstatus, message) {
            if(textstatus==="timeout") {
                alert("got timeout");
            } else {
                alert(textstatus);
            }
        }
    });?
    

    With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.

    Hope this helps!

    Detect changes in the DOM

    or you can simply Create your own event, that run everywhere

     $("body").on("domChanged", function () {
                    //dom is changed 
                });
    
    
     $(".button").click(function () {
    
              //do some change
              $("button").append("<span>i am the new change</span>");
    
              //fire event
              $("body").trigger("domChanged");
    
            });
    

    Full example http://jsfiddle.net/hbmaam/Mq7NX/

    bootstrap 3 tabs not working properly

    This will work

    $(".nav-tabs a").click(function(){
         $(this).tab('show');
     });
    

    Remove android default action bar

    You can set it as a no title bar theme in the activity's xml in the AndroidManifest

        <activity 
            android:name=".AnActivity"
            android:label="@string/a_string"
            android:theme="@android:style/Theme.NoTitleBar">
        </activity>
    

    Using LINQ to group by multiple properties and sum

    Linus is spot on in the approach, but a few properties are off. It looks like 'AgencyContractId' is your Primary Key, which is unrelated to the output you want to give the user. I think this is what you want (assuming you change your ViewModel to match the data you say you want in your view).

    var agencyContracts = _agencyContractsRepository.AgencyContracts
        .GroupBy(ac => new
                       {
                           ac.AgencyID,
                           ac.VendorID,
                           ac.RegionID
                       })
        .Select(ac => new AgencyContractViewModel
                       {
                           AgencyId = ac.Key.AgencyID,
                           VendorId = ac.Key.VendorID,
                           RegionId = ac.Key.RegionID,
                           Total = ac.Sum(acs => acs.Amount) + ac.Sum(acs => acs.Fee)
                       });
    

    vagrant login as root by default

    I had some troubles with provisioning when trying to login as root, even with PermitRootLogin yes. I made it so only the vagrant ssh command is affected:

    # Login as root when doing vagrant ssh
    if ARGV[0]=='ssh'
      config.ssh.username = 'root'
    end
    

    Specifying ssh key in ansible playbook file

    If you run your playbook with ansible-playbook -vvv you'll see the actual command being run, so you can check whether the key is actually being included in the ssh command (and you might discover that the problem was the wrong username rather than the missing key).

    I agree with Brian's comment above (and zigam's edit) that the vars section is too late. I also tested including the key in the on-the-fly definition of the host like this

    # fails
    - name: Add all instance public IPs to host group
      add_host: hostname={{ item.public_ip }} groups=ec2hosts ansible_ssh_private_key_file=~/.aws/dev_staging.pem
      loop: "{{ ec2.instances }}"
    

    but that fails too.

    So this is not an answer. Just some debugging help and things not to try.

    Why can't I push to this bare repository?

    This related question's answer provided the solution for me... it was just a dumb mistake:

    Remember to commit first!

    https://stackoverflow.com/a/7572252

    If you have not yet committed to your local repo, there is nothing to push, but the Git error message you get back doesn't help you too much.

    Removing rounded corners from a <select> element in Chrome/Webkit

    Just my solution with dropdown image (inline svg)

    select.form-control {
        -webkit-appearance: none;
        -webkit-border-radius: 0px;
        background-image: url("data:image/svg+xml;utf8,<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' width='24' height='24' viewBox='0 0 24 24'><path fill='%23444' d='M7.406 7.828l4.594 4.594 4.594-4.594 1.406 1.406-6 6-6-6z'></path></svg>");
        background-position: 100% 50%;
        background-repeat: no-repeat;
    }
    

    I'm using bootstrap that's why I used select.form-control
    You can use select{ or select.your-custom-class{ instead.

    Interpreting segfault messages

    Error 4 means "The cause was a user-mode read resulting in no page being found.". There's a tool that decodes it here.

    Here's the definition from the kernel. Keep in mind that 4 means that bit 2 is set and no other bits are set. If you convert it to binary that becomes clear.

    /*
     * Page fault error code bits
     *      bit 0 == 0 means no page found, 1 means protection fault
     *      bit 1 == 0 means read, 1 means write
     *      bit 2 == 0 means kernel, 1 means user-mode
     *      bit 3 == 1 means use of reserved bit detected
     *      bit 4 == 1 means fault was an instruction fetch
     */
    #define PF_PROT         (1<<0)
    #define PF_WRITE        (1<<1)
    #define PF_USER         (1<<2)
    #define PF_RSVD         (1<<3)
    #define PF_INSTR        (1<<4)
    

    Now then, "ip 00007f9bebcca90d" means the instruction pointer was at 0x00007f9bebcca90d when the segfault happened.

    "libQtWebKit.so.4.5.2[7f9beb83a000+f6f000]" tells you:

    • The object the crash was in: "libQtWebKit.so.4.5.2"
    • The base address of that object "7f9beb83a000"
    • How big that object is: "f6f000"

    If you take the base address and subtract it from the ip, you get the offset into that object:

    0x00007f9bebcca90d - 0x7f9beb83a000 = 0x49090D
    

    Then you can run addr2line on it:

    addr2line -e /usr/lib64/qt45/lib/libQtWebKit.so.4.5.2 -fCi 0x49090D
    ??
    ??:0
    

    In my case it wasn't successful, either the copy I installed isn't identical to yours, or it's stripped.

    iOS 7 status bar back to iOS 6 default style in iPhone app?

    This might be too late to share, but I have something to contribute which might help someone, I was trying to sub-class the UINavigationBar and wanted to make it look like ios 6 with black status bar and status bar text in white.

    Here is what I found working for that

            self.navigationController?.navigationBar.clipsToBounds = true
            self.navigationController?.navigationBar.translucent = false
            self.navigationController?.navigationBar.barStyle = .Black
            self.navigationController?.navigationBar.barTintColor = UIColor.whiteColor()
    

    It made my status bar background black, status bar text white and navigation bar's color white.

    iOS 9.3, XCode 7.3.1

    Has anyone ever got a remote JMX JConsole to work?

    Adding -Djava.rmi.server.hostname='<host ip>' resolved this problem for me.

    Multiple lines of input in <input type="text" />

    Input doesn't support multiple lines. You need to use a textarea to achieve that feature.

    <textarea name="Text1"></textarea>
    

    Remeber that the <textarea> have the value inside the tag, not in attribute:

    <textarea>INITIAL VALUE GOES HERE</textarea>
    

    It cannot be self closed as: <textarea/>


    For more information, take a look to this.

    How to pass List from Controller to View in MVC 3

    1. Create a model which contains your list and other things you need for the view.

      For example:

      public class MyModel
      {
          public List<string> _MyList { get; set; }
      }
      
    2. From the action method put your desired list to the Model, _MyList property, like:

      public ActionResult ArticleList(MyModel model)
      {
          model._MyList = new List<string>{"item1","item2","item3"};
          return PartialView(@"~/Views/Home/MyView.cshtml", model);
      }
      
    3. In your view access the model as follows

      @model MyModel
      foreach (var item in Model)
      {
         <div>@item</div>
      }
      

    I think it will help for start.

    Convert Float to Int in Swift

    You can get an integer representation of your float by passing the float into the Integer initializer method.

    Example:

    Int(myFloat)
    

    Keep in mind, that any numbers after the decimal point will be loss. Meaning, 3.9 is an Int of 3 and 8.99999 is an integer of 8.

    Can a normal Class implement multiple interfaces?

    An interface can extend other interfaces. Also an interface cannot implement any other interface. When it comes to a class, it can extend one other class and implement any number of interfaces.

    class A extends B implements C,D{...}
    

    What is WebKit and how is it related to CSS?

    Webkit is the html/css rendering engine used in Apple's Safari browser, and in Google's Chrome. css values prefixes with -webkit- are webkit-specific, they're usually CSS3 or other non-standardised features.

    to answer update 2 w3c is the body that tries to standardize these things, they write the rules, then programmers write their rendering engine to interpret those rules. So basically w3c says DIVs should work "This way" the engine-writer then uses that rule to write their code, any bugs or mis-interpretations of the rules cause the compatibility issues.

    Javascript getElementById based on a partial string

    You'll probably have to either give it a constant class and call getElementsByClassName, or maybe just use getElementsByTagName, and loop through your results, checking the name.

    I'd suggest looking at your underlying problem and figure out a way where you can know the ID in advance.

    Maybe if you posted a little more about why you're getting this, we could find a better alternative.

    java.util.NoSuchElementException: No line found

    You're calling nextLine() and it's throwing an exception when there's no line, exactly as the javadoc describes. It will never return null

    http://download.oracle.com/javase/1,5.0/docs/api/java/util/Scanner.html

    How do I uninstall nodejs installed from pkg (Mac OS X)?

    A little convenience script expanding on previous answers.

    #!/bin/bash
    
    # Uninstall node.js
    # 
    # Options:
    #
    # -d Actually delete files, otherwise the script just _prints_ a command to delete.
    # -p Installation prefix. Default /usr/local
    # -f BOM file. Default /var/db/receipts/org.nodejs.pkg.bom
    
    CMD="echo sudo rm -fr"
    BOM_FILE="/var/db/receipts/org.nodejs.pkg.bom"
    PREFIX="/usr/local"
    
    while getopts "dp:f:" arg; do
        case $arg in
            d)
                CMD="sudo rm -fr"
                ;;
            p)
                PREFIX=$arg
                ;;
            f)
                BOM_FILE=$arg
                ;;
        esac
    done
    
    lsbom -f -l -s -pf ${BOM_FILE} \
        | while read i; do
              $CMD ${PREFIX}/${i}
          done
    
    $CMD ${PREFIX}/lib/node \
         ${PREFIX}/lib/node_modules \
         ${BOM_FILE}
    

    Save it to file and run with:

    # bash filename.sh
    

    How to reference a .css file on a razor view?

    You can this structure in Layout.cshtml file

    <link href="~/YourCssFolder/YourCssStyle.css" rel="stylesheet" type="text/css" />
    

    Use string.Contains() with switch()

    string message = "This is test1";
    string[] switchStrings = { "TEST1", "TEST2" };
    switch (switchStrings.FirstOrDefault<string>(s => message.ToUpper().Contains(s)))
    {
        case "TEST1":
            //Do work
            break;
        case "TEST2":
            //Do work
            break;
        default:
            //Do work
            break; 
    }
    

    PHP Email sending BCC

    You have $headers .= '...'; followed by $headers = '...';; the second line is overwriting the first.

    Just put the $headers .= "Bcc: $emailList\r\n"; say after the Content-type line and it should be fine.

    On a side note, the To is generally required; mail servers might mark your message as spam otherwise.

    $headers  = "From: [email protected]\r\n" .
      "X-Mailer: php\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
    $headers .= "Bcc: $emailList\r\n";
    

    How to use paginator from material angular?

    The tricky part here is to handle is the page event. We can follow angular material documentation up to defining page event function.

    Visit https://material.angular.io/components/paginator/examples for the reference.

    I will add my work with hours of hard work in this regard. in the relevant HTML file should look like as follows,

    <pre>
    <mat-paginator
        [pageSizeOptions]="pageSizeOptions"
        [pageSize]="Size"
        (page)="pageEvent = pageNavigations($event)"
        [length]="recordCount">
    </mat-paginator>
    </pre>
    

    Then go to the relevant typescript file and following code,

    declarations,

    @Input('data') customers: Observable<Customer[]>;
    pageEvent: PageEvent;
    Page: number=0;
    Size: number=2;
    recordCount: number;
    pageSizeOptions: number[] = [2,3,4,5];
    

    The key part of page navigation as follows,

    pageNavigations(event? : PageEvent){
        console.log(event);
        this.Page = event.pageIndex;
        this.Size = event.pageSize;
        this.reloadData();
      }
    

    We require the following function to call data from the backend.

    reloadData() {
    
        this.customers = this.customerService.setPageSize(this.Page ,this.Size);
        this.customerService.getSize().subscribe(res => {
          this.recordCount = Number(res);
         
          console.log(this.recordCount);
        });
      }
    

    Before the aforementioned implementation, our services file should contain the following service call

    setPageSize(page: number, size: number): Observable<any> {
        return this.http.get(`${this.baseUrl}?pageSize=${size}&pageNo=${page}`);
      }
    

    Then all set to go and enable pagination in our app. Feel free to ask related questions thank you.

    Regular expression to find URLs within a string

    This is the one I use

    (http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?
    

    Works for me, should work for you too.

    How to return a table from a Stored Procedure?

    Where is your problem??

    For the stored procedure, just create:

    CREATE PROCEDURE dbo.ReadEmployees @EmpID INT
    AS
       SELECT *  -- I would *strongly* recommend specifying the columns EXPLICITLY
       FROM dbo.Emp
       WHERE ID = @EmpID
    

    That's all there is.

    From your ASP.NET application, just create a SqlConnection and a SqlCommand (don't forget to set the CommandType = CommandType.StoredProcedure)

    DataTable tblEmployees = new DataTable();
    
    using(SqlConnection _con = new SqlConnection("your-connection-string-here"))
    using(SqlCommand _cmd = new SqlCommand("ReadEmployees", _con))
    {
        _cmd.CommandType = CommandType.StoredProcedure;
    
        _cmd.Parameters.Add(new SqlParameter("@EmpID", SqlDbType.Int));
        _cmd.Parameters["@EmpID"].Value = 42;
    
        SqlDataAdapter _dap = new SqlDataAdapter(_cmd);
    
        _dap.Fill(tblEmployees);
    }
    
    YourGridView.DataSource = tblEmployees;
    YourGridView.DataBind();
    

    and then fill e.g. a DataTable with that data and bind it to e.g. a GridView.

    Static image src in Vue.js template

    You need use just simple code <img alt="img" src="../assets/index.png" />

    Do not forgot atribut alt in balise img

    How to find the logs on android studio?

    There is no way to get the logs for installing problems.

    Search for value in DataGridView in a column

    It's better also to separate your logic in another method, or maybe in another class.

    This method will help you retreive the DataGridViewCell object in which the text was found.

        /// <summary>
        /// Check if a given text exists in the given DataGridView at a given column index
        /// </summary>
        /// <param name="searchText"></param>
        /// <param name="dataGridView"></param>
        /// <param name="columnIndex"></param>
        /// <returns>The cell in which the searchText was found</returns>
        private DataGridViewCell GetCellWhereTextExistsInGridView(string searchText, DataGridView dataGridView, int columnIndex)
        {
            DataGridViewCell cellWhereTextIsMet = null;
    
            // For every row in the grid (obviously)
            foreach (DataGridViewRow row in dataGridView.Rows)
            {
                // I did not test this case, but cell.Value is an object, and objects can be null
                // So check if the cell is null before using .ToString()
                if (row.Cells[columnIndex].Value != null && searchText == row.Cells[columnIndex].Value.ToString())
                {
                    // the searchText is equals to the text in this cell.
                    cellWhereTextIsMet = row.Cells[columnIndex];
                    break;
                }
            }
    
            return cellWhereTextIsMet;
        }
    
        private void button_click(object sender, EventArgs e)
        {
            DataGridViewCell cell = GetCellWhereTextExistsInGridView(textBox1.Text, myGridView, 2);
            if (cell != null)
            {
                // Value exists in the grid
                // you can do extra stuff on the cell
                cell.Style = new DataGridViewCellStyle { ForeColor = Color.Red };
            }
            else
            {
                // Value does not exist in the grid
            }
        }
    

    PostgreSQL query to list all table names?

    SELECT table_name
    FROM information_schema.tables
    WHERE table_type='BASE TABLE'
    AND table_schema='public';
    

    For MySQL you would need table_schema='dbName' and for MSSQL remove that condition.

    Notice that "only those tables and views are shown that the current user has access to". Also, if you have access to many databases and want to limit the result to a certain database, you can achieve that by adding condition AND table_catalog='yourDatabase' (in PostgreSQL).

    If you'd also like to get rid of the header showing row names and footer showing row count, you could either start the psql with command line option -t (short for --tuples-only) or you can toggle the setting in psql's command line by \t (short for \pset tuples_only). This could be useful for example when piping output to another command with \g [ |command ].

    How to insert tab character when expandtab option is on in Vim

    You can disable expandtab option from within Vim as below:

    :set expandtab!
    

    or

    :set noet
    

    PS: And set it back when you are done with inserting tab, with "set expandtab" or "set et"

    PS: If you have tab set equivalent to 4 spaces in .vimrc (softtabstop), you may also like to set it to 8 spaces in order to be able to insert a tab by pressing tab key once instead of twice (set softtabstop=8).

    HTTP 401 - what's an appropriate WWW-Authenticate header value?

    When the user session times out, I send back an HTTP 204 status code. Note that the HTTP 204 status contains no content. On the client-side I do this:

    xhr.send(null);
    if (xhr.status == 204) 
        Reload();
    else 
        dropdown.innerHTML = xhr.responseText;
    

    Here is the Reload() function:

    function Reload() {
        var oForm = document.createElement("form");
        document.body.appendChild(oForm);
        oForm.submit();
        }
    

    Why do I get a "permission denied" error while installing a gem?

    After setting the gems directory to the user directory that runs the gem install, using export GEM_HOME=/home/<user>/gems, the issue has been solved.

    How to split strings over multiple lines in Bash?

    Line continuations also can be achieved through clever use of syntax.

    In the case of echo:

    # echo '-n' flag prevents trailing <CR> 
    echo -n "This is my one-line statement" ;
    echo -n " that I would like to make."
    This is my one-line statement that I would like to make.
    

    In the case of vars:

    outp="This is my one-line statement" ; 
    outp+=" that I would like to make." ; 
    echo -n "${outp}"
    This is my one-line statement that I would like to make.
    

    Another approach in the case of vars:

    outp="This is my one-line statement" ; 
    outp="${outp} that I would like to make." ; 
    echo -n "${outp}"
    This is my one-line statement that I would like to make.
    

    Voila!

    Horizontal swipe slider with jQuery and touch devices support?

    Ive found another: http://swipejs.com/

    seems to work nicely however I encounter an issue with it when paired with bootstrap on the OS X version of Chrome. If total cross-browser compatibility isn't an issue, then you're golden.

    Is there a "null coalescing" operator in JavaScript?

    function coalesce() {
        var len = arguments.length;
        for (var i=0; i<len; i++) {
            if (arguments[i] !== null && arguments[i] !== undefined) {
                return arguments[i];
            }
        }
        return null;
    }
    
    var xyz = {};
    xyz.val = coalesce(null, undefined, xyz.val, 5);
    
    // xyz.val now contains 5
    

    this solution works like the SQL coalesce function, it accepts any number of arguments, and returns null if none of them have a value. It behaves like the C# ?? operator in the sense that "", false, and 0 are considered NOT NULL and therefore count as actual values. If you come from a .net background, this will be the most natural feeling solution.

    Efficient way to remove keys with empty strings from a dict

    If you have a nested dictionary, and you want this to work even for empty sub-elements, you can use a recursive variant of BrenBarn's suggestion:

    def scrub_dict(d):
        if type(d) is dict:
            return dict((k, scrub_dict(v)) for k, v in d.iteritems() if v and scrub_dict(v))
        else:
            return d
    

    How to use a App.config file in WPF applications?

    You have to reference the System.Configuration assembly which is in GAC.

    Use of ConfigurationManager is not WPF-specific: it is the privileged way to access configuration information for any type of application.

    Please see Microsoft Docs - ConfigurationManager Class for further info.

    tsc throws `TS2307: Cannot find module` for a local file

    Don't use: import UserController from "api/xxxx" Should be: import UserController from "./api/xxxx"

    How do I Merge two Arrays in VBA?

    My preferred way is a bit long, but has some advantages over the other answers:

    • It can combine an indefinite number of arrays at once
    • It can combine arrays with non-arrays (objects, strings, integers, etc.)
    • It accounts for the possibility that one or more of the arrays may contain objects
    • It allows the user to choose the base of the new array (0, 1, etc.)

    Here it is:

    Function combineArrays(ByVal toCombine As Variant, Optional ByVal newBase As Long = 1)
    'Combines an array of one or more 1d arrays, objects, or values into a single 1d array
    'newBase parameter indicates start position of new array (0, 1, etc.)
    'Example usage:
        'combineArrays(Array(Array(1,2,3),Array(4,5,6),Array(7,8))) -> Array(1,2,3,4,5,6,7,8)
        'combineArrays(Array("Cat",Array(2,3,4))) -> Array("Cat",2,3,4)
        'combineArrays(Array("Cat",ActiveSheet)) -> Array("Cat",ActiveSheet)
        'combineArrays(Array(ThisWorkbook)) -> Array(ThisWorkbook)
        'combineArrays("Cat") -> Array("Cat")
    
        Dim tempObj As Object
        Dim tempVal As Variant
    
        If Not IsArray(toCombine) Then
            If IsObject(toCombine) Then
                Set tempObj = toCombine
                ReDim toCombine(newBase To newBase)
                Set toCombine(newBase) = tempObj
            Else
                tempVal = toCombine
                ReDim toCombine(newBase To newBase)
                toCombine(newBase) = tempVal
            End If
            combineArrays = toCombine
            Exit Function
        End If
    
        Dim i As Long
        Dim tempArr As Variant
        Dim newMax As Long
        newMax = 0
    
        For i = LBound(toCombine) To UBound(toCombine)
            If Not IsArray(toCombine(i)) Then
                If IsObject(toCombine(i)) Then
                    Set tempObj = toCombine(i)
                    ReDim tempArr(1 To 1)
                    Set tempArr(1) = tempObj
                    toCombine(i) = tempArr
                Else
                    tempVal = toCombine(i)
                    ReDim tempArr(1 To 1)
                    tempArr(1) = tempVal
                    toCombine(i) = tempArr
                End If
                newMax = newMax + 1
            Else
                newMax = newMax + (UBound(toCombine(i)) + LBound(toCombine(i)) - 1)
            End If
        Next
        newMax = newMax + (newBase - 1)
    
        ReDim newArr(newBase To newMax)
        i = newBase
        Dim j As Long
        Dim k As Long
        For j = LBound(toCombine) To UBound(toCombine)
            For k = LBound(toCombine(j)) To UBound(toCombine(j))
                If IsObject(toCombine(j)(k)) Then
                    Set newArr(i) = toCombine(j)(k)
                Else
                    newArr(i) = toCombine(j)(k)
                End If
                i = i + 1
            Next
        Next
    
        combineArrays = newArr
    
    End Function
    

    Flexbox and Internet Explorer 11 (display:flex in <html>?)

    You just need flex:1; It will fix issue for the IE11. I second Odisseas. Additionally assign 100% height to html,body elements.

    CSS changes:

    html, body{
        height:100%;
    }
    body {
        border: red 1px solid;
        min-height: 100vh;
        display: -ms-flexbox;
        display: -webkit-flex;
        display: flex;
        -ms-flex-direction: column;
        -webkit-flex-direction: column;
        flex-direction: column;
    }
    header {
        background: #23bcfc;
    }
    main {
        background: #87ccfc;
        -ms-flex: 1;
        -webkit-flex: 1;
        flex: 1;
    }
    footer {
        background: #dd55dd;
    }
    

    working url: http://jsfiddle.net/3tpuryso/13/

    Remove duplicates from a dataframe in PySpark

    if you have a data frame and want to remove all duplicates -- with reference to duplicates in a specific column (called 'colName'):

    count before dedupe:

    df.count()
    

    do the de-dupe (convert the column you are de-duping to string type):

    from pyspark.sql.functions import col
    df = df.withColumn('colName',col('colName').cast('string'))
    
    df.drop_duplicates(subset=['colName']).count()
    

    can use a sorted groupby to check to see that duplicates have been removed:

    df.groupBy('colName').count().toPandas().set_index("count").sort_index(ascending=False)
    

    How to force a UIViewController to Portrait orientation in iOS 6

    Put this in the .m file of each ViewController you don't want to rotate:

    - (NSUInteger)supportedInterfaceOrientations
    {
        //return UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft;
        return UIInterfaceOrientationMaskPortrait;
    }
    

    See here for more information.

    VSCode single to double quote automatic replace

    I added file called .prettierrc in my project folder. File content:

    {
        "singleQuote": true,
        "vetur.format.defaultFormatterOptions": {
            "prettier": {
                "singleQuote": true
            }
        }
    }
    

    Detecting Back Button/Hash Change in URL

    Try simple & lightweight PathJS lib.

    Simple example:

    Path.map("#/page").to(function(){
        alert('page!');
    });
    

    How to specify table's height such that a vertical scroll bar appears?

    Try using the overflow CSS property. There are also separate properties to define the behaviour of just horizontal overflow (overflow-x) and vertical overflow (overflow-y).

    Since you only want the vertical scroll, try this:

    table {
      height: 500px;
      overflow-y: scroll;
    }
    

    EDIT:

    Apparently <table> elements don't respect the overflow property. This appears to be because <table> elements are not rendered as display: block by default (they actually have their own display type). You can force the overflow property to work by setting the <table> element to be a block type:

    table {
      display: block;
      height: 500px;
      overflow-y: scroll;
    }
    

    Note that this will cause the element to have 100% width, so if you don't want it to take up the entire horizontal width of the page, you need to specify an explicit width for the element as well.

    Amazon S3 and Cloudfront cache, how to clear cache or synchronize their cache

    S3 is not used for real time development but if you really want to test your freshly deployed website use

    http://yourdomain.com/index.html?v=2
    http://yourdomain.com/init.js?v=2
    

    Adding a version parameter in the end will stop using the cached version of the file and the browser will get a fresh copy of the file from the server bucket

    Change button text from Xcode?

    myapp.h

    {
    UIButton *myButton;
    }
    @property (nonatomic,retain)IBoutlet UIButton *myButton;
    

    myapp.m

    @synthesize myButton;
    
    -(IBAction)buttonTitle{
    [myButton setTitle:@"Play" forState:UIControlStateNormal];
    }
    

    Adding a Method to an Existing Object Instance

    In Python, there is a difference between functions and bound methods.

    >>> def foo():
    ...     print "foo"
    ...
    >>> class A:
    ...     def bar( self ):
    ...         print "bar"
    ...
    >>> a = A()
    >>> foo
    <function foo at 0x00A98D70>
    >>> a.bar
    <bound method A.bar of <__main__.A instance at 0x00A9BC88>>
    >>>
    

    Bound methods have been "bound" (how descriptive) to an instance, and that instance will be passed as the first argument whenever the method is called.

    Callables that are attributes of a class (as opposed to an instance) are still unbound, though, so you can modify the class definition whenever you want:

    >>> def fooFighters( self ):
    ...     print "fooFighters"
    ...
    >>> A.fooFighters = fooFighters
    >>> a2 = A()
    >>> a2.fooFighters
    <bound method A.fooFighters of <__main__.A instance at 0x00A9BEB8>>
    >>> a2.fooFighters()
    fooFighters
    

    Previously defined instances are updated as well (as long as they haven't overridden the attribute themselves):

    >>> a.fooFighters()
    fooFighters
    

    The problem comes when you want to attach a method to a single instance:

    >>> def barFighters( self ):
    ...     print "barFighters"
    ...
    >>> a.barFighters = barFighters
    >>> a.barFighters()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: barFighters() takes exactly 1 argument (0 given)
    

    The function is not automatically bound when it's attached directly to an instance:

    >>> a.barFighters
    <function barFighters at 0x00A98EF0>
    

    To bind it, we can use the MethodType function in the types module:

    >>> import types
    >>> a.barFighters = types.MethodType( barFighters, a )
    >>> a.barFighters
    <bound method ?.barFighters of <__main__.A instance at 0x00A9BC88>>
    >>> a.barFighters()
    barFighters
    

    This time other instances of the class have not been affected:

    >>> a2.barFighters()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: A instance has no attribute 'barFighters'
    

    More information can be found by reading about descriptors and metaclass programming.

    Convert DataTable to CSV stream

    You can just write something quickly yourself:

    public static class Extensions
    {
        public static string ToCSV(this DataTable table)
        {
            var result = new StringBuilder();
            for (int i = 0; i < table.Columns.Count; i++)
            {
                result.Append(table.Columns[i].ColumnName);
                result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
            }
    
            foreach (DataRow row in table.Rows)
            {
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    result.Append(row[i].ToString());
                    result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
                }
            }
    
            return result.ToString();
        }
    }
    

    And to test:

      public static void Main()
      {
            DataTable table = new DataTable();
            table.Columns.Add("Name");
            table.Columns.Add("Age");
            table.Rows.Add("John Doe", "45");
            table.Rows.Add("Jane Doe", "35");
            table.Rows.Add("Jack Doe", "27");
            var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(table.ToCSV());
            MemoryStream stream = new MemoryStream(bytes);
    
            StreamReader reader = new StreamReader(stream);
            Console.WriteLine(reader.ReadToEnd());
      }
    

    EDIT: Re your comments:

    It depends on how you want your csv formatted but generally if the text contains special characters, you want to enclose it in double quotes ie: "my,text". You can add checking in the code that creates the csv to check for special characters and encloses the text in double quotes if it is. As for the .NET 2.0 thing, just create it as a helper method in your class or remove the word this in the method declaration and call it like so : Extensions.ToCsv(table);

    Best practice for Django project working directory structure

    As per the Django Project Skeleton, the proper directory structure that could be followed is :

    [projectname]/                  <- project root
    +-- [projectname]/              <- Django root
    ¦   +-- __init__.py
    ¦   +-- settings/
    ¦   ¦   +-- common.py
    ¦   ¦   +-- development.py
    ¦   ¦   +-- i18n.py
    ¦   ¦   +-- __init__.py
    ¦   ¦   +-- production.py
    ¦   +-- urls.py
    ¦   +-- wsgi.py
    +-- apps/
    ¦   +-- __init__.py
    +-- configs/
    ¦   +-- apache2_vhost.sample
    ¦   +-- README
    +-- doc/
    ¦   +-- Makefile
    ¦   +-- source/
    ¦       +-- *snap*
    +-- manage.py
    +-- README.rst
    +-- run/
    ¦   +-- media/
    ¦   ¦   +-- README
    ¦   +-- README
    ¦   +-- static/
    ¦       +-- README
    +-- static/
    ¦   +-- README
    +-- templates/
        +-- base.html
        +-- core
        ¦   +-- login.html
        +-- README
    

    Refer https://django-project-skeleton.readthedocs.io/en/latest/structure.html for the latest directory structure.

    How to set a cookie to expire in 1 hour in Javascript?

    You can write this in a more compact way:

    var now = new Date();
    now.setTime(now.getTime() + 1 * 3600 * 1000);
    document.cookie = "name=value; expires=" + now.toUTCString() + "; path=/";
    

    And for someone like me, who wasted an hour trying to figure out why the cookie with expiration is not set up (but without expiration can be set up) in Chrome, here is in answer:

    For some strange reason Chrome team decided to ignore cookies from local pages. So if you do this on localhost, you will not be able to see your cookie in Chrome. So either upload it on the server or use another browser.

    document.getElementById('btnid').disabled is not working in firefox and chrome

    stay true to native (Boolean) property support and its powerful syntax like:

    [elem].disabled = condition ? true : false; //done!

    and for our own good collective coding experience, -please insist on others to support it as well.

    Horizontal line using HTML/CSS

    I have try this my new code and it might be helpful to you, it works perfectly in google chromr

    hr {
         color: #f00;
         background: #f00; 
         width: 75%; 
         height: 5px;
    }
    

    What is the difference between screenX/Y, clientX/Y and pageX/Y?

    Here's a picture explaining the difference between pageY and clientY.

    pageY vs clientY

    Same for pageX and clientX, respectively.


    pageX/Y coordinates are relative to the top left corner of the whole rendered page (including parts hidden by scrolling),

    while clientX/Y coordinates are relative to the top left corner of the visible part of the page, "seen" through browser window.

    See Demo

    You'll probably never need screenX/Y

    How to make custom dialog with rounded corners in android

    You can use the shape for the background as-

    <shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@android:color/transparent"/>
    <corners android:radius="10dp" />
    <padding android:left="10dp" android:right="10dp"/>
    </shape>
    

    Have a look on this for the details.

    Run local python script on remote server

    Although this question isn't quite new and an answer was already chosen, I would like to share another nice approach.

    Using the paramiko library - a pure python implementation of SSH2 - your python script can connect to a remote host via SSH, copy itself (!) to that host and then execute that copy on the remote host. Stdin, stdout and stderr of the remote process will be available on your local running script. So this solution is pretty much independent of an IDE.

    On my local machine, I run the script with a cmd-line parameter 'deploy', which triggers the remote execution. Without such a parameter, the actual code intended for the remote host is run.

    import sys
    import os
    
    def main():
        print os.name
    
    if __name__ == '__main__':
        try:
            if sys.argv[1] == 'deploy':
                import paramiko
    
                # Connect to remote host
                client = paramiko.SSHClient()
                client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                client.connect('remote_hostname_or_IP', username='john', password='secret')
    
                # Setup sftp connection and transmit this script
                sftp = client.open_sftp()
                sftp.put(__file__, '/tmp/myscript.py')
                sftp.close()
    
                # Run the transmitted script remotely without args and show its output.
                # SSHClient.exec_command() returns the tuple (stdin,stdout,stderr)
                stdout = client.exec_command('python /tmp/myscript.py')[1]
                for line in stdout:
                    # Process each line in the remote output
                    print line
    
                client.close()
                sys.exit(0)
        except IndexError:
            pass
    
        # No cmd-line args provided, run script normally
        main()
    

    Exception handling is left out to simplify this example. In projects with multiple script files you will probably have to put all those files (and other dependencies) on the remote host.

    Export DataBase with MySQL Workbench with INSERT statements

    You can do it using mysqldump tool in command-line:

    mysqldump your_database_name > script.sql
    

    This creates a file with database create statements together with insert statements.

    More info about options for mysql dump: https://dev.mysql.com/doc/refman/5.7/en/mysqldump-sql-format.html

    What is the `zero` value for time.Time in Go?

    The zero value for time.Time is 0001-01-01 00:00:00 +0000 UTC See http://play.golang.org/p/vTidOlmb9P

    Creating a very simple linked list

    Here is a good implementation.

    1. It is short, but implemented Add(x), Delete(x), Contain(x) and Print().
    2. It avoid special process when add to empty list or delete the first element. While most of other examples did special process when delete the first element.
    3. The list can contain any data type.

      using System;
      
      class Node<Type> : LinkedList<Type>
      {   // Why inherit from LinkedList? A: We need to use polymorphism.
          public Type value;
          public Node(Type value) { this.value = value; }
      }
      class LinkedList<Type>
      {   
          Node<Type> next;  // This member is treated as head in class LinkedList, but treated as next element in class Node.
          /// <summary> if x is in list, return previos pointer of x. (We can see any class variable as a pointer.)
          /// if not found, return the tail of the list. </summary>
          protected LinkedList<Type> Previos(Type x)
          {
              LinkedList<Type> p = this;      // point to head
              for (; p.next != null; p = p.next)
                  if (p.next.value.Equals(x))
                      return p;               // find x, return the previos pointer.
              return p;                       // not found, p is the tail.
          }
          /// <summary> return value: true = success ; false = x not exist </summary>
          public bool Contain(Type x) { return Previos(x).next != null ? true : false; }
          /// <summary> return value: true = success ; false = fail to add. Because x already exist. 
          /// </summary> // why return value? If caller want to know the result, they don't need to call Contain(x) before, the action waste time.
          public bool Add(Type x)
          {
              LinkedList<Type> p = Previos(x);
              if (p.next != null)             // Find x already in list
                  return false;
              p.next = new Node<Type>(x);
              return true;
          }
          /// <summary> return value: true = success ; false = x not exist </summary>
          public bool Delete(Type x)
          {
              LinkedList<Type> p = Previos(x);
              if (p.next == null)
                  return false;
              //Node<Type> node = p.next;
              p.next = p.next.next;
              //node.Dispose();       // GC dispose automatically.
              return true;
          }
          public void Print()
          {
              Console.Write("List: ");
              for (Node<Type> node = next; node != null; node = node.next)
                  Console.Write(node.value.ToString() + " ");
              Console.WriteLine();
          }
      }
      class Test
      {
          static void Main()
          {
              LinkedList<int> LL = new LinkedList<int>();
              if (!LL.Contain(0)) // Empty list
                  Console.WriteLine("0 is not exist.");
              LL.Print();
              LL.Add(0);      // Add to empty list
              LL.Add(1); LL.Add(2); // attach to tail
              LL.Add(2);      // duplicate add, 2 is tail.
              if (LL.Contain(0))// Find existed element which is head
                  Console.WriteLine("0 is exist.");
              LL.Print();
              LL.Delete(0);   // Delete head
              LL.Delete(2);   // Delete tail
              if (!LL.Delete(0)) // Delete non-exist element
                  Console.WriteLine("0 is not exist.");
              LL.Print();
              Console.ReadLine();
          }
      }
      

    By the way, the implementation in http://www.functionx.com/csharp1/examples/linkedlist.htm have some problem:

    1. Delete() will fail when there is only 1 element. (Throw exception at line "Head.Next = Current.Next;" because Current is null.)
    2. Delete(position) will fail when deleting first element, In other words, call Delete(0) will fail.

    Python: Remove division decimal

    You could probably do like below

    # p and q are the numbers to be divided
    if p//q==p/q:
        print(p//q)
    else:
        print(p/q)
    

    How to set a timer in android

    yes java's timer can be used, but as the question asks for better way (for mobile). Which is explained Here.


    For the sake of StackOverflow:

    Since Timer creates a new thread it may be considered heavy,

    if all you need is to get is a call back while the activity is running a Handler can be used in conjunction with a

    Runnable:

    private final int interval = 1000; // 1 Second
    private Handler handler = new Handler();
    private Runnable runnable = new Runnable(){
        public void run() {
            Toast.makeText(MyActivity.this, "C'Mom no hands!", Toast.LENGTH_SHORT).show();
        }
    };
    ...
    handler.postAtTime(runnable, System.currentTimeMillis()+interval);
    handler.postDelayed(runnable, interval);
    

    or a Message

    private final int EVENT1 = 1; 
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {         
            case Event1:
                Toast.makeText(MyActivity.this, "Event 1", Toast.LENGTH_SHORT).show();
                break;
    
            default:
                Toast.makeText(MyActivity.this, "Unhandled", Toast.LENGTH_SHORT).show();
                break;
            }
        }
    };
    
    ...
    
    Message msg = handler.obtainMessage(EVENT1);
    handler.sendMessageAtTime(msg, System.currentTimeMillis()+interval);
    handler.sendMessageDelayed(msg, interval);
    

    on a side note this approach can be used, if you want to run a piece of code in the UI thread from an another thread.

    if you need to get a call back even if your activity is not running then, you can use an AlarmManager

    Google reCAPTCHA: How to get user response and validate in the server side?

    The cool thing about the new Google Recaptcha is that the validation is now completely encapsulated in the widget. That means, that the widget will take care of asking questions, validating responses all the way till it determines that a user is actually a human, only then you get a g-recaptcha-response value.

    But that does not keep your site safe from HTTP client request forgery.

    Anyone with HTTP POST knowledge could put random data inside of the g-recaptcha-response form field, and foll your site to make it think that this field was provided by the google widget. So you have to validate this token.

    In human speech it would be like,

    • Your Server: Hey Google, there's a dude that tells me that he's not a robot. He says that you already verified that he's a human, and he told me to give you this token as a proof of that.
    • Google: Hmm... let me check this token... yes I remember this dude I gave him this token... yeah he's made of flesh and bone let him through.
    • Your Server: Hey Google, there's another dude that tells me that he's a human. He also gave me a token.
    • Google: Hmm... it's the same token you gave me last time... I'm pretty sure this guy is trying to fool you. Tell him to get off your site.

    Validating the response is really easy. Just make a GET Request to

    https://www.google.com/recaptcha/api/siteverify?secret=your_secret&response=response_string&remoteip=user_ip_address

    And replace the response_string with the value that you earlier got by the g-recaptcha-response field.

    You will get a JSON Response with a success field.

    More information here: https://developers.google.com/recaptcha/docs/verify

    Edit: It's actually a POST, as per documentation here.

    $apply already in progress error

    I call $scope.$apply like this to ignored call multiple in one times.

          var callApplyTimeout = null;
          function callApply(callback) {
              if (!callback) callback = function () { };
              if (callApplyTimeout) $timeout.cancel(callApplyTimeout);
    
              callApplyTimeout = $timeout(function () {
                  callback();
                  $scope.$apply();
                  var d = new Date();
                  var m = d.getMilliseconds();
                  console.log('$scope.$apply(); call ' + d.toString() + ' ' + m);
              }, 300);
          }
    

    simply call

    callApply();
    

    Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation

    You may not have any collation issues in your database whatsoever, but if you restored a copy of your database from a backup on a server with a different collation than the origin, and your code is creating temporary tables, those temporary tables would inherit collation from the server and there would be conflicts with your database.

    Reducing MongoDB database file size

    We need solve 2 ways, based on StorageEngine.

    1. MMAP() engine:

    command: db.repairDatabase()

    NOTE: repairDatabase requires free disk space equal to the size of your current data set plus 2 gigabytes. If the volume that holds dbpath lacks sufficient space, you can mount a separate volume and use that for the repair. When mounting a separate volume for repairDatabase you must run repairDatabase from the command line and use the --repairpath switch to specify the folder in which to store temporary repair files. eg: Imagine DB size is 120 GB means, (120*2)+2 = 242 GB Hard Disk space required.

    another way you do collection wise, command: db.runCommand({compact: 'collectionName'})

    2. WiredTiger: Its automatically resolved it-self.

    How to use the 'main' parameter in package.json?

    Just think of it as the "starting point".

    In a sense of object-oriented programming, say C#, it's the init() or constructor of the object class, that's what "entry point" meant.

    For example

    public class IamMain  // when export and require this guy
    {
        public IamMain()  // this is "main"
        {...}
    
        ...   // many others such as function, properties, etc.
    }
    

    JavaScript: How to join / combine two arrays to concatenate into one array?

    var a = ['a','b','c'];
    var b = ['d','e','f'];
    var c = a.concat(b); //c is now an an array with: ['a','b','c','d','e','f']
    console.log( c[3] ); //c[3] will be 'd'
    

    Why am I getting 'Assembly '*.dll' must be strong signed in order to be marked as a prerequisite.'?

    you need to sign the assembly with a key. Go in the project properties under the tab signing: enter image description here

    Determine if 2 lists have the same elements, regardless of order?

    This seems to work, though possibly cumbersome for large lists.

    >>> A = [0, 1]
    >>> B = [1, 0]
    >>> C = [0, 2]
    >>> not sum([not i in A for i in B])
    True
    >>> not sum([not i in A for i in C])
    False
    >>> 
    

    However, if each list must contain all the elements of other then the above code is problematic.

    >>> A = [0, 1, 2]
    >>> not sum([not i in A for i in B])
    True
    

    The problem arises when len(A) != len(B) and, in this example, len(A) > len(B). To avoid this, you can add one more statement.

    >>> not sum([not i in A for i in B]) if len(A) == len(B) else False
    False
    

    One more thing, I benchmarked my solution with timeit.repeat, under the same conditions used by Aaron Hall in his post. As suspected, the results are disappointing. My method is the last one. set(x) == set(y) it is.

    >>> def foocomprehend(): return not sum([not i in data for i in data2])
    >>> min(timeit.repeat('fooset()', 'from __main__ import fooset, foocount, foocomprehend'))
    25.2893661496
    >>> min(timeit.repeat('foosort()', 'from __main__ import fooset, foocount, foocomprehend'))
    94.3974742993
    >>> min(timeit.repeat('foocomprehend()', 'from __main__ import fooset, foocount, foocomprehend'))
    187.224562545
    

    Getting the .Text value from a TextBox

    if(sender is TextBox) {
     var text = (sender as TextBox).Text;
    }
    

    Disabling of EditText in Android

    For disable edit EditText, I think we can use focusable OR enable but

    1. Using android:enabled=... or editText.setEnabled(...)

      It also changes the text color in EditText to gray.
      When clicked it have no effect

    2. Using android:focusable=... or editText.setFocusable(false) - editText.setFocusableInTouchMode(true)

      It doesn't change text color of EditText
      When clicked it highlights the EditText bottom line for about few millisecond

    Output

    enter image description here

    What is the behavior difference between return-path, reply-to and from?

    Let's start with a simple example. Let's say you have an email list, that is going to send out the following RFC2822 content.

    From: <[email protected]>
    To: <[email protected]>
    Subject: Super simple email
    Reply-To: <[email protected]>
    
    This is a very simple body.
    

    Now, let's say you are going to send it from a mailing list, that implements VERP (or some other bounce tracking mechanism that uses a different return-path). Lets say it will have a return-path of [email protected]. The SMTP session might look like:

    {S}220 workstation1 Microsoft ESMTP MAIL Service
    {C}HELO workstation1
    {S}250 workstation1 Hello [127.0.0.1]
    {C}MAIL FROM:<[email protected]>
    {S}250 2.1.0 [email protected] OK
    {C}RCPT TO:<[email protected]>
    {S}250 2.1.5 [email protected] 
    {C}DATA
    {S}354 Start mail input; end with <CRLF>.<CRLF>
    {C}From: <[email protected]>
    To: <[email protected]>
    Subject: Super simple email
    Reply-To: <[email protected]>
    
    This is a very simple body.
    .
    
    {S}250 Queued mail for delivery
    {C}QUIT
    {S}221 Service closing transmission channel
    

    Where {C} and {S} represent Client and Server commands, respectively.

    The recipient's mail would look like:

    Return-Path: [email protected]
    From: <[email protected]>
    To: <[email protected]>
    Subject: Super simple email
    Reply-To: <[email protected]>
    
    This is a very simple body.
    

    Now, let's describe the different "FROM"s.

    1. The return path (sometimes called the reverse path, envelope sender, or envelope from — all of these terms can be used interchangeably) is the value used in the SMTP session in the MAIL FROM command. As you can see, this does not need to be the same value that is found in the message headers. Only the recipient's mail server is supposed to add a Return-Path header to the top of the email. This records the actual Return-Path sender during the SMTP session. If a Return-Path header already exists in the message, then that header is removed and replaced by the recipient's mail server.

    All bounces that occur during the SMTP session should go back to the Return-Path address. Some servers may accept all email, and then queue it locally, until it has a free thread to deliver it to the recipient's mailbox. If the recipient doesn't exist, it should bounce it back to the recorded Return-Path value.

    Note, not all mail servers obey this rule; Some mail servers will bounce it back to the FROM address.

    1. The FROM address is the value found in the FROM header. This is supposed to be who the message is FROM. This is what you see as the "FROM" in most mail clients. If an email does not have a Reply-To header, then all human (mail client) replies should go back to the FROM address.

    2. The Reply-To header is added by the sender (or the sender's software). It is where all human replies should be addressed too. Basically, when the user clicks "reply", the Reply-To value should be the value used as the recipient of the newly composed email. The Reply-To value should not be used by any server. It is meant for client-side (MUA) use only.

    However, as you can tell, not all mail servers obey the RFC standards or recommendations.

    Hopefully this should help clear things up. However, if I missed anything, let me know, and I'll try to answer.

    Node.js: for each … in not working

    https://github.com/cscott/jsshaper implements a translator from JavaScript 1.8 to ECMAScript 5.1, which would allow you to use 'for each' in code running on webkit or node.

    Cannot open new Jupyter Notebook [Permission Denied]

    The top answer here didn't quite fix the problem, although it's probably a necessary step:

    sudo chown -R user:user ~/.local/share/jupyter 
    

    (user should be whoever is the logged in user running the notebook server) This changes the folder owner to the user running the server, giving it full access.

    After doing this, the error message said it didn't have permission to create the checkpoint file in ~/.ipynb_checkpoints/ so I also changed ownership of that folder (which was previously root)

    sudo chown -R user:user ~/.ipynb_checkpoints/
    

    And then I was able to create and save a notebook!

    How do I automatically scroll to the bottom of a multiline text box?

    Try to add the suggested code to the TextChanged event:

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
      textBox1.SelectionStart = textBox1.Text.Length;
      textBox1.ScrollToCaret();
    }
    

    How do I know which version of Javascript I'm using?

    Rather than finding which version you are using you can rephrase your question to "which version of ECMA script does my browser's JavaScript/JSscript engine conform to".

    For IE :

    alert(@_jscript_version);      //IE
    

    Refer Squeegy's answer for non-IE versions :)

    Email Address Validation in Android on EditText

    public static boolean isEmailValid(String email) {
        boolean isValid = false;
    
        String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
        CharSequence inputStr = email;
    
        Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(inputStr);
        if (matcher.matches()) {
            isValid = true;
        }
        return isValid;
    }
    

    C free(): invalid pointer

    You can't call free on the pointers returned from strsep. Those are not individually allocated strings, but just pointers into the string s that you've already allocated. When you're done with s altogether, you should free it, but you do not have to do that with the return values of strsep.

    How to get the file ID so I can perform a download of a file from Google Drive API on Android?

    This script logs all the file names and ids in the drive:

    // Log the name and id of every file in the user's Drive
    function listFiles() {
      var files = DriveApp.getFiles();
      while ( files.hasNext() ) {
        var file = files.next();
        Logger.log( file.getName() + ' ' + file.getId() );
      }
    }  
    

    Also, the "Files: list" page has a form at the end that lists the metadata of all the files in the drive, that can be used in case you need but a few ids.

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

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

    This could be due to a few things:

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

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

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

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

    Simulator or Emulator? What is the difference?

    I don't think emulator and simulator can be compared. Both mimic something, but are not part of the same scope of reasonning, they are not used in the same context.

    In short: an emulator is designed to copy some features of the orginial and can even replace it in the real environment. A simulator is not desgined to copy the features of the original, but only to appear similar to the original to human beings. Without the features of the orginal, the simulator cannot replace it in the real environment.

    An emulator is a device that mimics something close enough so that it can be substituted to the real thing. E.g you want a circuit to work like a ROM (read only memory) circuit, but also wants to adjust the content until it is what you want. You'll use a ROM emulator, a black box (likely to be CPU-based) with a physical and electrical interfaces compatible with the ROM you want to emulate. The emulator will be plugged into the device in place of the real ROM. The motherboard will not see any difference when working, but you will be able to change the emulated-ROM content easily. Said otherwise the emulator will act exactly as the actual thing in its motherboard context (maybe a little bit slower due to actual internal model) but there will be additional functions (like re-writing) visible only to the designer, out of the motherboard context. So emulator definition would be: something that mimic the original, has all of its functional features, can actually replace it to some extend in the real world, and may have additional features not visible in the normal context.

    A simulator is used in another thinking context, e.g a plane simulator, a car simulator, etc. The simulation will take care only of some aspect of the actual thing, usually those related to how a human being will perceive and control it. The simulator will not perform the functions of the real stuff, and cannot be sustituted to it. The plane simulator will not fly or carry someone, it's not its purpose at all. The simulator is not intended to work, but to appear to the pilot somehow like the actual thing for purposes other than its normal ones, e.g. to allow ground training (including in unusual situations like all-engine failure). So simulator definition would be: something that can appear to human, to some extend, like the original, but cannot replace it for actual use. In addition the pilot will know that the simulator is a simulator.

    I don't think we'll see any ROM simulator, because ROM are not interacting with human beings, nor we'll see any plane emulator, because planes cannot have a replacement performing the same functions in the real world.

    In my view the model inside an emulator or a simulator can be anything, and has not to be similar to the model of the original. A ROM emulator model will likely be software instead of hardware, MS Flight Simulator cannot be more software than it is.

    This comparison of both terms will contradict the currently selected answer (from Toybuilder) which puts the difference on the internal model, while my suggestion is that the difference is whether the fake can or cannot be used to perform the actual function in the actual world (to some accepted extend, indeed).

    Note that the plane simulator will have also to simulate the earth, the sun, the wind, etc, which are not part of the plane, so a plane simulator will have to mimic some aspects of the plane, as well as the environment of the plane because it is not used in this actual environment, but in a training room.

    This is a big difference with the emulator which emulates only the orginal, and its purpose is to be used in the environment of the original with no need to emulate it. Back to the plane context... what could be a plane emulator? Maybe a train that will connect two airports -- actually two plane steps -- carrying passengers, with stewardesses onboard, with car interior looking like an actual plane cabin, and with captain saying "ladies and gentlemen our altitude is currenlty 10 kms and the temperature at our destination is 24°C". Its benefit is difficult to see, hum...

    As a conclusion, the emulator is a real thing intended to work, the simulator is a fake intended to trick the user.

    object==null or null==object?

    In Java there is no good reason.

    A couple of other answers have claimed that it's because you can accidentally make it assignment instead of equality. But in Java, you have to have a boolean in an if, so this:

    if (o = null)
    

    will not compile.

    The only time this could matter in Java is if the variable is boolean:

    int m1(boolean x)
    {
        if (x = true)  // oops, assignment instead of equality
    

    How can I make content appear beneath a fixed DIV element?

    If your menu height is variable (for responsiveness or because it's loaded dynamically), you can set the top margin to where the fixed div ends. For example:

    CSS

    .fixed-header {
        width: 100%;
        margin: 0 auto;
        position: fixed;
        -webkit-box-sizing: border-box;
        -moz-box-sizing: border-box;
        -ms-box-sizing: border-box;
        box-sizing: border-box;
        z-index: 999;
    }
    

    Javascript

    $(document).ready(function() {
        var contentPlacement = $('#header').position().top + $('#header').height();
        $('#content').css('margin-top',contentPlacement);
    });
    

    HTML

    ...
    <div id="header" class="fixed-header"></div>
    <div id="content">...</div>
    ...
    

    Here's a fiddle (https://jsfiddle.net/632k9xkv/5/) that goes a little beyond this with both a fixed nav menu and header in an attempt to hopefully make this a useful sample.

    How to make a cross-module variable?

    I believe that there are plenty of circumstances in which it does make sense and it simplifies programming to have some globals that are known across several (tightly coupled) modules. In this spirit, I would like to elaborate a bit on the idea of having a module of globals which is imported by those modules which need to reference them.

    When there is only one such module, I name it "g". In it, I assign default values for every variable I intend to treat as global. In each module that uses any of them, I do not use "from g import var", as this only results in a local variable which is initialized from g only at the time of the import. I make most references in the form g.var, and the "g." serves as a constant reminder that I am dealing with a variable that is potentially accessible to other modules.

    If the value of such a global variable is to be used frequently in some function in a module, then that function can make a local copy: var = g.var. However, it is important to realize that assignments to var are local, and global g.var cannot be updated without referencing g.var explicitly in an assignment.

    Note that you can also have multiple such globals modules shared by different subsets of your modules to keep things a little more tightly controlled. The reason I use short names for my globals modules is to avoid cluttering up the code too much with occurrences of them. With only a little experience, they become mnemonic enough with only 1 or 2 characters.

    It is still possible to make an assignment to, say, g.x when x was not already defined in g, and a different module can then access g.x. However, even though the interpreter permits it, this approach is not so transparent, and I do avoid it. There is still the possibility of accidentally creating a new variable in g as a result of a typo in the variable name for an assignment. Sometimes an examination of dir(g) is useful to discover any surprise names that may have arisen by such accident.

    How to write a multidimensional array to a text file?

    If you don't need a human-readable output, another option you could try is to save the array as a MATLAB .mat file, which is a structured array. I despise MATLAB, but the fact that I can both read and write a .mat in very few lines is convenient.

    Unlike Joe Kington's answer, the benefit of this is that you don't need to know the original shape of the data in the .mat file, i.e. no need to reshape upon reading in. And, unlike using pickle, a .mat file can be read by MATLAB, and probably some other programs/languages as well.

    Here is an example:

    import numpy as np
    import scipy.io
    
    # Some test data
    x = np.arange(200).reshape((4,5,10))
    
    # Specify the filename of the .mat file
    matfile = 'test_mat.mat'
    
    # Write the array to the mat file. For this to work, the array must be the value
    # corresponding to a key name of your choice in a dictionary
    scipy.io.savemat(matfile, mdict={'out': x}, oned_as='row')
    
    # For the above line, I specified the kwarg oned_as since python (2.7 with 
    # numpy 1.6.1) throws a FutureWarning.  Here, this isn't really necessary 
    # since oned_as is a kwarg for dealing with 1-D arrays.
    
    # Now load in the data from the .mat that was just saved
    matdata = scipy.io.loadmat(matfile)
    
    # And just to check if the data is the same:
    assert np.all(x == matdata['out'])
    

    If you forget the key that the array is named in the .mat file, you can always do:

    print matdata.keys()
    

    And of course you can store many arrays using many more keys.

    So yes – it won't be readable with your eyes, but only takes 2 lines to write and read the data, which I think is a fair trade-off.

    Take a look at the docs for scipy.io.savemat and scipy.io.loadmat and also this tutorial page: scipy.io File IO Tutorial

    Sass Variable in CSS calc() function

    To use $variables inside your calc() of the height property:

    HTML:

    <div></div>
    

    SCSS:

    $a: 4em;
    
    div {
      height: calc(#{$a} + 7px);
      background: #e53b2c;
    }
    

    Fixed height and width for bootstrap carousel

    Because some images could have less than 500px of height, it's better to keep the auto-adjust, so i recommend the following:

    <div class="carousel-inner" role="listbox" style="max-width:900px; max-height:600px !important;">`
    

    Chrome sendrequest error: TypeError: Converting circular structure to JSON

    One approach is to strip object and functions from main object. And stringify the simpler form

    function simpleStringify (object){
        var simpleObject = {};
        for (var prop in object ){
            if (!object.hasOwnProperty(prop)){
                continue;
            }
            if (typeof(object[prop]) == 'object'){
                continue;
            }
            if (typeof(object[prop]) == 'function'){
                continue;
            }
            simpleObject[prop] = object[prop];
        }
        return JSON.stringify(simpleObject); // returns cleaned up JSON
    };
    

    How to send a html email with the bash command "sendmail"?

    To follow up on the previous answer using mail :

    Often times one's html output is interpreted by the client mailer, which may not format things using a fixed-width font. Thus your nicely formatted ascii alignment gets all messed up. To send old-fashioned fixed-width the way the God intended, try this:

    { echo -e "<pre>"
    echo "Descriptive text here."
    shell_command_1_here
    another_shell_command
    cat <<EOF
    
    This is the ending text.
    </pre><br>
    </div>
    EOF
    } | mail -s "$(echo -e 'Your subject.\nContent-Type: text/html')" [email protected]
    

    You don't necessarily need the "Descriptive text here." line, but I have found that sometimes the first line may, depending on its contents, cause the mail program to interpret the rest of the file in ways you did not intend. Try the script with simple descriptive text first, before fine tuning the output in the way that you want.

    How to get position of a certain element in strings vector, to use it as an index in ints vector?

    To get a position of an element in a vector knowing an iterator pointing to the element, simply subtract v.begin() from the iterator:

    ptrdiff_t pos = find(Names.begin(), Names.end(), old_name_) - Names.begin();
    

    Now you need to check pos against Names.size() to see if it is out of bounds or not:

    if(pos >= Names.size()) {
        //old_name_ not found
    }
    

    vector iterators behave in ways similar to array pointers; most of what you know about pointer arithmetic can be applied to vector iterators as well.

    Starting with C++11 you can use std::distance in place of subtraction for both iterators and pointers:

    ptrdiff_t pos = distance(Names.begin(), find(Names.begin(), Names.end(), old_name_));
    

    JAVA_HOME should point to a JDK not a JRE

    Control Panel -> System and Security -> System -> Advanced system settings -> Advanced -> Environment Variables -> New System Variable

    enter image description here

    Read Post Data submitted to ASP.Net Form

    NameValueCollection nvclc = Request.Form;
    string   uName= nvclc ["txtUserName"];
    string   pswod= nvclc ["txtPassword"];
    //try login
    CheckLogin(uName, pswod);
    

    Get List of connected USB Devices

      lstResult.Clear();
      foreach (ManagementObject drive in new ManagementObjectSearcher("select * from Win32_DiskDrive where InterfaceType='USB'").Get())
      {
           foreach (ManagementObject partition in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + drive["DeviceID"] + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition").Get())
           {
                foreach (ManagementObject disk in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + partition["DeviceID"] + "'} WHERE AssocClass = Win32_LogicalDiskToPartition").Get())
                {
                      foreach (var item in disk.Properties)
                      {
                           object value = disk.GetPropertyValue(item.Name);
                      }
                      string valor = disk["Name"].ToString();
                      lstResult.Add(valor);
                      }
                 }
            }
       }
    

    How to get the date from jQuery UI datepicker

    Use

    var jsDate = $('#your_datepicker_id').datepicker('getDate');
    if (jsDate !== null) { // if any date selected in datepicker
        jsDate instanceof Date; // -> true
        jsDate.getDate();
        jsDate.getMonth();
        jsDate.getFullYear();
    }
    

    How to Set Selected value in Multi-Value Select in Jquery-Select2.?

    you can add the selected values in an array and set it as the value for default selection

    eg:

    var selectedItems =[];
    selectedItems.push("your selected items");
    ..
    $('#drp_Books_Ill_Illustrations').select2('val',selectedItems );
    

    Try this, this should definitely work!

    How to use youtube-dl from a python program?

    If youtube-dl is a terminal program, you can use the subprocess module to access the data you want.

    Check out this link for more details: Calling an external command in Python

    How to get the latest tag name in current branch in Git?

    For the question as asked,

    How to get the latest tag name in the current branch

    you want

    git log --first-parent --pretty=%d | grep -m1 tag:
    

    --first-parent tells git log not to detail any merged histories, --pretty=%d says to show only the decorations i.e. local names for any commits. grep -m1 says "match just one", so you get just the most-recent tag.

    Visual Studio opens the default browser instead of Internet Explorer

    In visual studio 2013, this can be done as follows:

    1) Ensure you have selected a start up project from your solution explore window 2) This brings a drop down to the left of the debug drop down. You can choose browser from this new drop down.

    Key is there should be a project selected as start up

    How to set or change the default Java (JDK) version on OS X?

    If you have multiple versions and you want to run something by using a specific version, use this example:

    /usr/libexec/java_home -v 1.7.0_75 --exec java -jar you-file.jar
    

    What is newline character -- '\n'

    Try this:

    $ sed -e $'s/\n/\n\n/g' states
    

    How to move all HTML element children to another parent using JavaScript?

    DEMO

    Basically, you want to loop through each direct descendent of the old-parent node, and move it to the new parent. Any children of a direct descendent will get moved with it.

    var newParent = document.getElementById('new-parent');
    var oldParent = document.getElementById('old-parent');
    
    while (oldParent.childNodes.length > 0) {
        newParent.appendChild(oldParent.childNodes[0]);
    }
    

    HTTPS connection Python

    If using httplib.HTTPSConnection:

    Please take a look at:

    Changed in version 2.7.9:

    This class now performs all the necessary certificate and hostname checks by default. To revert to the previous, unverified, behavior ssl._create_unverified_context() can be passed to the context parameter. You can use:

    if hasattr(ssl, '_create_unverified_context'):
      ssl._create_default_https_context = ssl._create_unverified_context
    

    How to sum columns in a dataTable?

    Try this:

                DataTable dt = new DataTable();
                int sum = 0;
                foreach (DataRow dr in dt.Rows)
                {
                    foreach (DataColumn dc in dt.Columns)
                    {
                        sum += (int)dr[dc];
                    }
                } 
    

    'cl' is not recognized as an internal or external command,

    I sometimes get this problem when changing from Debug to Release or vice-versa. Closing and reopening QtCreator and building again solves the problem for me.

    Qt Creator 2.8.1; Qt 5.1.1 (MSVC2010, 32bit)

    "Python version 2.7 required, which was not found in the registry" error when attempting to install netCDF4 on Windows 8

    I had the same issue when using an .exe to install a Python package (because I use Anaconda and it didn't add Python to the registry). I fixed the problem by running this script:

    #
    # script to register Python 2.0 or later for use with 
    # Python extensions that require Python registry settings
    #
    # written by Joakim Loew for Secret Labs AB / PythonWare
    #
    # source:
    # http://www.pythonware.com/products/works/articles/regpy20.htm
    #
    # modified by Valentine Gogichashvili as described in http://www.mail-archive.com/[email protected]/msg10512.html
    
    import sys
    
    from _winreg import *
    
    # tweak as necessary
    version = sys.version[:3]
    installpath = sys.prefix
    
    regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % (version)
    installkey = "InstallPath"
    pythonkey = "PythonPath"
    pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % (
        installpath, installpath, installpath
    )
    
    def RegisterPy():
        try:
            reg = OpenKey(HKEY_CURRENT_USER, regpath)
        except EnvironmentError as e:
            try:
                reg = CreateKey(HKEY_CURRENT_USER, regpath)
                SetValue(reg, installkey, REG_SZ, installpath)
                SetValue(reg, pythonkey, REG_SZ, pythonpath)
                CloseKey(reg)
            except:
                print "*** Unable to register!"
                return
            print "--- Python", version, "is now registered!"
            return
        if (QueryValue(reg, installkey) == installpath and
            QueryValue(reg, pythonkey) == pythonpath):
            CloseKey(reg)
            print "=== Python", version, "is already registered!"
            return
        CloseKey(reg)
        print "*** Unable to register!"
        print "*** You probably have another Python installation!"
    
    if __name__ == "__main__":
        RegisterPy()
    

    How to style an asp.net menu with CSS

    There are well achieved third-party tools, but i usually use superfish http://www.conceptdevelopment.net/Fun/Superfish/ it's cool, free and easy ;)

    Can’t delete docker image with dependent child images

    Building on Simon Brady's brute force method here, if you don't have a ton of images you can use this shell function:

    recursive_remove_image() {
      for image in $(docker images --quiet --filter "since=${1}")
      do
        if [ $(docker history --quiet ${image} | grep ${1}) ]
        then
          recursive_remove_image "${image}"
        fi
      done
      echo "Removing: ${1}"
      docker rmi -f ${1}
    }
    

    and then call it using recursive_remove_image <image-id>.

    Export DataTable to Excel File

    While not a .NET implementation, you may find that the plug-in TableTools may be highly effective depending on your audience. It relies upon flash which shouldn't be a problem for most cases of needing to actually work in-depth and then want to record tabular information.

    The latest version appears to support copying to clipboard, into a CSV, ".XLS" (really just a tab-delimited file named .xls), to a PDF, or create a printer friendly page version with all rows displayed and the rest of your page's contents hidden.

    I found the extension on the DataTables site here: http://datatables.net/extras/tabletools/

    The download is available in the plug-ins (extras) page here: http://datatables.net/extras/

    It supposedly is downloaded as a part of DataTables (hence the phrase "Extras included in the DataTables package") but I didn't find it in the download I have been using. Seems to work wonderfully!

    How to redirect to another page using AngularJS?

    I used the below code to redirect to new page

    $window.location.href = '/foldername/page.html';
    

    and injected $window object in my controller function.

    Retrieving JSON Object Literal from HttpServletRequest

    There is another way to do it, using org.apache.commons.io.IOUtils to extract the String from the request

    String jsonString = IOUtils.toString(request.getInputStream());
    

    Then you can do whatever you want, convert it to JSON or other object with Gson, etc.

    JSONObject json = new JSONObject(jsonString);
    MyObject myObject = new Gson().fromJson(jsonString, MyObject.class);
    

    How can I retrieve Id of inserted entity using Entity framework?

    I had been using Ladislav Mrnka's answer to successfully retrieve Ids when using the Entity Framework however I am posting here because I had been miss-using it (i.e. using it where it wasn't required) and thought I would post my findings here in-case people are looking to "solve" the problem I had.

    Consider an Order object that has foreign key relationship with Customer. When I added a new customer and a new order at the same time I was doing something like this;

    var customer = new Customer(); //no Id yet;
    var order = new Order(); //requires Customer.Id to link it to customer;
    context.Customers.Add(customer);
    context.SaveChanges();//this generates the Id for customer
    order.CustomerId = customer.Id;//finally I can set the Id
    

    However in my case this was not required because I had a foreign key relationship between customer.Id and order.CustomerId

    All I had to do was this;

    var customer = new Customer(); //no Id yet;
    var order = new Order{Customer = customer}; 
    context.Orders.Add(order);
    context.SaveChanges();//adds customer.Id to customer and the correct CustomerId to order
    

    Now when I save the changes the id that is generated for customer is also added to order. I've no need for the additional steps

    I'm aware this doesn't answer the original question but thought it might help developers who are new to EF from over-using the top-voted answer for something that may not be required.

    This also means that updates complete in a single transaction, potentially avoiding orphin data (either all updates complete, or none do).

    How do I find the length/number of items present for an array?

    I'm not sure that i know exactly what you mean.

    But to get the length of an initialized array,

    doesn't strlen(string) work ??

    How to install PHP intl extension in Ubuntu 14.04

    you could search with aptitude search intl after you can choose the right one, for example sudo aptitude install php-intl and finally sudo service apache2 restart

    good Luck!

    How do I compare strings in GoLang?

    The content inside strings in Golang can be compared using == operator. If the results are not as expected there may be some hidden characters like \n, \r, spaces, etc. So as a general rule of thumb, try removing those using functions provided by strings package in golang.

    For Instance, spaces can be removed using strings.TrimSpace function. You can also define a custom function to remove any character you need. strings.TrimFunc function can give you more power.

    'foo' was not declared in this scope c++

    In C++, your source files are usually parsed from top to bottom in a single pass, so any variable or function must be declared before they can be used. There are some exceptions to this, like when defining functions inline in a class definition, but that's not the case for your code.

    Either move the definition of integrate above the one for getSkewNormal, or add a forward declaration above getSkewNormal:

    double integrate (double start, double stop, int numSteps, Evaluatable evalObj);
    

    The same applies for sum.

    How to get rid of underline for Link component of React Router?

    If you are using styled-components, you could do something like this:

    import React, { Component } from 'react';
    import { Link } from 'react-router-dom';
    import styled from 'styled-components';
    
    
    const StyledLink = styled(Link)`
        text-decoration: none;
    
        &:focus, &:hover, &:visited, &:link, &:active {
            text-decoration: none;
        }
    `;
    
    export default (props) => <StyledLink {...props} />;
    

    How to make div background color transparent in CSS

    It might be a little late to the discussion but inevitably someone will stumble onto this post like I did. I found the answer I was looking for and thought I'd post my own take on it. The following JSfiddle includes how to layer .PNG's with transparency. Jerska's mention of the transparency attribute for the div's CSS was the solution: http://jsfiddle.net/jyef3fqr/

    HTML:

       <button id="toggle-box">toggle</button>
       <div id="box" style="display:none;" ><img src="x"></div>
       <button id="toggle-box2">toggle</button>
       <div id="box2" style="display:none;"><img src="xx"></div>
       <button id="toggle-box3">toggle</button>
       <div id="box3" style="display:none;" ><img src="xxx"></div>
    

    CSS:

    #box {
    background-color: #ffffff;
    height:400px;
    width: 1200px;
    position: absolute;
    top:30px;
    z-index:1;
    }
    #box2 {
    background-color: #ffffff;
    height:400px;
    width: 1200px;
    position: absolute;
    top:30px;
    z-index:2;
    background-color : transparent;
          }
          #box3 {
    background-color: #ffffff;
    height:400px;
    width: 1200px;
    position: absolute;
    top:30px;
    z-index:2;
    background-color : transparent;
          }
     body {background-color:#c0c0c0; }
    

    JS:

    $('#toggle-box').click().toggle(function() {
    $('#box').animate({ width: 'show' });
    }, function() {
    $('#box').animate({ width: 'hide' });
    });
    
    $('#toggle-box2').click().toggle(function() {
    $('#box2').animate({ width: 'show' });
    }, function() {
    $('#box2').animate({ width: 'hide' });
    });
    $('#toggle-box3').click().toggle(function() {
    $('#box3').animate({ width: 'show' });
     }, function() {
    $('#box3').animate({ width: 'hide' });
    });
    

    And my original inspiration:http://jsfiddle.net/5g1zwLe3/ I also used paint.net for creating the transparent PNG's, or rather the PNG's with transparent BG's.

    Can an Option in a Select tag carry multiple values?

    I did this by using data attributes. Is a lot cleaner than other methods attempting to explode etc.

    HTML

    <select class="example">
        <option value="1" data-value="A">One</option>
        <option value="2" data-value="B">Two</option>
        <option value="3" data-value="C">Three</option>
        <option value="4" data-value="D">Four</option>
    </select>
    

    JS

    $('select.example').change(function() {
    
        var other_val = $('select.example option[value="' + $(this).val() + '"]').data('value');
    
        console.log(other_val);
    
    });
    

    SQL Query to fetch data from the last 30 days?

    The easiest way would be to specify

    SELECT productid FROM product where purchase_date > sysdate-30;

    Remember this sysdate above has the time component, so it will be purchase orders newer than 03-06-2011 8:54 AM based on the time now.

    If you want to remove the time conponent when comparing..

    SELECT productid FROM product where purchase_date > trunc(sysdate-30);
    

    And (based on your comments), if you want to specify a particular date, make sure you use to_date and not rely on the default session parameters.

    SELECT productid FROM product where purchase_date > to_date('03/06/2011','mm/dd/yyyy')

    And regardng the between (sysdate-30) - (sysdate) comment, for orders you should be ok with usin just the sysdate condition unless you can have orders with order_dates in the future.

    Combine Points with lines with ggplot2

    A small change to Paul's code so that it doesn't return the error mentioned above.

    dat = melt(subset(iris, select = c("Sepal.Length","Sepal.Width", "Species")),
               id.vars = "Species")
    dat$x <- c(1:150, 1:150)
    ggplot(aes(x = x, y = value, color = variable), data = dat) +  
      geom_point() + geom_line()
    

    File upload from <input type="file">

    Another way using template reference variable and ViewChild, as proposed by Frelseren:

    import { ViewChild } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      template: `
        <div>
          <input type="file" #fileInput/>
        </div>
      `
    })  
    export class AppComponent {
      @ViewChild("fileInput") fileInputVariable: any;
      randomMethod() {
        const files = this.fileInputVariable.nativeElement.files;
        console.log(files);
      }
    }
    

    Also see https://stackoverflow.com/a/40165524/4361955

    How do you get assembler output from C/C++ source in gcc?

    If you're looking for LLVM assembly:

    llvm-gcc -emit-llvm -S hello.c
    

    node.js require() cache - possible to invalidate?

    I couldn't neatly add code in an answer's comment. But I would use @Ben Barkay's answer then add this to the require.uncache function.

        // see https://github.com/joyent/node/issues/8266
        // use in it in @Ben Barkay's require.uncache function or along with it. whatever
        Object.keys(module.constructor._pathCache).forEach(function(cacheKey) {
            if ( cacheKey.indexOf(moduleName) > -1 ) {
                delete module.constructor._pathCache[ cacheKey ];
            }
        }); 
    

    Say you've required a module, then uninstalled it, then reinstalled the same module but used a different version that has a different main script in its package.json, the next require will fail because that main script does not exists because it's cached in Module._pathCache

    Reading a single char in Java

    You can use a Scanner for this. It's not clear what your exact requirements are, but here's an example that should be illustrative:

        Scanner sc = new Scanner(System.in).useDelimiter("\\s*");
        while (!sc.hasNext("z")) {
            char ch = sc.next().charAt(0);
            System.out.print("[" + ch + "] ");
        }
    

    If you give this input:

    123 a b c x   y   z
    

    The output is:

    [1] [2] [3] [a] [b] [c] [x] [y] 
    

    So what happens here is that the Scanner uses \s* as delimiter, which is the regex for "zero or more whitespace characters". This skips spaces etc in the input, so you only get non-whitespace characters, one at a time.

    Checking if an object is null in C#

    You cannot use ToString() on a null object so use a Null Coalescing Operator to assign an empty string to the null object then evaluate with IsNullOrEmpty

            var foo = obj ?? "";
    
            if (!String.IsNullOrEmpty(foo.ToString()))
            {
              //Do something
            }
    

    What does a just-in-time (JIT) compiler do?

    Jit stands for just in time compiler jit is a program that turns java byte code into instruction that can be sent directly to the processor.

    Using the java just in time compiler (really a second compiler) at the particular system platform complies the bytecode into particular system code,once the code has been re-compiled by the jit complier ,it will usually run more quickly in the computer.

    The just-in-time compiler comes with the virtual machine and is used optionally. It compiles the bytecode into platform-specific executable code that is immediately executed.

    YAML Multi-Line Arrays

    If what you are needing is an array of arrays, you can do this way:

    key:
      - [ 'value11', 'value12', 'value13' ]
      - [ 'value21', 'value22', 'value23' ]
    

    Using Sockets to send and receive data

        //Client
    
        import java.io.*;
        import java.net.*;
    
        public class Client {
            public static void main(String[] args) {
    
            String hostname = "localhost";
            int port = 6789;
    
            // declaration section:
            // clientSocket: our client socket
            // os: output stream
            // is: input stream
    
                Socket clientSocket = null;  
                DataOutputStream os = null;
                BufferedReader is = null;
    
            // Initialization section:
            // Try to open a socket on the given port
            // Try to open input and output streams
    
                try {
                    clientSocket = new Socket(hostname, port);
                    os = new DataOutputStream(clientSocket.getOutputStream());
                    is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                } catch (UnknownHostException e) {
                    System.err.println("Don't know about host: " + hostname);
                } catch (IOException e) {
                    System.err.println("Couldn't get I/O for the connection to: " + hostname);
                }
    
            // If everything has been initialized then we want to write some data
            // to the socket we have opened a connection to on the given port
    
            if (clientSocket == null || os == null || is == null) {
                System.err.println( "Something is wrong. One variable is null." );
                return;
            }
    
            try {
                while ( true ) {
                System.out.print( "Enter an integer (0 to stop connection, -1 to stop server): " );
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                String keyboardInput = br.readLine();
                os.writeBytes( keyboardInput + "\n" );
    
                int n = Integer.parseInt( keyboardInput );
                if ( n == 0 || n == -1 ) {
                    break;
                }
    
                String responseLine = is.readLine();
                System.out.println("Server returns its square as: " + responseLine);
                }
    
                // clean up:
                // close the output stream
                // close the input stream
                // close the socket
    
                os.close();
                is.close();
                clientSocket.close();   
            } catch (UnknownHostException e) {
                System.err.println("Trying to connect to unknown host: " + e);
            } catch (IOException e) {
                System.err.println("IOException:  " + e);
            }
            }           
        }
    
    
    
    
    
    //Server
    
    
    
    
    import java.io.*;
    import java.net.*;
    
    public class Server1 {
        public static void main(String args[]) {
        int port = 6789;
        Server1 server = new Server1( port );
        server.startServer();
        }
    
        // declare a server socket and a client socket for the server
    
        ServerSocket echoServer = null;
        Socket clientSocket = null;
        int port;
    
        public Server1( int port ) {
        this.port = port;
        }
    
        public void stopServer() {
        System.out.println( "Server cleaning up." );
        System.exit(0);
        }
    
        public void startServer() {
        // Try to open a server socket on the given port
        // Note that we can't choose a port less than 1024 if we are not
        // privileged users (root)
    
            try {
            echoServer = new ServerSocket(port);
            }
            catch (IOException e) {
            System.out.println(e);
            }   
    
        System.out.println( "Waiting for connections. Only one connection is allowed." );
    
        // Create a socket object from the ServerSocket to listen and accept connections.
        // Use Server1Connection to process the connection.
    
        while ( true ) {
            try {
            clientSocket = echoServer.accept();
            Server1Connection oneconnection = new Server1Connection(clientSocket, this);
            oneconnection.run();
            }   
            catch (IOException e) {
            System.out.println(e);
            }
        }
        }
    }
    
    class Server1Connection {
        BufferedReader is;
        PrintStream os;
        Socket clientSocket;
        Server1 server;
    
        public Server1Connection(Socket clientSocket, Server1 server) {
        this.clientSocket = clientSocket;
        this.server = server;
        System.out.println( "Connection established with: " + clientSocket );
        try {
            is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            os = new PrintStream(clientSocket.getOutputStream());
        } catch (IOException e) {
            System.out.println(e);
        }
        }
    
        public void run() {
            String line;
        try {
            boolean serverStop = false;
    
                while (true) {
                    line = is.readLine();
            System.out.println( "Received " + line );
                    int n = Integer.parseInt(line);
            if ( n == -1 ) {
                serverStop = true;
                break;
            }
            if ( n == 0 ) break;
                    os.println("" + n*n ); 
                }
    
            System.out.println( "Connection closed." );
                is.close();
                os.close();
                clientSocket.close();
    
            if ( serverStop ) server.stopServer();
        } catch (IOException e) {
            System.out.println(e);
        }
        }
    }
    

    Find position of a node using xpath

    If you ever upgrade to XPath 2.0, note that it provides function index-of, it solves problem this way:

    index-of(//b, //b[.='tsr'])
    

    Where:

    • 1st parameter is sequence for searching
    • 2nd is what to search

    How to use absolute path in twig functions

    From Symfony2 documentation: Absolute URLs for assets were introduced in Symfony 2.5.

    If you need absolute URLs for assets, you can set the third argument (or the absolute argument) to true:

    Example:

    <img src="{{ asset('images/logo.png', absolute=true) }}" alt="Symfony!" />
    

    Adding elements to a collection during iteration

    Using iterators...no, I don't think so. You'll have to hack together something like this:

        Collection< String > collection = new ArrayList< String >( Arrays.asList( "foo", "bar", "baz" ) );
        int i = 0;
        while ( i < collection.size() ) {
    
            String curItem = collection.toArray( new String[ collection.size() ] )[ i ];
            if ( curItem.equals( "foo" ) ) {
                collection.add( "added-item-1" );
            }
            if ( curItem.equals( "added-item-1" ) ) {
                collection.add( "added-item-2" );
            }
    
            i++;
        }
    
        System.out.println( collection );
    

    Which yeilds:
    [foo, bar, baz, added-item-1, added-item-2]

    Rails Active Record find(:all, :order => ) issue

    isn't it only :order => 'column1 ASC, column2 DESC'?

    Using G++ to compile multiple .cpp and .h files

    I used to use a custom Makefile that compiled all the files in current directory, but I had to copy it in every directory I needed it, everytime.

    So I created my own tool - Universal Compiler which made the process much easier when compile many files.

    Purpose of "%matplotlib inline"

    If you want to add plots to your Jupyter notebook, then %matplotlib inline is a standard solution. And there are other magic commands will use matplotlib interactively within Jupyter.

    %matplotlib: any plt plot command will now cause a figure window to open, and further commands can be run to update the plot. Some changes will not draw automatically, to force an update, use plt.draw()

    %matplotlib notebook: will lead to interactive plots embedded within the notebook, you can zoom and resize the figure

    %matplotlib inline: only draw static images in the notebook

    How to convert existing non-empty directory into a Git working directory and push files to a remote repository

    I had a similar problem. I created a new repository, NOT IN THE DIRECTORY THAT I WANTED TO MAKE A REPOSITORY. I then copied the files created to the directory I wanted to make a repository. Then open an existing repository using the directory I just copied the files to.

    NOTE: I did use github desktop to make and open exiting repository.

    C++ string to double conversion

    The C++ way of solving conversions (not the classical C) is illustrated with the program below. Note that the intent is to be able to use the same formatting facilities offered by iostream like precision, fill character, padding, hex, and the manipulators, etcetera.

    Compile and run this program, then study it. It is simple

    #include "iostream"
    #include "iomanip"
    #include "sstream"
    using namespace std;
    
    int main()
    {
        // Converting the content of a char array or a string to a double variable
        double d;
        string S;
        S = "4.5";
        istringstream(S) >> d;    
        cout << "\nThe value of the double variable d is " << d << endl;
        istringstream("9.87654") >> d;  
        cout << "\nNow the value of the double variable d is " << d << endl;
    
    
    
        // Converting a double to string with formatting restrictions
        double D=3.771234567;
    
        ostringstream Q;
        Q.fill('#');
        Q << "<<<" << setprecision(6) << setw(20) << D << ">>>";
        S = Q.str(); // formatted converted double is now in string 
    
        cout << "\nThe value of the string variable S is " << S << endl;
        return 0;
    }
    

    Prof. Martinez

    JSON ValueError: Expecting property name: line 1 column 2 (char 1)

    A different case in which I encountered this was when I was using echo to pipe the JSON into my python script and carelessly wrapped the JSON string in double quotes:

    echo "{"thumbnailWidth": 640}" | myscript.py
    

    Note that the JSON string itself has quotes and I should have done:

    echo '{"thumbnailWidth": 640}' | myscript.py
    

    As it was, this is what the python script received: {thumbnailWidth: 640}; the double quotes were effectively stripped.

    How to change font size on part of the page in LaTeX?

    To add exact fontsize you can use following. Worked for me since in my case predefined ranges (Large, tiny) are not match with the font size required to me.

    \fontsize{10}{12}\selectfont This is the text you need to be in 10px
    

    More info: https://tug.org/TUGboat/tb33-3/tb105thurnherr.pdf

    Need to get current timestamp in Java

    Joda-Time

    Here is the same kind of code but using the third-party library Joda-Time 2.3.

    In real life, I would specify a time zone, as relying on default zone is usually a bad practice. But omitted here for simplicity of example.

    org.joda.time.DateTime now = new DateTime();
    org.joda.time.format.DateTimeFormatter formatter = DateTimeFormat.forPattern( "MM/dd/yyyy h:mm:ss a" );
    String nowAsString = formatter.print( now );
    
    System.out.println( "nowAsString: " + nowAsString );
    

    When run…

    nowAsString: 11/28/2013 11:28:15 PM
    

    How to count number of files in each directory?

    I combined @glenn jackman's answer and @pcarvalho's answer(in comment list, there is something wrong with pcarvalho's answer because the extra style control function of character '`'(backtick)).

    My script can accept path as an augument and sort the directory list as ls -l, also it can handles the problem of "space in file name".

    #!/bin/bash
    OLD_IFS="$IFS"
    IFS=$'\n'
    for dir in $(find $1 -maxdepth 1 -type d | sort); 
    do
        files=("$dir"/*)
        printf "%5d,%s\n" "${#files[@]}" "$dir"
    done
    FS="$OLD_IFS"
    

    My first answer in stackoverflow, and I hope it can help someone ^_^

    How to obtain a QuerySet of all rows, with specific fields for each one of them?

    In addition to values_list as Daniel mentions you can also use only (or defer for the opposite effect) to get a queryset of objects only having their id and specified fields:

    Employees.objects.only('eng_name')
    

    This will run a single query:

    SELECT id, eng_name FROM employees
    

    Disabling and enabling a html input button

    Since you are disabling it in the first place, the way to enable it is to set its disabled property as false.

    To change its disabled property in Javascript, you use this:

    var btn = document.getElementById("Button");
    btn.disabled = false;
    

    And obviously to disable it again, you'd use true instead.

    Since you also tagged the question with jQuery, you could use the .prop method. Something like:

    var btn = $("#Button");
    btn.prop("disabled", true);   // Or `false`
    

    This is in the newer versions of jQuery. The older way to do this is to add or remove an attribute like so:

    var btn = $("#Button");
    btn.attr("disabled", "disabled");
    // or
    btn.removeAttr("disabled");
    

    The mere presence of the disabled property disables the element, so you cannot set its value as "false". Even the following should disable the element

    <input type="button" value="Submit" disabled="" />
    

    You need to either remove the attribute completely or set its property.

    How do I set the timeout for a JAX-WS webservice client?

    I know this is old and answered elsewhere but hopefully this closes this down. I'm not sure why you would want to download the WSDL dynamically but the system properties:

    sun.net.client.defaultConnectTimeout (default: -1 (forever))
    sun.net.client.defaultReadTimeout (default: -1 (forever))
    

    should apply to all reads and connects using HttpURLConnection which JAX-WS uses. This should solve your problem if you are getting the WSDL from a remote location - but a file on your local disk is probably better!

    Next, if you want to set timeouts for specific services, once you've created your proxy you need to cast it to a BindingProvider (which you know already), get the request context and set your properties. The online JAX-WS documentation is wrong, these are the correct property names (well, they work for me).

    MyInterface myInterface = new MyInterfaceService().getMyInterfaceSOAP();
    Map<String, Object> requestContext = ((BindingProvider)myInterface).getRequestContext();
    requestContext.put(BindingProviderProperties.REQUEST_TIMEOUT, 3000); // Timeout in millis
    requestContext.put(BindingProviderProperties.CONNECT_TIMEOUT, 1000); // Timeout in millis
    myInterface.callMyRemoteMethodWith(myParameter);
    

    Of course, this is a horrible way to do things, I would create a nice factory for producing these binding providers that can be injected with the timeouts you want.

    400 vs 422 response to POST of data

    422 Unprocessable Entity Explained Updated: March 6, 2017

    What Is 422 Unprocessable Entity?

    A 422 status code occurs when a request is well-formed, however, due to semantic errors it is unable to be processed. This HTTP status was introduced in RFC 4918 and is more specifically geared toward HTTP extensions for Web Distributed Authoring and Versioning (WebDAV).

    There is some controversy out there on whether or not developers should return a 400 vs 422 error to clients (more on the differences between both statuses below). However, in most cases, it is agreed upon that the 422 status should only be returned if you support WebDAV capabilities.

    A word-for-word definition of the 422 status code taken from section 11.2 in RFC 4918 can be read below.

    The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions.

    The definition goes on to say:

    For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

    400 vs 422 Status Codes

    Bad request errors make use of the 400 status code and should be returned to the client if the request syntax is malformed, contains invalid request message framing, or has deceptive request routing. This status code may seem pretty similar to the 422 unprocessable entity status, however, one small piece of information that distinguishes them is the fact that the syntax of a request entity for a 422 error is correct whereas the syntax of a request that generates a 400 error is incorrect.

    The use of the 422 status should be reserved only for very particular use-cases. In most other cases where a client error has occurred due to malformed syntax, the 400 Bad Request status should be used.

    https://www.keycdn.com/support/422-unprocessable-entity/

    Update multiple values in a single statement

    In Oracle the solution would be:

    UPDATE
        MasterTbl
    SET
        (TotalX,TotalY,TotalZ) =
          (SELECT SUM(X),SUM(Y),SUM(Z)
             from DetailTbl where DetailTbl.MasterID = MasterTbl.ID)
    

    Don't know if your system allows the same.

    How to fetch data from local JSON file on react native?

    Take a look at this Github issue:

    https://github.com/facebook/react-native/issues/231

    They are trying to require non-JSON files, in particular JSON. There is no method of doing this right now, so you either have to use AsyncStorage as @CocoOS mentioned, or you could write a small native module to do what you need to do.

    Escape double quotes in a string

    In C# you can use the backslash to put special characters to your string. For example, to put ", you need to write \". There are a lot of characters that you write using the backslash: Backslash with a number:

    • \000 null
    • \010 backspace
    • \011 horizontal tab
    • \012 new line
    • \015 carriage return
    • \032 substitute
    • \042 double quote
    • \047 single quote
    • \134 backslash
    • \140 grave accent

    Backslash with othe character

    • \a Bell (alert)
    • \b Backspace
    • \f Formfeed
    • \n New line
    • \r Carriage return
    • \t Horizontal tab
    • \v Vertical tab
    • \' Single quotation mark
    • \" Double quotation mark
    • \ Backslash
    • \? Literal question mark
    • \ ooo ASCII character in octal notation
    • \x hh ASCII character in hexadecimal notation
    • \x hhhh Unicode character in hexadecimal notation if this escape sequence is used in a wide-character constant or a Unicode string literal. For example, WCHAR f = L'\x4e00' or WCHAR b[] = L"The Chinese character for one is \x4e00".

    What's the difference between ng-model and ng-bind

    We can use ng-bind with <p> to display, we can use shortcut for ng-bind {{model}}, we cannot use ng-bind with html input controls, but we can use shortcut for ng-bind {{model}} with html input controls.

    <input type="text" ng-model="name" placeholder="Enter Something"/>
    <input type="text" value="{{name}}" placeholder="Enter Something"/>
      Hello {{name}}
    <p ng-bind="name"</p>
    

    Create sequence of repeated values, in sequence?

    You missed the each= argument to rep():

    R> n <- 3
    R> rep(1:5, each=n)
     [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
    R> 
    

    so your example can be done with a simple

    R> rep(1:8, each=20)
    

    How to test if a double is zero?

    Yes, it's a valid test although there's an implicit conversion from int to double. For clarity/simplicity you should use (foo.x == 0.0) to test. That will hinder NAN errors/division by zero, but the double value can in some cases be very very very close to 0, but not exactly zero, and then the test will fail (I'm talking about in general now, not your code). Division by that will give huge numbers.

    If this has anything to do with money, do not use float or double, instead use BigDecimal.

    Updating GUI (WPF) using a different thread

    there.

    I am also developing a serial port testing tool using WPF, and I'd like to share some experience of mine.

    I think you should refactor your source code according to MVVM design pattern.

    At the beginning, I met the same problem as you met, and I solved it using this code:

    new Thread(() => 
    {
        while (...)
        {
            SomeTextBox.Dispatcher.BeginInvoke((Action)(() => SomeTextBox.Text = ...));
        }
    }).Start();
    

    This works, but is too ugly. I have no idea how to refactor it, until I saw this: http://www.codeproject.com/Articles/165368/WPF-MVVM-Quick-Start-Tutorial

    This is a very kindly step-by-step MVVM tutorial for beginners. No shiny UI, no complex logic, only the basic of MVVM.

    Which is the preferred way to concatenate a string in Python?

    You can do in different ways.

    str1 = "Hello"
    str2 = "World"
    str_list = ['Hello', 'World']
    str_dict = {'str1': 'Hello', 'str2': 'World'}
    
    # Concatenating With the + Operator
    print(str1 + ' ' + str2)  # Hello World
    
    # String Formatting with the % Operator
    print("%s %s" % (str1, str2))  # Hello World
    
    # String Formatting with the { } Operators with str.format()
    print("{}{}".format(str1, str2))  # Hello World
    print("{0}{1}".format(str1, str2))  # Hello World
    print("{str1} {str2}".format(str1=str_dict['str1'], str2=str_dict['str2']))  # Hello World
    print("{str1} {str2}".format(**str_dict))  # Hello World
    
    # Going From a List to a String in Python With .join()
    print(' '.join(str_list))  # Hello World
    
    # Python f'strings --> 3.6 onwards
    print(f"{str1} {str2}")  # Hello World
    

    I created this little summary through following articles.

    The mysqli extension is missing. Please check your PHP configuration

    1. Find out which php.ini is used.
    2. In file php.ini this line:

      extension=mysqli
      
    3. Replace by:

      extension="C:\php\ext\php_mysqli.dll"
      
    4. Restart apache

    Spring Boot REST API - request timeout?

    You can try server.connection-timeout=5000 in your application.properties. From the official documentation:

    server.connection-timeout= # Time in milliseconds that connectors will wait for another HTTP request before closing the connection. When not set, the connector's container-specific default will be used. Use a value of -1 to indicate no (i.e. infinite) timeout.

    On the other hand, you may want to handle timeouts on the client side using Circuit Breaker pattern as I have already described in my answer here: https://stackoverflow.com/a/44484579/2328781

    Overriding !important style

    Building on @Premasagar's excellent answer; if you don't want to remove all the other inline styles use this

    //accepts the hyphenated versions (i.e. not 'cssFloat')
    addStyle(element, property, value, important) {
        //remove previously defined property
        if (element.style.setProperty)
            element.style.setProperty(property, '');
        else
            element.style.setAttribute(property, '');
    
        //insert the new style with all the old rules
        element.setAttribute('style', element.style.cssText +
            property + ':' + value + ((important) ? ' !important' : '') + ';');
    }
    

    Can't use removeProperty() because it wont remove !important rules in Chrome.
    Can't use element.style[property] = '' because it only accepts camelCase in FireFox.

    Regex match everything after question mark?

    \?(.*)
    

    You want the content of the first capture group.

    Default value of 'boolean' and 'Boolean' in Java

    class BooleanTester
    {
        boolean primitive;
        Boolean object;
    
        public static void main(String[] args) {
            BooleanTester booleanTester = new BooleanTester();
            System.out.println("primitive: " + booleanTester.getPrimitive());
            System.out.println("object: " + booleanTester.getObject());
    }
    
        public boolean getPrimitive() {
            return primitive;
        }
    
        public Boolean getObject() {
            return object;
        }
    }
    

    output:

    primitive: false
    object: null
    

    This seems obvious but I had a situation where Jackson, while serializing an object to JSON, was throwing an NPE after calling a getter, just like this one, that returns a primitive boolean which was not assigned. This led me to believe that Jackson was receiving a null and trying to call a method on it, hence the NPE. I was wrong.

    Moral of the story is that when Java allocates memory for a primitive, that memory has a value even if not initialized, which Java equates to false for a boolean. By contrast, when allocating memory for an uninitialized complex object like a Boolean, it allocates only space for a reference to that object, not the object itself - there is no object in memory to refer to - so resolving that reference results in null.

    I think that strictly speaking, "defaults to false" is a little off the mark. I think Java does not allocate the memory and assign it a value of false until it is explicitly set; I think Java allocates the memory and whatever value that memory happens to have is the same as the value of 'false'. But for practical purpose they are the same thing.

    How to check if command line tools is installed

    10.14 Mojave Update:

    See Yosemite Update.

    10.13 High Sierra Update:

    See Yosemite Update.

    10.12 Sierra Update:

    See Yosemite Update.

    10.11 El Capitan Update:

    See Yosemite Update.

    10.10 Yosemite Update:

    Just enter in gcc or make on the command line! OSX will know that you do not have the command line tools and prompt you to install them!

    To check if they exist, xcode-select -p will print the directory. Alternatively, the return value will be 2 if they do NOT exist, and 0 if they do. To just print the return value (thanks @Andy):

    xcode-select -p 1>/dev/null;echo $?
    

    10.9 Mavericks Update:

    Use pkgutil --pkg-info=com.apple.pkg.CLTools_Executables

    10.8 Update:

    Option 1: Rob Napier suggested to use pkgutil --pkg-info=com.apple.pkg.DeveloperToolsCLI, which is probably cleaner.

    Option 2: Check inside /var/db/receipts/com.apple.pkg.DeveloperToolsCLI.plist for a reference to com.apple.pkg.DeveloperToolsCLI and it will list the version 4.5.0.

    [Mar 12 17:04] [jnovack@yourmom ~]$ defaults read /var/db/receipts/com.apple.pkg.DeveloperToolsCLI.plist
    {
        InstallDate = "2012-12-26 22:45:54 +0000";
        InstallPrefixPath = "/";
        InstallProcessName = Xcode;
        PackageFileName = "DeveloperToolsCLI.pkg";
        PackageGroups =     (
            "com.apple.FindSystemFiles.pkg-group",
            "com.apple.DevToolsBoth.pkg-group",
            "com.apple.DevToolsNonRelocatableShared.pkg-group"
        );
        PackageIdentifier = "com.apple.pkg.DeveloperToolsCLI";
        PackageVersion = "4.5.0.0.1.1249367152";
        PathACLs =     {
            Library = "!#acl 1\\ngroup:ABCDEFAB-CDEF-ABCD-EFAB-CDEF0000000C:everyone:12:deny:delete\\n";
            System = "!#acl 1\\ngroup:ABCDEFAB-CDEF-ABCD-EFAB-CDEF0000000C:everyone:12:deny:delete\\n";
        };
    }
    

    How to write to a CSV line by line?

    You could just write to the file as you would write any normal file.

    with open('csvfile.csv','wb') as file:
        for l in text:
            file.write(l)
            file.write('\n')
    

    If just in case, it is a list of lists, you could directly use built-in csv module

    import csv
    
    with open("csvfile.csv", "wb") as file:
        writer = csv.writer(file)
        writer.writerows(text)
    

    How can I change the value of the elements in a vector?

    You might want to consider using some algorithms instead:

    // read in the data:
    std::copy(std::istream_iterator<double>(input), 
              std::istream_iterator<double>(),
              std::back_inserter(v));
    
    sum = std::accumulate(v.begin(), v.end(), 0);
    average = sum / v.size();
    

    You can modify the values with std::transform, though until we get lambda expressions (C++0x) it may be more trouble than it's worth:

    class difference { 
        double base;
    public:
        difference(double b) : base(b) {}
        double operator()(double v) { return v-base; }
    };
    
    std::transform(v.begin(), v.end(), v.begin(), difference(average));
    

    phpMyAdmin mbstring error

    Solved it.

    I tried all of the solutions above but it still did not work. I'm currently using WAMP to launch the mysql server. When I tried to open the "php.ini" file with the WAMP panel, it said that it did not exist and asked me to create a new "php.ini" in the location, "C:\wamp\bin\apache\apache2.4.17\bin". Once I created this new "php.ini" file, I located the existing "php.ini" file which was in the path "C:\wamp\bin\php\php5.6.15", and cloned it. I then pasted the clone in the previous path where it had asked me to create the "php.ini" file.

    Hope this helped.

    Spring Data JPA find by embedded object property

    If you are using BookId as an combined primary key, then remember to change your interface from:

    public interface QueuedBookRepo extends JpaRepository<QueuedBook, Long> {
    

    to:

    public interface QueuedBookRepo extends JpaRepository<QueuedBook, BookId> {
    

    And change the annotation @Embedded to @EmbeddedId, in your QueuedBook class like this:

    public class QueuedBook implements Serializable {
    
    @EmbeddedId
    @NotNull
    private BookId bookId;
    
    ...
    

    How do I remove all non alphanumeric characters from a string except dash?

    I´ve made a different solution, by eliminating the Control characters, which was my original problem.

    It is better than putting in a list all the "special but good" chars

    char[] arr = str.Where(c => !char.IsControl(c)).ToArray();    
    str = new string(arr);
    

    it´s simpler, so I think it´s better !

    Postgresql SQL: How check boolean field with null and True,False Value?

    Resurrecting this to post the DISTINCT FROM option, which has been around since Postgres 8. The approach is similar to Brad Dre's answer. In your case, your select would be something like

    SELECT *
      FROM table_name
     WHERE boolean_column IS DISTINCT FROM TRUE
    

    What's the best way to trim std::string?

    This version trims internal whitespace and non-alphanumerics:

    static inline std::string &trimAll(std::string &s)
    {   
        if(s.size() == 0)
        {
            return s;
        }
    
        int val = 0;
        for (int cur = 0; cur < s.size(); cur++)
        {
            if(s[cur] != ' ' && std::isalnum(s[cur]))
            {
                s[val] = s[cur];
                val++;
            }
        }
        s.resize(val);
        return s;
    }