Programs & Examples On #Ant

Apache Ant (formerly Jakarta Ant) is a declarative, XML-based build tool created originally for Java projects. It provides a rich set of standard tasks for performing most common build operations, such as compiling Java source, building archives and running tests. Ant's functionality can be extended through custom tasks and macros.

Server certificate verification failed: issuer is not trusted

from cmd run: SVN List URL you will be provided with 3 options (r)eject, (a)ccept, (p)ermanently. enter p. This resolved issue for me

How can I install Apache Ant on Mac OS X?

If you're a homebrew user instead of macports, homebrew has an ant recipe.

brew install ant

Use Ant for running program with command line arguments

The only effective mechanism for passing parameters into a build is to use Java properties:

ant -Done=1 -Dtwo=2

The following example demonstrates how you can check and ensure the expected parameters have been passed into the script

<project name="check" default="build">

    <condition property="params.set">
        <and>
            <isset property="one"/>
            <isset property="two"/>
        </and>
    </condition>

    <target name="check">
        <fail unless="params.set">
        Must specify the parameters: one, two
        </fail>
    </target>

    <target name="build" depends="check">
        <echo>
        one = ${one}
        two = ${two}
        </echo>
    </target>

</project>

This compilation unit is not on the build path of a Java project

Since you imported the project as a General Project, it does not have the java nature and that is the problem.

Add the below lines in the .project file of your workspace and refresh.

<natures>
      <nature>org.eclipse.jdt.core.javanature</nature>
</natures>

ant warning: "'includeantruntime' was not set"

i faced this same, i check in in program and feature. there was an update has install for jdk1.8 which is not compatible with my old setting(jdk1.6.0) for ant in eclipse. I install that update. right now, my ant project is build success.

Try it, hope this will be helpful.

Why does ANT tell me that JAVA_HOME is wrong when it is not?

I faced this problem when building my project with Jenkins. First, it could not find ant.bat, which was fixed by adding the path to ant.bat to the system environment variable path. Then ant could not find the jdk directory. This was fixed by right-clicking on my computer > properties > advanced > environment variables and creating a new environment variable called JAVA_HOME and assigning it a value of C:\Program Files\Java\jdk1.7.0_21. Don't create this environment variable in User Variables. Create it under System Variables only.
In both cases, I had to restart the system.

Including external jar-files in a new jar-file build with Ant

As Cheesle said, you can unpack and your library Jars and re-jar them all with the following modification.

    <jar destfile="${jar.file}"  
        basedir="${build.dir}"  
        manifest="${manifest.file}"> 
        <fileset dir="${classes.dir}" includes="**/*.class" /> 
        <zipgroupfileset dir="${lib.dir}" includes="**/*.jar" /> 
    </jar> 

Jar files are really just zip files with a manifest file embedded. You can extract and repackage the dependency Jars into your application's Jar file.

http://ant.apache.org/manual/Tasks/zip.html "The Zip task also supports the merging of multiple zip files into the zip file. This is possible through either the src attribute of any nested filesets or by using the special nested fileset zipgroupfileset."

Do pay attention to the licenses involved with your dependency libaries. Linking externally to a library and including the library in your application are very different things legally.

EDIT 1: Darn my slow typing. Grodriguez beat me to it. :)

EDIT 2: If you decide you can't include your dependencies into your application then you have to specify them in your Jar's classpath either at the command line at startup or via the Manifest file. There's a nice command in ANT to handle the special formatting of the classpath in a Manifest file for you.

<manifestclasspath property="manifest.classpath" jarfile="${jar.file}">
    <classpath location="${lib.dir}" />
</manifestclasspath>

 <manifest file="${manifest.file}" >      
        <attribute name="built-by" value="${user.name}" />      
        <attribute name="Main-Class" value="${main.class}" />    
        <attribute name="Class-Path" value="${manifest.classpath}" />
 </manifest>

Ant task to run an Ant target only if a file exists?

Available and Condition

<target name="check-abc">
    <available file="abc.txt" property="abc.present"/>
</target>

<target name="do-if-abc" depends="check-abc" if="abc.present">
    ...
</target> 

JUnit: how to avoid "no runnable methods" in test utils classes

Be careful when using an IDE's code-completion to add the import for @Test.

It has to be import org.junit.Test and not import org.testng.annotations.Test, for example. If you do the latter, you'll get the "no runnable methods" error.

adding comment in .properties files

According to the documentation of the PropertyFile task, you can append the generated properties to an existing file. You could have a properties file with just the comment line, and have the Ant task append the generated properties.

Ant if else condition?

You can also do this with ant contrib's if task.

<if>
    <equals arg1="${condition}" arg2="true"/>
    <then>
        <copy file="${some.dir}/file" todir="${another.dir}"/>
    </then>
    <elseif>
        <equals arg1="${condition}" arg2="false"/>
        <then>
            <copy file="${some.dir}/differentFile" todir="${another.dir}"/>
        </then>
    </elseif>
    <else>
        <echo message="Condition was neither true nor false"/>
    </else>
</if>

Ant build failed: "Target "build..xml" does not exist"

since your ant file's name is build.xml, you should just type ant without ant build.xml. that is: > ant [enter]

Why is Ant giving me a Unsupported major.minor version error

The runtime jre was set to jre 6 instead of jre 7 in the build configuration window.

Using FileUtils in eclipse

Now selenium supports following code:

FileHandler.copy(src, dest);

How to put a jar in classpath in Eclipse?

As of rev 17 of the Android Developer Tools, the correct way to add a library jar when.using the tools and Eclipse is to create a directory called libs on the same level as your src and assets directories and then drop the jar in there. Nothing else.required, the tools take care of all the rest for you automatically.

Any way to generate ant build.xml file automatically from Eclipse?

I've had the same problem, our work environment is based on Eclipse Java projects, and we needed to build automatically an ANT file so that we could use a continuous integration server (Jenkins, in our case).

We rolled out our own Eclipse Java to Ant tool, which is now available on GitHub:

ant-build-for-java

To use it, call:

java -jar ant-build-for-java.jar <folder with repositories> [<.userlibraries file>]

The first argument is the folder with the repositories. It will search the folder recursively for any .project file. The tool will create a build.xml in the given folder.

Optionally, the second argument can be an exported .userlibraries file, from Eclipse, needed when any of the projects use Eclipse user libraries. The tool was tested only with user libraries using relative paths, it's how we use them in our repo. This implies that JARs and other archives needed by projects are inside an Eclipse project, and referenced from there.

The tool only supports dependencies from other Eclipse projects and from Eclipse user libraries.

How to create a signed APK file using Cordova command line interface?

Build cordova release APK file in cmd.

KEY STORE FILE PATH: keystore file path (F:/cordova/myApp/xxxxx.jks)

KEY STORE PASSWORD: xxxxx

KEY STORE ALIAS: xxxxx

KEY STORE ALIAS PASSWORD: xxxxx

PATH OF zipalign.exe: zipalign.exe file path (C:\Users\xxxx\AppData\Local\Android\sdk\build-tools\25.0.2\zipalign)

ANDROID UNSIGNED APK NAME: android-release-unsigned.apk

ANDROID RELEASE APK NAME: android-release.apk

Run below steps in cmd (run as administrator)

  1. cordova build --release android
  2. go to android-release-unsigned.apk file location (PROJECT\platforms\android\build\outputs\apk)
  3. jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore <KEY STORE FILE PATH> <ANDROID UNSIGNED APK NAME> <KEY STORE ALIAS>
  4. <PATH OF zipalign.exe> -v 4 <ANDROID UNSIGNED APK NAME> <ANDROID RELEASE APK NAME>

NoClassDefFoundError - Eclipse and Android

I have encountered the same issue. The reason was that the library that I was trying to use had been compiled with a standard JDK 7.

I recompiled it with the -source 1.6 -target 1.6 options and it worked fine.

Replacing characters in Ant property

In case you want a solution that does use Ant built-ins only, consider this:

<target name="replace-spaces">
    <property name="propA" value="This is a value" />
    <echo message="${propA}" file="some.tmp.file" />
    <loadfile property="propB" srcFile="some.tmp.file">
        <filterchain>
            <tokenfilter>
                <replaceregex pattern=" " replace="_" flags="g"/>
            </tokenfilter>
        </filterchain>
    </loadfile>
    <echo message="$${propB} = &quot;${propB}&quot;" />
</target>

Output is ${propB} = "This_is_a_value"

How do I change the JAVA_HOME for ant?

You will need to change JAVA_HOME path to the Java SDK directory instead of the Java RE directory. In Windows you can do this using the set command in a command prompt.

e.g.

set JAVA_HOME="C:\Program Files\Java\jdk1.6.0_14"

Differences between Ant and Maven

Maven also houses a large repository of commonly used open source projects. During the build Maven can download these dependencies for you (as well as your dependencies dependencies :)) to make this part of building a project a little more manageable.

Setting the target version of Java in ant javac

To find the version of the java in the classfiles I used:

javap -verbose <classname>

which announces the version at the start as

minor version: 0
major version: 49

which corresponds to Java 1.5

How to change JAVA.HOME for Eclipse/ANT

For me, ant apparently refuses to listen to any configuration for eclipse default, project JDK, and the suggestion of "Ant Home Entries" just didn't have traction - there was nothing there referring to JDK.

However, this works:

Menu "Run" -> "External Tools" -> "External Tools Configuration".
  Goto the node "Ant build", choose the ant buildfile in question.
     Choose tab "JRE".
        Select e.g. "Run in same JRE as workspace", or whatever you want.

How do I check out an SVN project into Eclipse as a Java project?

If it wasn't checked in as a Java Project, you can add the java nature as shown here.

Ant is using wrong java version

In Eclipse:

  • Right click on your build.xml

  • click "Run As", click on "External Tool Configurations..."

  • Select tab JRE. Select the JRE you are using.

Re-run the task, it should be fine now.

Why use Gradle instead of Ant or Maven?

It's also much easier to manage native builds. Ant and Maven are effectively Java-only. Some plugins exist for Maven that try to handle some native projects, but they don't do an effective job. Ant tasks can be written that compile native projects, but they are too complex and awkward.

We do Java with JNI and lots of other native bits. Gradle simplified our Ant mess considerably. When we started to introduce dependency management to the native projects it was messy. We got Maven to do it, but the equivalent Gradle code was a tiny fraction of what was needed in Maven, and people could read it and understand it without becoming Maven gurus.

ant build.xml file doesn't exist

If you couldn't find the build.xml file in your project then you have to build it to be able to debug it and get your .apk

you can use this command-line to build:

android update project -p "project full path"

where "Project full path" -- Give your full path of your project location

after this you will find the build.xml then you can debug it.

Error executing command 'ant' on Mac OS X 10.9 Mavericks when building for Android with PhoneGap/Cordova

it don't needed port and brew! because you have android sdk package.

.1 edit your .bash_profile

export ANT_HOME="[your android_sdk_path/eclipse/plugins/org.apache.ant_1.8.3.v201301120609]" 

// its only my org.apache.ant version, check your org.apache.ant version

export PATH=$PATH:$ANT_HOME/bin

.2 make ant command that can executed

chmod 770 [your ANT_HOME/bin/ant]

.3 test if you see below message. that's success!

command line execute: ant

Buildfile: build.xml does not exist!

Build failed

Ant error when trying to build file, can't find tools.jar?

Just set your java_home property with java home (eg:C:\Program Files\Java\jdk1.7.0_25) directory. Close command prompt and reopen it. Then error relating to tools.jar will be solved. For the second one("build.xml not found ") you should have to ensure your command line also at the directory where your build.xml file resides.

Ant: How to execute a command for each file in directory?

You can use the ant-contrib task "for" to iterate on the list of files separate by any delimeter, default delimeter is ",".

Following is the sample file which shows this:

<project name="modify-files" default="main" basedir=".">
    <taskdef resource="net/sf/antcontrib/antlib.xml"/>
    <target name="main">
        <for list="FileA,FileB,FileC,FileD,FileE" param="file">
          <sequential>
            <echo>Updating file: @{file}</echo>
            <!-- Do something with file here -->
          </sequential>
        </for>                         
    </target>
</project>

"Unable to locate tools.jar" when running ant

Make sure you use the root folder of the JDK. Don't add "\lib" to the end of the path, where tools.jar is physically located. It took me an hour to figure that one out. Also, this post will help show you where Ant is looking for tools.jar:

Why does ANT tell me that JAVA_HOME is wrong when it is not?

‘ant’ is not recognized as an internal or external command

create a script including the following; (replace the ant and jdk paths with whatever is correct for your machine)

set  PATH=%BASEPATH%
set ANT_HOME=c:\tools\apache-ant-1.9-bin
set JAVA_HOME=c:\tools\jdk7x64
set PATH=%ANT_HOME%\bin;%JAVA_HOME%\bin;%PATH%

run it in shell.

How to exclude a directory from ant fileset, based on directories contents

it works for me with a jar target:

<jar jarfile="${server.jar}" basedir="${classes.dir}" excludes="**/client/">
  <manifest>
    <attribute name="Main-Class" value="${mainServer.class}" />
  </manifest>
</jar>

this code include all files in "classes.dir" but exclude the directory "client" from the jar.

How to execute Ant build in command line

Go to the Ant website and download. This way, you have a copy of Ant outside of Eclipse. I recommend to put it under the C:\ant directory. This way, it doesn't have any spaces in the directory names. In your System Control Panel, set the Environment Variable ANT_HOME to this directory, then pre-pend to the System PATHvariable, %ANT_HOME%\bin. This way, you don't have to put in the whole directory name.

Assuming you did the above, try this:

C:\> cd \Silk4J\Automation\iControlSilk4J
C:\Silk4J\Automation\iControlSilk4J> ant -d build

This will do several things:

  • It will eliminate the possibility that the problem is with Eclipe's version of Ant.
  • It is way easier to type
  • Since you're executing the build.xml in the directory where it exists, you don't end up with the possibility that your Ant build can't locate a particular directory.

The -d will print out a lot of output, so you might want to capture it, or set your terminal buffer to something like 99999, and run cls first to clear out the buffer. This way, you'll capture all of the output from the beginning in the terminal buffer.

Let's see how Ant should be executing. You didn't specify any targets to execute, so Ant should be taking the default build target. Here it is:

<target depends="build-subprojects,build-project" name="build"/>

The build target does nothing itself. However, it depends upon two other targets, so these will be called first:

The first target is build-subprojects:

<target name="build-subprojects"/>

This does nothing at all. It doesn't even have a dependency.

The next target specified is build-project does have code:

<target depends="init" name="build-project">

This target does contain tasks, and some dependent targets. Before build-project executes, it will first run the init target:

<target name="init">
    <mkdir dir="bin"/>
    <copy includeemptydirs="false" todir="bin">
        <fileset dir="src">
            <exclude name="**/*.java"/>
        </fileset>
    </copy>
</target>

This target creates a directory called bin, then copies all files under the src tree with the suffix *.java over to the bin directory. The includeemptydirs mean that directories without non-java code will not be created.

Ant uses a scheme to do minimal work. For example, if the bin directory is created, the <mkdir/> task is not executed. Also, if a file was previously copied, or there are no non-Java files in your src directory tree, the <copy/> task won't run. However, the init target will still be executed.

Next, we go back to our previous build-project target:

<target depends="init" name="build-project">
    <echo message="${ant.project.name}: ${ant.file}"/>
    <javac debug="true" debuglevel="${debuglevel}" destdir="bin" source="${source}" target="${target}">
        <src path="src"/>
        <classpath refid="iControlSilk4J.classpath"/>
    </javac>
</target>

Look at this line:

<echo message="${ant.project.name}: ${ant.file}"/>

That should have always executed. Did your output print:

[echo] iControlSilk4J: C:\Silk4J\Automation\iControlSilk4J\build.xml

Maybe you didn't realize that was from your build.

After that, it runs the <javac/> task. That is, if there's any files to actually compile. Again, Ant tries to avoid work it doesn't have to do. If all of the *.java files have previously been compiled, the <javac/> task won't execute.

And, that's the end of the build. Your build might not have done anything simply because there was nothing to do. You can try running the clean task, and then build:

C:\Silk4J\Automation\iControlSilk4J> ant -d clean build

However, Ant usually prints the target being executed. You should have seen this:

init:

build-subprojects:

build-projects:

    [echo] iControlSilk4J: C:\Silk4J\Automation\iControlSilk4J\build.xml

build:

Build Successful

Note that the targets are all printed out in order they're executed, and the tasks are printed out as they are executed. However, if there's nothing to compile, or nothing to copy, then you won't see these tasks being executed. Does this look like your output? If so, it could be there's nothing to do.

  • If the bin directory already exists, <mkdir/> isn't going to execute.
  • If there are no non-Java files in src, or they have already been copied into bin, the <copy/> task won't execute.
  • If there are no Java file in your src directory, or they have already been compiled, the <java/> task won't run.

If you look at the output from the -d debug, you'll see Ant looking at a task, then explaining why a particular task wasn't executed. Plus, the debug option will explain how Ant decides what tasks to execute.

See if that helps.

JAVA_HOME does not point to the JDK

Under Jenkins it complains like :

/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.191.b12-1.el7_6.x86_64/ doesn’t look like a JDK directory

Reason : Unable to found any Dev Kit for JDK.

Solution:

Please make sure to install openjdk-devel package as well along with your JDK-1.8* version and reexport with : # source ~/.bash_profile

Unable to locate tools.jar

I was also facing the same error. This was removed after setting Java_Home path to C:\Program Files\Java\jdk1.8.0_121. Please ensure bin is not included in the path and no slash is there after jdk1.8.0_121 after you have defined %JAVA_HOME%\bin in the system path variable.

"Line contains NULL byte" in CSV reader (Python)

pandas.read_csv now handles the different UTF encoding when reading/writing and therefore can deal directly with null bytes

data = pd.read_csv(file, encoding='utf-16')

see https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html

How to put a link on a button with bootstrap?

The easiest solution is the first one of your examples:

<a href="#link" class="btn btn-info" role="button">Link Button</a>

The reason it's not working for you is most likely, as you say, a problem in the theme you're using. There is no reason to resort to bloated extra markup or inline Javascript for this.

How can I search sub-folders using glob.glob module?

To find files in immediate subdirectories:

configfiles = glob.glob(r'C:\Users\sam\Desktop\*\*.txt')

For a recursive version that traverse all subdirectories, you could use ** and pass recursive=True since Python 3.5:

configfiles = glob.glob(r'C:\Users\sam\Desktop\**\*.txt', recursive=True)

Both function calls return lists. You could use glob.iglob() to return paths one by one. Or use pathlib:

from pathlib import Path

path = Path(r'C:\Users\sam\Desktop')
txt_files_only_subdirs = path.glob('*/*.txt')
txt_files_all_recursively = path.rglob('*.txt') # including the current dir

Both methods return iterators (you can get paths one by one).

How to write the Fibonacci Sequence?

These all look a bit more complicated than they need to be. My code is very simple and fast:

def fibonacci(x):

    List = []
    f = 1
    List.append(f)
    List.append(f) #because the fibonacci sequence has two 1's at first
    while f<=x:
        f = List[-1] + List[-2]   #says that f = the sum of the last two f's in the series
        List.append(f)
    else:
        List.remove(List[-1])  #because the code lists the fibonacci number one past x. Not necessary, but defines the code better
        for i in range(0, len(List)):
        print List[i]  #prints it in series form instead of list form. Also not necessary

How to validate inputs dynamically created using ng-repeat, ng-show (angular)

It is too late but might be it can help anyone

  1. Create unique name for every control
  2. Validate by using fromname[uniquname].$error

Sample code:

<input 
    ng-model="r.QTY" 
    class="span1" 
    name="QTY{{$index}}" 
    ng-pattern="/^[\d]*\.?[\d]*$/" required/>
<div ng-messages="formName['QTY' +$index].$error"
     ng-show="formName['QTY' +$index].$dirty || formName.$submitted">
   <div ng-message="required" class='error'>Required</div>
   <div ng-message="pattern" class='error'>Invalid Pattern</div>
</div>

See working demo here

How to uninstall a windows service and delete its files without rebooting

Both Jonathan and Charles are right... you've got to stop the service first, then uninstall/reinstall. Combining their two answers makes the perfect batch file or PowerShell script.

I will make mention of a caution learned the hard way -- Windows 2000 Server (possibly the client OS as well) will require a reboot before the reinstall no matter what. There must be a registry key that is not fully cleared until the box is rebooted. Windows Server 2003, Windows XP and later OS versions do not suffer that pain.

How do I use the new computeIfAbsent function?

Recently I was playing with this method too. I wrote a memoized algorithm to calcualte Fibonacci numbers which could serve as another illustration on how to use the method.

We can start by defining a map and putting the values in it for the base cases, namely, fibonnaci(0) and fibonacci(1):

private static Map<Integer,Long> memo = new HashMap<>();
static {
   memo.put(0,0L); //fibonacci(0)
   memo.put(1,1L); //fibonacci(1)
}

And for the inductive step all we have to do is redefine our Fibonacci function as follows:

public static long fibonacci(int x) {
   return memo.computeIfAbsent(x, n -> fibonacci(n-2) + fibonacci(n-1));
}

As you can see, the method computeIfAbsent will use the provided lambda expression to calculate the Fibonacci number when the number is not present in the map. This represents a significant improvement over the traditional, tree recursive algorithm.

Bash integer comparison

I know this has been answered, but here's mine just because I think case is an under-appreciated tool. (Maybe because people think it is slow, but it's at least as fast as an if, sometimes faster.)

case "$1" in
    0|1) xinput set-prop 12 "Device Enabled" $1 ;;
      *) echo "This script requires a 1 or 0 as first parameter." ;;
esac

difference between throw and throw new Exception()

None of the answers here show the difference, which could be helpful for folks struggling to understand the difference. Consider this sample code:

using System;
using System.Collections.Generic;

namespace ExceptionDemo
{
   class Program
   {
      static void Main(string[] args)
      {
         void fail()
         {
            (null as string).Trim();
         }

         void bareThrow()
         {
            try
            {
               fail();
            }
            catch (Exception e)
            {
               throw;
            }
         }

         void rethrow()
         {
            try
            {
               fail();
            }
            catch (Exception e)
            {
               throw e;
            }
         }

         void innerThrow()
         {
            try
            {
               fail();
            }
            catch (Exception e)
            {
               throw new Exception("outer", e);
            }
         }

         var cases = new Dictionary<string, Action>()
         {
            { "Bare Throw:", bareThrow },
            { "Rethrow", rethrow },
            { "Inner Throw", innerThrow }
         };

         foreach (var c in cases)
         {
            Console.WriteLine(c.Key);
            Console.WriteLine(new string('-', 40));
            try
            {
               c.Value();
            } catch (Exception e)
            {
               Console.WriteLine(e.ToString());
            }
         }
      }
   }
}

Which generates the following output:

Bare Throw:
----------------------------------------
System.NullReferenceException: Object reference not set to an instance of an object.
   at ExceptionDemo.Program.<Main>g__fail|0_0() in C:\...\ExceptionDemo\Program.cs:line 12
   at ExceptionDemo.Program.<>c.<Main>g__bareThrow|0_1() in C:\...\ExceptionDemo\Program.cs:line 19
   at ExceptionDemo.Program.Main(String[] args) in C:\...\ExceptionDemo\Program.cs:line 64

Rethrow
----------------------------------------
System.NullReferenceException: Object reference not set to an instance of an object.
   at ExceptionDemo.Program.<>c.<Main>g__rethrow|0_2() in C:\...\ExceptionDemo\Program.cs:line 35
   at ExceptionDemo.Program.Main(String[] args) in C:\...\ExceptionDemo\Program.cs:line 64

Inner Throw
----------------------------------------
System.Exception: outer ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at ExceptionDemo.Program.<Main>g__fail|0_0() in C:\...\ExceptionDemo\Program.cs:line 12
   at ExceptionDemo.Program.<>c.<Main>g__innerThrow|0_3() in C:\...\ExceptionDemo\Program.cs:line 43
   --- End of inner exception stack trace ---
   at ExceptionDemo.Program.<>c.<Main>g__innerThrow|0_3() in C:\...\ExceptionDemo\Program.cs:line 47
   at ExceptionDemo.Program.Main(String[] args) in C:\...\ExceptionDemo\Program.cs:line 64

The bare throw, as indicated in the previous answers, clearly shows both the original line of code that failed (line 12) as well as the two other points active in the call stack when the exception occurred (lines 19 and 64).

The output of the re-throw case shows why it's a problem. When the exception is rethrown like this the exception won't include the original stack information. Note that only the throw e (line 35) and outermost call stack point (line 64) are included. It would be difficult to track down the fail() method as the source of the problem if you throw exceptions this way.

The last case (innerThrow) is most elaborate and includes more information than either of the above. Since we're instantiating a new exception we get the chance to add contextual information (the "outer" message, here but we can also add to the .Data dictionary on the new exception) as well as preserving all of the information in the original exception (including help links, data dictionary, etc.).

NoClassDefFoundError for code in an Java library on Android

Solutions:

  1. List item
  2. Check Exports Order
  3. Enable Multi Dex
  4. Check api level of views in layout. I faced same problem with searchView. I have check api level while adding searchview but added implements SearchView.OnQueryTextListener to class file.

What is so bad about singletons?

Recent article on this subject by Chris Reath at Coding Without Comments.

Note: Coding Without Comments is no longer valid. However, The article being linked to has been cloned by another user.

http://geekswithblogs.net/AngelEyes/archive/2013/09/08/singleton-i-love-you-but-youre-bringing-me-down-re-uploaded.aspx

php is null or empty?

PHP 7 isset() vs empty() vs is_null()

enter image description here

Min width in window resizing

You can set min-width property of CSS for body tag. Since this property is not supported by IE6, you can write like:

body{
   min-width:1000px;        /* Suppose you want minimum width of 1000px */
   width: auto !important;  /* Firefox will set width as auto */
   width:1000px;            /* As IE6 ignores !important it will set width as 1000px; */
}

Or:

body{
   min-width:1000px; // Suppose you want minimum width of 1000px
   _width: expression( document.body.clientWidth > 1000 ? "1000px" : "auto" ); /* sets max-width for IE6 */
}

How to do while loops with multiple conditions

while not condition1 or not condition2 or val == -1:

But there was nothing wrong with your original of using an if inside of a while True.

Java 8: Difference between two LocalDateTime in multiple units

I found the best way to do this is with ChronoUnit.

long minutes = ChronoUnit.MINUTES.between(fromDate, toDate);
long hours = ChronoUnit.HOURS.between(fromDate, toDate);

Additional documentation is here: https://docs.oracle.com/javase/tutorial/datetime/iso/period.html

Is it possible to use argsort in descending order?

With your example:

avgDists = np.array([1, 8, 6, 9, 4])

Obtain indexes of n maximal values:

ids = np.argpartition(avgDists, -n)[-n:]

Sort them in descending order:

ids = ids[np.argsort(avgDists[ids])[::-1]]

Obtain results (for n=4):

>>> avgDists[ids]
array([9, 8, 6, 4])

What is the purpose of mvnw and mvnw.cmd files?

Command mvnw uses Maven that is by default downloaded to ~/.m2/wrapper on the first use.

URL with Maven is specified in each project at .mvn/wrapper/maven-wrapper.properties:

distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip

To update or change Maven version invoke the following (remember about --non-recursive for multi-module projects):

./mvnw io.takari:maven:wrapper -Dmaven=3.3.9 

or just modify .mvn/wrapper/maven-wrapper.properties manually.

To generate wrapper from scratch using Maven (you need to have it already in PATH run:

mvn io.takari:maven:wrapper -Dmaven=3.3.9 

Should I test private methods or only public ones?

The answer to "Should I test private methods?" is ".......sometimes". Typically you should be testing against the interface of your classes.

  • One of the reasons is because you do not need double coverage for a feature.
  • Another reason is that if you change private methods, you will have to update each test for them, even if the interface of your object hasn't changed at all.

Here is an example:

class Thing
  def some_string
    one + two
  end

  private 

  def one
    'aaaa'
  end

  def two
    'bbbb'
  end

end


class RefactoredThing
def some_string
    one + one_a + two + two_b
  end

  private 

  def one
    'aa'
  end

  def one_a
    'aa'
  end

  def two
    'bb'
  end

  def two_b
    'bb'
  end
end

In RefactoredThing you now have 5 tests, 2 of which you had to update for refactoring, but your object's functionality really hasn't changed. So let's say that things are more complex than that and you have some method that defines the order of the output such as:

def some_string_positioner
  if some case
  elsif other case
  elsif other case
  elsif other case
  else one more case
  end
end

This shouldn't be run by an outside user, but your encapsulating class may be to heavy to run that much logic through it over and over again. In this case maybe you would rather extract this into a seperate class, give that class an interface and test against it.

And finally, let's say that your main object is super heavy, and the method is quite small and you really need to ensure that the output is correct. You are thinking, "I have to test this private method!". Have you that maybe you can make your object lighter by passing in some of the heavy work as an initialization parameter? Then you can pass something lighter in and test against that.

Using reflection in Java to create a new instance with the reference variable type set to the new instance class name?

This line seems to sum up the crux of your problem:

The issue with this is that now you can't call any new methods (only overrides) on the implementing class, as your object reference variable has the interface type.

You are pretty stuck in your current implementation, as not only do you have to attempt a cast, you also need the definition of the method(s) that you want to call on this subclass. I see two options:

1. As stated elsewhere, you cannot use the String representation of the Class name to cast your reflected instance to a known type. You can, however, use a String equals() test to determine whether your class is of the type that you want, and then perform a hard-coded cast:

try {
   String className = "com.path.to.ImplementationType";// really passed in from config
   Class c = Class.forName(className);
   InterfaceType interfaceType = (InterfaceType)c.newInstance();
   if (className.equals("com.path.to.ImplementationType") {
      ((ImplementationType)interfaceType).doSomethingOnlyICanDo();
   } 
} catch (Exception e) {
   e.printStackTrace();
}

This looks pretty ugly, and it ruins the nice config-driven process that you have. I dont suggest you do this, it is just an example.

2. Another option you have is to extend your reflection from just Class/Object creation to include Method reflection. If you can create the Class from a String passed in from a config file, you can also pass in a method name from that config file and, via reflection, get an instance of the Method itself from your Class object. You can then call invoke(http://java.sun.com/javase/6/docs/api/java/lang/reflect/Method.html#invoke(java.lang.Object, java.lang.Object...)) on the Method, passing in the instance of your class that you created. I think this will help you get what you are after.

Here is some code to serve as an example. Note that I have taken the liberty of hard coding the params for the methods. You could specify them in a config as well, and would need to reflect on their class names to define their Class obejcts and instances.

public class Foo {

    public void printAMessage() {
    System.out.println(toString()+":a message");
    }
    public void printAnotherMessage(String theString) {
        System.out.println(toString()+":another message:" + theString);
    }

    public static void main(String[] args) {
        Class c = null;
        try {
            c = Class.forName("Foo");
            Method method1 = c.getDeclaredMethod("printAMessage", new Class[]{});
            Method method2 = c.getDeclaredMethod("printAnotherMessage", new Class[]{String.class});
            Object o = c.newInstance();
            System.out.println("this is my instance:" + o.toString());
            method1.invoke(o);
            method2.invoke(o, "this is my message, from a config file, of course");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException nsme){
            nsme.printStackTrace();
        } catch (IllegalAccessException iae) {
            iae.printStackTrace();
        } catch (InstantiationException ie) {
            ie.printStackTrace();
        } catch (InvocationTargetException ite) {
            ite.printStackTrace();
        }
    }
}

and my output:

this is my instance:Foo@e0cf70
Foo@e0cf70:a message
Foo@e0cf70:another message:this is my message, from a config file, of course

How to "log in" to a website using Python's Requests module?

If the information you want is on the page you are directed to immediately after login...

Lets call your ck variable payload instead, like in the python-requests docs:

payload = {'inUserName': 'USERNAME/EMAIL', 'inUserPass': 'PASSWORD'}
url = 'http://www.locationary.com/home/index2.jsp'
requests.post(url, data=payload)

Otherwise...

See https://stackoverflow.com/a/17633072/111362 below.

How to Implement DOM Data Binding in JavaScript

Late to the party, especially since I've written 2 libs related months/years ago, I'll mention them later, but still looks relevant to me. To make it really short spoiler, the technologies of my choice are:

  • Proxy for observation of model
  • MutationObserver for the tracking changes of DOM (for binding reasons, not value changes)
  • value changes (view to model flow) are handled via regular addEventListener handlers

IMHO, in addition to the OP, it is important that data binding implementation will:

  • handle different app lifecycle cases (HTML first, then JS, JS first then HTML, dynamic attributes change etc)
  • allow deep binding of model, so that one may bind user.address.block
  • arrays as a model should be supported correctly (shift, splice and alike)
  • handle ShadowDOM
  • attempt to be as easy for technology replacement as possible, thus any templating sub-languages are a non-future-changes-friendly approach since it's too heavily coupled with framework

Taking all those into consideration, in my opinion makes it impossible to just throw few dozens of JS lines. I've tried to do it as a pattern rather than lib - didn't work for me.

Next, having Object.observe is removed, and yet given that observation of model is crucial part - this whole part MUST be concern-separated to another lib. Now to the point of principals of how I took this problem - exactly as OP asked:

Model (JS part)

My take for model observation is Proxy, it is the only sane way to make it work, IMHO. Fully featured observer deserves it's own library, so I've developed object-observer library for that sole purpose.

The model/s should be registered via some dedicated API, that's the point where POJOs turn into Observables, can't see any shortcut here. The DOM elements which are considered to be a bound views (see below), are updated with the values of the model/s at first and then upon each data change.

Views (HTML part)

IMHO, the cleanest way to express the binding, is via attributes. Many did this before and many will do after, so no news here, this is just a right way to do that. In my case I've gone with the following syntax: <span data-tie="modelKey:path.to.data => targerProperty"></span>, but this is less important. What is important to me, no complex scripting syntax in the HTML - this is wrong, again, IMHO.

All the elements designated to be a bound views shall be collected at first. It looks inevitable to me from a performance side to manage some internal mapping between the models and the views, seems a right case where memory + some management should be sacrificed to save runtime lookups and updates.

The views are updated at first from the model, if available and upon later model changes, as we said. More yet, the whole DOM should be observed by means of MutationObserver in order to react (bind/unbind) on the dynamically added/remove/changed elements. Furthermore, all this, should be replicated into the ShadowDOM (open one, of course) in order to not leave unbound black holes.

The list of specifics may go further indeed, but those are in my opinion the main principals that would made data binding implemented with a good balance of feature completeness from one and sane simplicity from the other side.

And thus, in addition to the object-observer mentioned above, I've written indeed also data-tier library, that implements data binding along the above mentioned concepts.

I want my android application to be only run in portrait mode?

In the manifest, set this for all your activities:

<activity android:name=".YourActivity"
    android:configChanges="orientation"
    android:screenOrientation="portrait"/>

Let me explain:

  • With android:configChanges="orientation" you tell Android that you will be responsible of the changes of orientation.
  • android:screenOrientation="portrait" you set the default orientation mode.

How to grep Git commit diffs or contents for a certain word?

After a lot of experimentation, I can recommend the following, which shows commits that introduce or remove lines containing a given regexp, and displays the text changes in each, with colours showing words added and removed.

git log --pickaxe-regex -p --color-words -S "<regexp to search for>"

Takes a while to run though... ;-)

How to use GROUP_CONCAT in a CONCAT in MySQL

 SELECT id, GROUP_CONCAT(CONCAT_WS(':', Name, CAST(Value AS CHAR(7))) SEPARATOR ',') AS result 
    FROM test GROUP BY id

you must use cast or convert, otherwise will be return BLOB

result is

id         Column
1          A:4,A:5,B:8
2          C:9

you have to handle result once again by program such as python or java

Reverse Singly Linked List Java

public void reverse() {
    Node prev = null; Node current = head; Node next = current.next;
    while(current.next != null) {
        current.next = prev;
        prev = current;
        current = next;
        next = current.next;
    }
    current.next = prev;
    head = current;
}

MacOS Xcode CoreSimulator folder very big. Is it ok to delete content?

If you happen to be an iOS developer:

Check how many simulators that you have downloaded as they take up a lot of space:

Go to: ~/Library/Developer/Xcode/iOS DeviceSupport

Also delete old archived apps:

Go to: ~/Library/Developer/Xcode/Archives

I cleared 100GB doing this.

HTTP response code for POST when resource already exists

Personally I go with the WebDAV extension 422 Unprocessable Entity.

According to RFC 4918

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.

JSON find in JavaScript

Ok. So, I know this is an old post, but perhaps this can help someone else. This is not backwards compatible, but that's almost irrelevant since Internet Explorer is being made redundant.

Easiest way to do exactly what is wanted:

function findInJson(objJsonResp, key, value, aType){        
     if(aType=="edit"){
        return objJsonResp.find(x=> x[key] == value);
     }else{//delete
         var a =objJsonResp.find(x=> x[key] == value);
         objJsonResp.splice(objJsonResp.indexOf(a),1);
     }
}

It will return the item you want to edit if you supply 'edit' as the type. Supply anything else, or nothing, and it assumes delete. You can flip the conditionals if you'd prefer.

How to select a radio button by default?

They pretty much got it there... just like a checkbox, all you have to do is add the attribute checked="checked" like so:

<input type="radio" checked="checked">

...and you got it.

Cheers!

php.ini & SMTP= - how do you pass username & password

Use Fake sendmail for Windows to send mail.

  1. Create a folder named sendmail in C:\wamp\.
  2. Extract these 4 files in sendmail folder: sendmail.exe, libeay32.dll, ssleay32.dll and sendmail.ini.
  3. Then configure C:\wamp\sendmail\sendmail.ini:
smtp_server=smtp.gmail.com
smtp_port=465
[email protected]
auth_password=your_password
  1. The above will work against a Gmail account. And then configure php.ini:

    sendmail_path = "C:\wamp\sendmail\sendmail.exe -t"

  2. Now, restart Apache, and that is basically all you need to do.

Dark Theme for Visual Studio 2010 With Productivity Power Tools

Not sure if any of these help, but this might get you started: http://studiostyles.info

I know that the site owner has been gradually adding functionality to allow support for new color assignments, so perhaps there's something there.

Prevent scroll-bar from adding-up to the Width of page on Chrome

.modal-dialog {
   position: absolute;
   left: calc(50vw - 300px);
}

where 300 px is a half of my dialog window width.

This is actually the only thing that worked for me.

What is the Swift equivalent to Objective-C's "@synchronized"?

Another method is to create a superclass and then inherit it. This way you can use GCD more directly

class Lockable {
    let lockableQ:dispatch_queue_t

    init() {
        lockableQ = dispatch_queue_create("com.blah.blah.\(self.dynamicType)", DISPATCH_QUEUE_SERIAL)
    }

    func lock(closure: () -> ()) {
        dispatch_sync(lockableQ, closure)
    }
}


class Foo: Lockable {

    func boo() {
        lock {
            ....... do something
        }
    }

How can I create an error 404 in PHP?

Try this:

<?php
header("HTTP/1.0 404 Not Found");
?>

Java: Reading integers from a file into an array

It looks like Java is trying to convert an empty string into a number. Do you have an empty line at the end of the series of numbers?

You could probably fix the code like this

String s = in.readLine();
int i = 0;

while (s != null) {
    // Skip empty lines.
    s = s.trim();
    if (s.length() == 0) {
        continue;
    }

    tall[i] = Integer.parseInt(s); // This is line 19.
    System.out.println(tall[i]);
    s = in.readLine();
    i++;
}

in.close();

C++ Calling a function from another class

Forward declare class B and swap order of A and B definitions: 1st B and 2nd A. You can not call methods of forward declared B class.

How to get image width and height in OpenCV?

You can use rows and cols:

cout << "Width : " << src.cols << endl;
cout << "Height: " << src.rows << endl;

or size():

cout << "Width : " << src.size().width << endl;
cout << "Height: " << src.size().height << endl;

This project references NuGet package(s) that are missing on this computer

One solution would be to remove from the .csproj file the following:

<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />

This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.

Are the decimal places in a CSS width respected?

Even when the number is rounded when the page is painted, the full value is preserved in memory and used for subsequent child calculation. For example, if your box of 100.4999px paints to 100px, it's child with a width of 50% will be calculated as .5*100.4999 instead of .5*100. And so on to deeper levels.

I've created deeply nested grid layout systems where parents widths are ems, and children are percents, and including up to four decimal points upstream had a noticeable impact.

Edge case, sure, but something to keep in mind.

this is error ORA-12154: TNS:could not resolve the connect identifier specified?

ORA-12154: TNS:could not resolve the connect identifier specified?

In case the TNS is not defined you can also try this one:

If you are using C#.net 2010 or other version of VS and oracle 10g express edition or lower version, and you make a connection string like this:

static string constr = @"Data Source=(DESCRIPTION=
    (ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=yourhostname )(PORT=1521)))
    (CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)));
    User Id=system ;Password=yourpasswrd"; 

After that you get error message ORA-12154: TNS:could not resolve the connect identifier specified then first you have to do restart your system and run your project.

And if Your windows is 64 bit then you need to install oracle 11g 32 bit and if you installed 11g 64 bit then you need to Install Oracle 11g Oracle Data Access Components (ODAC) with Oracle Developer Tools for Visual Studio version 11.2.0.1.2 or later from OTN and check it in Oracle Universal Installer Please be sure that the following are checked:

Oracle Data Provider for .NET 2.0

Oracle Providers for ASP.NET

Oracle Developer Tools for Visual Studio

Oracle Instant Client 

And then restart your Visual Studio and then run your project .... NOTE:- SYSTEM RESTART IS necessary TO SOLVE THIS TYPES OF ERROR.......

How to set a transparent background of JPanel?

(Feature Panel).setOpaque(false);

Hope this helps.

How to check if $? is not equal to zero in unix shell scripting?

I put together some code that may help to see how return value vs returned strings works. There may be a better way, but this is what I found through testing.

#!/bin/sh
#
# ro
#

pass(){
  echo passed
  return 0;   # no errors
}
fail(){
  echo failed
  return 1;   # has an error
}
t(){
  echo true, has error
}
f(){
  echo false, no error
}

dv=$(printf "%60s"); dv=${dv// /-}

echo return code good for one use, not available for echo
echo $dv
pass
[ $? -gt 0 ] && t || f
echo "function pass: \$? $?" ' return value is gone'
echo
fail
[ $? -gt 0 ] && t || f
echo "function fail: \$? $?" ' return value is gone'
echo

echo save return code to var k for continued usage
echo $dv
pass
k=$?
[ $k -gt 0 ] && t || f
echo "function pass: \$k $k"
echo
fail
k=$?
[ $k -gt 0 ] && t || f
echo "function fail: \$k $k"
echo

# direct evaluation of the return value
# note that (...) and $(...) executes in a subshell
# with return value to calling shell
# ((...)) is for math/string evaluation

echo direct evaluations of the return value:
echo '  by if (pass) and if (fail)'
echo $dv
if (pass); then
  echo pass has no errors
else
  echo pass has errors
fi
if (fail); then
  echo fail has no errors
else
  echo fail has errors
fi

# this code results in error because of returned string (stdout)
# but comment out the echo statements in pass/fail functions and this code succeeds
echo
echo '  by if $(pass) and if $(fail) ..this succeeds if no echo to stdout from function'
echo $dv
if $(pass); then
  echo pass has no errors
else
  echo pass has errors
fi
if $(fail); then
  echo fail has no errors
else
  echo fail has errors
fi

echo
echo '  by if ((pass)) and if ((fail)) ..this always fails'
echo $dv
if ((pass)); then
  echo pass has no errors
else
  echo pass has errors
fi
if ((fail)); then
  echo fail has no errors
else
  echo fail has errors
fi

echo 
s=$(pass)
r=$?
echo pass, "s: $s  ,  r: $r"
s=$(fail)
r=$?
echo fail, "s: $s  ,  r: $r"

How to add column to numpy array

I add a new column with ones to a matrix array in this way:

Z = append([[1 for _ in range(0,len(Z))]], Z.T,0).T

Maybe it is not that efficient?

Difference between readFile() and readFileSync()

fs.readFile takes a call back which calls response.send as you have shown - good. If you simply replace that with fs.readFileSync, you need to be aware it does not take a callback so your callback which calls response.send will never get called and therefore the response will never end and it will timeout.

You need to show your readFileSync code if you're not simply replacing readFile with readFileSync.

Also, just so you're aware, you should never call readFileSync in a node express/webserver since it will tie up the single thread loop while I/O is performed. You want the node loop to process other requests until the I/O completes and your callback handling code can run.

How to compare strings

You could use strcmp():

/* strcmp example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char szKey[] = "apple";
  char szInput[80];
  do {
     printf ("Guess my favourite fruit? ");
     gets (szInput);
  } while (strcmp (szKey,szInput) != 0);
  puts ("Correct answer!");
  return 0;
}

Transform DateTime into simple Date in Ruby on Rails

For old Ruby (1.8.x):

myDate = Date.parse(myDateTime.to_s)

Break or return from Java 8 stream forEach?

public static void main(String[] args) {
    List<String> list = Arrays.asList("one", "two", "three", "seven", "nine");
    AtomicBoolean yes = new AtomicBoolean(true);
    list.stream().takeWhile(value -> yes.get()).forEach(value -> {
        System.out.println("prior cond" + value);
        if (value.equals("two")) {
            System.out.println(value);
            yes.set(false);
        }

    });
    //System.out.println("Hello World");
}

Remove all whitespace in a string

import re    
sentence = ' hello  apple'
re.sub(' ','',sentence) #helloworld (remove all spaces)
re.sub('  ',' ',sentence) #hello world (remove double spaces)

Capture Signature using HTML5 and iPad

Here's another canvas based version with variable width (based on drawing velocity) curves: demo at http://szimek.github.io/signature_pad and code at https://github.com/szimek/signature_pad.

signature sample

CSS media queries for screen sizes

Unless you have more style sheets than that, you've messed up your break points:

#1 (max-width: 700px)
#2 (min-width: 701px) and (max-width: 900px)
#3 (max-width: 901px)

The 3rd media query is probably meant to be min-width: 901px. Right now, it overlaps #1 and #2, and only controls the page layout by itself when the screen is exactly 901px wide.

Edit for updated question:

(max-width: 640px)
(max-width: 800px)
(max-width: 1024px)
(max-width: 1280px)

Media queries aren't like catch or if/else statements. If any of the conditions match, then it will apply all of the styles from each media query it matched. If you only specify a min-width for all of your media queries, it's possible that some or all of the media queries are matched. In your case, a device that's 640px wide matches all 4 of your media queries, so all for style sheets are loaded. What you are most likely looking for is this:

(max-width: 640px)
(min-width: 641px) and (max-width: 800px)
(min-width: 801px) and (max-width: 1024px)
(min-width: 1025px)

Now there's no overlap. The styles will only apply if the device's width falls between the widths specified.

How do I force "git pull" to overwrite local files?

I had a similar problem. I had to do this:

git reset --hard HEAD
git clean -f
git pull

How do I use jQuery to redirect?

You forgot the HTTP part:

window.location.href = "http://example.com/Registration/Success/";

How to remove a branch locally?

You can delete multiple branches on windows using Git GUI:

  1. Go to your Project folder
  2. Open Git Gui: enter image description here
  3. Click on 'Branch': enter image description here
  4. Now choose 'Delete': enter image description here
  5. If you want to delete all branches besides the fact they are merged or not, then check 'Always (Do not perform merge checks)' enter image description here

Query grants for a table in postgres

The query below will give you a list of all users and their permissions on the table in a schema.

select a.schemaname, a.tablename, b.usename,
  HAS_TABLE_PRIVILEGE(usename, quote_ident(schemaname) || '.' || quote_ident(tablename), 'select') as has_select,
  HAS_TABLE_PRIVILEGE(usename, quote_ident(schemaname) || '.' || quote_ident(tablename), 'insert') as has_insert,
  HAS_TABLE_PRIVILEGE(usename, quote_ident(schemaname) || '.' || quote_ident(tablename), 'update') as has_update,
  HAS_TABLE_PRIVILEGE(usename, quote_ident(schemaname) || '.' || quote_ident(tablename), 'delete') as has_delete, 
  HAS_TABLE_PRIVILEGE(usename, quote_ident(schemaname) || '.' || quote_ident(tablename), 'references') as has_references 
from pg_tables a, pg_user b 
where a.schemaname = 'your_schema_name' and a.tablename='your_table_name';

More details on has_table_privilages can be found here.

Alternate table row color using CSS?

There is a fairly easy way to do this in PHP, if I understand your query, I assume that you code in PHP and you are using CSS and javascript to enhance the output.

The dynamic output from the database will carry a for loop to iterate through results which are then loaded into the table. Just add a function call to the like this:

echo "<tr style=".getbgc($i).">";  //this calls the function based on the iteration of the for loop.

then add the function to the page or library file:

function getbgc($trcount)
{

$blue="\"background-color: #EEFAF6;\"";
$green="\"background-color: #D4F7EB;\"";
$odd=$trcount%2;
    if($odd==1){return $blue;}
    else{return $green;}    

}

Now this will alternate dynamically between colors at each newly generated table row.

It's a lot easier than messing about with CSS that doesn't work on all browsers.

Hope this helps.

How to Access Hive via Python?

To connect using a username/password and specifying ports, the code looks like this:

from pyhive import presto

cursor = presto.connect(host='host.example.com',
                    port=8081,
                    username='USERNAME:PASSWORD').cursor()

sql = 'select * from table limit 10'

cursor.execute(sql)

print(cursor.fetchone())
print(cursor.fetchall())

jQuery javascript regex Replace <br> with \n

myString.replace(/<br ?\/?>/g, "\n")

One line if/else condition in linux shell scripting

It's not a direct answer to the question but you could just use the OR-operator

( grep "#SystemMaxUse=" journald.conf > /dev/null && sed -i 's/\#SystemMaxUse=/SystemMaxUse=50M/g' journald.conf ) || echo "This file has been edited. You'll need to do it manually."

What is the meaning of git reset --hard origin/master?

git reset --hard origin/master

says: throw away all my staged and unstaged changes, forget everything on my current local branch and make it exactly the same as origin/master.

You probably wanted to ask this before you ran the command. The destructive nature is hinted at by using the same words as in "hard reset".

Json.net serialize/deserialize derived types?

You have to enable Type Name Handling and pass that to the (de)serializer as a settings parameter.

Base object1 = new Base() { Name = "Object1" };
Derived object2 = new Derived() { Something = "Some other thing" };
List<Base> inheritanceList = new List<Base>() { object1, object2 };

JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
string Serialized = JsonConvert.SerializeObject(inheritanceList, settings);
List<Base> deserializedList = JsonConvert.DeserializeObject<List<Base>>(Serialized, settings);

This will result in correct deserialization of derived classes. A drawback to it is that it will name all the objects you are using, as such it will name the list you are putting the objects in.

What exactly are iterator, iterable, and iteration?

Iterators are objects that implement the iter and next methods. If those methods are defined, we can use for loop or comprehensions.

class Squares:
    def __init__(self, length):
        self.length = length
        self.i = 0
        
    def __iter__(self):
        print('calling __iter__') # this will be called first and only once
        return self
    
    def __next__(self): 
        print('calling __next__') # this will be called for each iteration
        if self.i >= self.length:
            raise StopIteration
        else:
            result = self.i ** 2
            self.i += 1
            return result

Iterators get exhausted. It means after you iterate over items, you cannot reiterate, you have to create a new object. Let's say you have a class, which holds the cities properties and you want to iterate over.

class Cities:
    def __init__(self):
        self._cities = ['Brooklyn', 'Manhattan', 'Prag', 'Madrid', 'London']
        self._index = 0
    
    def __iter__(self):
        return self
    
    def __next__(self):
        if self._index >= len(self._cities):
            raise StopIteration
        else:
            item = self._cities[self._index]
            self._index += 1
            return item

Instance of class Cities is an iterator. However if you want to reiterate over cities, you have to create a new object which is an expensive operation. You can separate the class into 2 classes: one returns cities and second returns an iterator which gets the cities as init param.

class Cities:
    def __init__(self):
        self._cities = ['New York', 'Newark', 'Istanbul', 'London']        
    def __len__(self):
        return len(self._cities)



class CityIterator:
    def __init__(self, city_obj):
        # cities is an instance of Cities
        self._city_obj = city_obj
        self._index = 0
        
    def __iter__(self):
        return self
    
    def __next__(self):
        if self._index >= len(self._city_obj):
            raise StopIteration
        else:
            item = self._city_obj._cities[self._index]
            self._index += 1
            return item

Now if we need to create a new iterator, we do not have to create the data again, which is cities. We creates cities object and pass it to the iterator. But we are still doing extra work. We could implement this by creating only one class.

Iterable is a Python object that implements the iterable protocol. It requires only __iter__() that returns a new instance of iterator object.

class Cities:
    def __init__(self):
        self._cities = ['New York', 'Newark', 'Istanbul', 'Paris']
        
    def __len__(self):
        return len(self._cities)
    
    def __iter__(self):
        return self.CityIterator(self)
    
    class CityIterator:
        def __init__(self, city_obj):
            self._city_obj = city_obj
            self._index = 0

        def __iter__(self):
            return self

        def __next__(self):
            if self._index >= len(self._city_obj):
                raise StopIteration
            else:
                item = self._city_obj._cities[self._index]
                self._index += 1
                return item

Iterators has __iter__ and __next__, iterables have __iter__, so we can say Iterators are also iterables but they are iterables that get exhausted. Iterables on the other hand never become exhausted because they always return a new iterator that is then used to iterate

You notice that the main part of the iterable code is in the iterator, and the iterable itself is nothing more than an extra layer that allows us to create and access the iterator.

Iterating over an iterable

Python has a built function iter() which calls the __iter__(). When we iterate over an iterable, Python calls the iter() which returns an iterator, then it starts using __next__() of iterator to iterate over the data.

NOte that in the above example, Cities creates an iterable but it is not a sequence type, it means we cannot get a city by an index. To fix this we should just add __get_item__ to the Cities class.

class Cities:
    def __init__(self):
        self._cities = ['New York', 'Newark', 'Budapest', 'Newcastle']
        
    def __len__(self):
        return len(self._cities)
    
    def __getitem__(self, s): # now a sequence type
        return self._cities[s]
    
    def __iter__(self):
        return self.CityIterator(self)
    
    class CityIterator:
        def __init__(self, city_obj):
            self._city_obj = city_obj
            self._index = 0

        def __iter__(self):
            return self

        def __next__(self):
            if self._index >= len(self._city_obj):
                raise StopIteration
            else:
                item = self._city_obj._cities[self._index]
                self._index += 1
                return item

How do I concatenate two text files in PowerShell?

If you need to order the files by specific parameter (e.g. date time):

gci *.log | sort LastWriteTime | % {$(Get-Content $_)} | Set-Content result.log

How to play or open *.mp3 or *.wav sound file in c++ program?

Use a library to (a) read the sound file(s) and (b) play them back. (I'd recommend trying both yourself at some point in your spare time, but...)

Perhaps (*nix):

Windows: DirectX.

find files by extension, *.html under a folder in nodejs

Old post but ES6 now handles this out of the box with the includes method.

let files = ['file.json', 'other.js'];

let jsonFiles = files.filter(file => file.includes('.json'));

console.log("Files: ", jsonFiles) ==> //file.json

How can I order a List<string>?

ListaServizi = ListaServizi.OrderBy(q => q).ToList();

Batch file FOR /f tokens

for /f "tokens=* delims= " %%f in (myfile) do

This reads a file line-by-line, removing leading spaces (thanks, jeb).

set line=%%f

sets then the line variable to the line just read and

call :procesToken

calls a subroutine that does something with the line

:processToken

is the start of the subroutine mentioned above.

for /f "tokens=1* delims=/" %%a in ("%line%") do

will then split the line at /, but stopping tokenization after the first token.

echo Got one token: %%a

will output that first token and

set line=%%b

will set the line variable to the rest of the line.

if not "%line%" == "" goto :processToken

And if line isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.

How to tell if a string contains a certain character in JavaScript?

To test for alphanumeric characters only:

if (/^[0-9A-Za-z]+$/.test(yourString))
{
    //there are only alphanumeric characters
}
else
{
    //it contains other characters
}

The regex is testing for 1 or more (+) of the set of characters 0-9, A-Z, and a-z, starting with the beginning of input (^) and stopping with the end of input ($).

Get city name using geolocation

You can use https://ip-api.io/ to get city Name. It supports IPv6.

As a bonus it allows to check whether ip address is a tor node, public proxy or spammer.

Javascript Code:

$(document).ready(function () {
        $('#btnGetIpDetail').click(function () {
            if ($('#txtIP').val() == '') {
                alert('IP address is reqired');
                return false;
            }
            $.getJSON("http://ip-api.io/json/" + $('#txtIP').val(),
                 function (result) {
                     alert('City Name: ' + result.city)
                     console.log(result);
                 });
        });
    });

HTML Code

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div>
    <input type="text" id="txtIP" />
    <button id="btnGetIpDetail">Get Location of IP</button>
</div>

JSON Output

{
    "ip": "64.30.228.118",
    "country_code": "US",
    "country_name": "United States",
    "region_code": "FL",
    "region_name": "Florida",
    "city": "Fort Lauderdale",
    "zip_code": "33309",
    "time_zone": "America/New_York",
    "latitude": 26.1882,
    "longitude": -80.1711,
    "metro_code": 528,
    "suspicious_factors": {
        "is_proxy": false,
        "is_tor_node": false,
        "is_spam": false,
        "is_suspicious": false
    }
}

phpMyAdmin + CentOS 6.0 - Forbidden

I tried all answers provided here: editing phpMyAdmin.conf, changing selinux context for phpmyadmin folder, disabling selinux... but I still got a 'Forbidden' from the web server.

I finally found what I was missing in Edouard Thiel post here :

$ yum install php

then restart httpd :

$ service httpd restart => for centos 6 hots

$ systemctl restart httpd => for centos 7 hosts

What has me amazed is why php is not installed as dependency for phpmyadmin in the first place.

Regards, Fred

Get folder up one level

echo dirname(__DIR__);

But note the __DIR__ constant was added in PHP 5.3.0.

Angular 2 change event - model changes

If this helps you,

<input type="checkbox"  (ngModelChange)="mychange($event)" [ngModel]="mymodel">

mychange(val)
{
   console.log(val); // updated value
}

How to view hierarchical package structure in Eclipse package explorer

Package Explorer / View Menu / Package Presentation... / Hierarchical

The "View Menu" can be opened with Ctrl + F10, or the small arrow-down icon in the top-right corner of the Package Explorer.

What is the most efficient way to store a list in the Django models?

"Premature optimization is the root of all evil."

With that firmly in mind, let's do this! Once your apps hit a certain point, denormalizing data is very common. Done correctly, it can save numerous expensive database lookups at the cost of a little more housekeeping.

To return a list of friend names we'll need to create a custom Django Field class that will return a list when accessed.

David Cramer posted a guide to creating a SeperatedValueField on his blog. Here is the code:

from django.db import models

class SeparatedValuesField(models.TextField):
    __metaclass__ = models.SubfieldBase

    def __init__(self, *args, **kwargs):
        self.token = kwargs.pop('token', ',')
        super(SeparatedValuesField, self).__init__(*args, **kwargs)

    def to_python(self, value):
        if not value: return
        if isinstance(value, list):
            return value
        return value.split(self.token)

    def get_db_prep_value(self, value):
        if not value: return
        assert(isinstance(value, list) or isinstance(value, tuple))
        return self.token.join([unicode(s) for s in value])

    def value_to_string(self, obj):
        value = self._get_val_from_obj(obj)
        return self.get_db_prep_value(value)

The logic of this code deals with serializing and deserializing values from the database to Python and vice versa. Now you can easily import and use our custom field in the model class:

from django.db import models
from custom.fields import SeparatedValuesField 

class Person(models.Model):
    name = models.CharField(max_length=64)
    friends = SeparatedValuesField()

How to jump to a particular line in a huge text file?

I'm probably spoiled by abundant ram, but 15 M is not huge. Reading into memory with readlines() is what I usually do with files of this size. Accessing a line after that is trivial.

<> And Not In VB.NET

I have always used the following:

If Request.QueryString("MyQueryString") IsNot Nothing Then

But only because syntactically it reads better.

When testing for a valid QueryString entry I also use the following:

If Not String.IsNullOrEmpty(Request.QueryString("MyQueryString")) Then

These are just the methods I have always used so I could not justify their usage other than they make the most sense to me when reading back code.

How can I add an item to a IEnumerable<T> collection?

you can do this.

//Create IEnumerable    
IEnumerable<T> items = new T[]{new T("msg")};

//Convert to list.
List<T> list = items.ToList();

//Add new item to list.
list.add(new T("msg2"));

//Cast list to IEnumerable
items = (IEnumerable<T>)items;

Java: convert seconds to minutes, hours and days

The simpliest way

    Scanner in = new Scanner(System.in);
    System.out.println("Enter seconds");
    int s = in.nextInt();

    int sec = s % 60;
    int min = (s / 60)%60;
    int hours = (s/60)/60;

    System.out.println(hours + ":" + min + ":" + sec);

What's the best way to generate a UML diagram from Python source code?

Certain classes of well-behaved programs may be diagrammable, but in the general case, it can't be done. Python objects can be extended at run time, and objects of any type can be assigned to any instance variable. Figuring out what classes an object can contain pointers to (composition) would require a full understanding of the runtime behavior of the program.

Python's metaclass capabilities mean that reasoning about the inheritance structure would also require a full understanding of the runtime behavior of the program.

To prove that these are impossible, you argue that if such a UML diagrammer existed, then you could take an arbitrary program, convert "halt" statements into statements that would impact the UML diagram, and use the UML diagrammer to solve the halting problem, which as we know is impossible.

Calling Python in PHP

is so easy You can use [phpy - library for php][1] php file

<?php
  require_once "vendor/autoload.php";

  use app\core\App;

  $app = new App();
  $python = $app->python;
  $output = $python->set(your python path)->send(data..)->gen();
  var_dump($ouput);

python file:

import include.library.phpy as phpy
print(phpy.get_data(number of data , first = 1 , two =2 ...))

you can see also example in github page [1]: https://github.com/Raeen123/phpy

Custom events in jQuery?

I think so.. it's possible to 'bind' custom events, like(from: http://docs.jquery.com/Events/bind#typedatafn):

 $("p").bind("myCustomEvent", function(e, myName, myValue){
      $(this).text(myName + ", hi there!");
      $("span").stop().css("opacity", 1)
               .text("myName = " + myName)
               .fadeIn(30).fadeOut(1000);
    });
    $("button").click(function () {
      $("p").trigger("myCustomEvent", [ "John" ]);
    });

How to enable authentication on MongoDB through Docker?

If you take a look at:

you will notice that there are two variables used in the docker-entrypoint.sh:

  • MONGO_INITDB_ROOT_USERNAME
  • MONGO_INITDB_ROOT_PASSWORD

You can use them to setup root user. For example you can use following docker-compose.yml file:

mongo-container:
  image: mongo:3.4.2
  environment:
      # provide your credentials here
      - MONGO_INITDB_ROOT_USERNAME=root
      - MONGO_INITDB_ROOT_PASSWORD=rootPassXXX
  ports:
    - "27017:27017"
  volumes:
      # if you wish to setup additional user accounts specific per DB or with different roles you can use following entry point
    - "$PWD/mongo-entrypoint/:/docker-entrypoint-initdb.d/"
  # no --auth is needed here as presence of username and password add this option automatically
  command: mongod

Now when starting the container by docker-compose up you should notice following entries:

...
I CONTROL  [initandlisten] options: { net: { bindIp: "127.0.0.1" }, processManagement: { fork: true }, security: { authorization: "enabled" }, systemLog: { destination: "file", path: "/proc/1/fd/1" } }
...
I ACCESS   [conn1] note: no users configured in admin.system.users, allowing localhost access
...
Successfully added user: {
    "user" : "root",
    "roles" : [
        {
            "role" : "root",
            "db" : "admin"
        }
    ]
}

To add custom users apart of root use the entrypoint exectuable script (placed under $PWD/mongo-entrypoint dir as it is mounted in docker-compose to entrypoint):

#!/usr/bin/env bash
echo "Creating mongo users..."
mongo admin --host localhost -u USER_PREVIOUSLY_DEFINED -p PASS_YOU_PREVIOUSLY_DEFINED --eval "db.createUser({user: 'ANOTHER_USER', pwd: 'PASS', roles: [{role: 'readWrite', db: 'xxx'}]}); db.createUser({user: 'admin', pwd: 'PASS', roles: [{role: 'userAdminAnyDatabase', db: 'admin'}]});"
echo "Mongo users created."

Entrypoint script will be executed and additional users will be created.

How to sort multidimensional array by column?

The optional key parameter to sort/sorted is a function. The function is called for each item and the return values determine the ordering of the sort

>>> lst = [['John', 2], ['Jim', 9], ['Jason', 1]]
>>> def my_key_func(item):
...     print("The key for {} is {}".format(item, item[1]))
...     return item[1]
... 
>>> sorted(lst, key=my_key_func)
The key for ['John', 2] is 2
The key for ['Jim', 9] is 9
The key for ['Jason', 1] is 1
[['Jason', 1], ['John', 2], ['Jim', 9]]

taking the print out of the function leaves

>>> def my_key_func(item):
...     return item[1]

This function is simple enough to write "inline" as a lambda function

>>> sorted(lst, key=lambda item: item[1])
[['Jason', 1], ['John', 2], ['Jim', 9]]

Python AttributeError: 'module' object has no attribute 'Serial'

Yes this topic is a bit old but i wanted to share the solution that worked for me for those who might need it anyway

As Ali said, try to locate your program using the following from terminal :

 sudo python3
 import serial

print(serial.__file__) --> Copy

CTRL+D #(to get out of python)

sudo python3-->paste/__init__.py

Activating __init__.py will say to your program "ok i'm going to use Serial from python3". My problem was that my python3 program was using Serial from python 2.7

Other solution: remove other python versions

Cao

Sources : https://raspberrypi.stackexchange.com/questions/74742/python-serial-serial-module-not-found-error/85930#85930

Tryhard

configure: error: C compiler cannot create executables

First get the gcc path using

Command: which gcc

Output: /usr/bin/gcc

I had the same issue, Please set the gcc path in below command and install

CC=/usr/bin/gcc rvm install 1.9.3

Later if you get "Ruby was built without documentation" run below command

rvm docs generate-ri

Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe

Even when you asked finally for the opposite, to reform 0s and 1s into Trues and Falses, however, I post an answer about how to transform falses and trues into ones and zeros (1s and 0s), for a whole dataframe, in a single line.

Example given

df <- structure(list(p1_1 = c(TRUE, FALSE, FALSE, NA, TRUE, FALSE, 
                NA), p1_2 = c(FALSE, TRUE, FALSE, NA, FALSE, NA, 
                TRUE), p1_3 = c(TRUE, 
                TRUE, FALSE, NA, NA, FALSE, TRUE), p1_4 = c(FALSE, NA, 
                FALSE,  FALSE, TRUE, FALSE, NA), p1_5 = c(TRUE, NA, 
                FALSE, TRUE, FALSE, NA, TRUE), p1_6 = c(TRUE, NA, 
                FALSE, TRUE, FALSE, NA, TRUE), p1_7 = c(TRUE, NA, 
                FALSE, TRUE, NA, FALSE, TRUE), p1_8 = c(FALSE, 
                FALSE, NA, FALSE, TRUE, FALSE, NA), p1_9 = c(TRUE, 
                FALSE,  NA, FALSE, FALSE, NA, TRUE), p1_10 = c(TRUE, 
                FALSE, NA, FALSE, FALSE, NA, TRUE), p1_11 = c(FALSE, 
                FALSE, NA, FALSE, NA, FALSE, TRUE)), .Names = 
                c("p1_1", "p1_2", "p1_3", "p1_4", "p1_5", "p1_6", 
                "p1_7", "p1_8", "p1_9", "p1_10", "p1_11"), row.names = 
                 c(NA, -7L), class = "data.frame")

   p1_1  p1_2  p1_3  p1_4  p1_5  p1_6  p1_7  p1_8  p1_9 p1_10 p1_11
1  TRUE FALSE  TRUE FALSE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE FALSE
2 FALSE  TRUE  TRUE    NA    NA    NA    NA FALSE FALSE FALSE FALSE
3 FALSE FALSE FALSE FALSE FALSE FALSE FALSE    NA    NA    NA    NA
4    NA    NA    NA FALSE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE
5  TRUE FALSE    NA  TRUE FALSE FALSE    NA  TRUE FALSE FALSE    NA
6 FALSE    NA FALSE FALSE    NA    NA FALSE FALSE    NA    NA FALSE
7    NA  TRUE  TRUE    NA  TRUE  TRUE  TRUE    NA  TRUE  TRUE  TRUE

Then by running that: df * 1 all Falses and Trues are trasnformed into 1s and 0s. At least, this was happen in the R version that I have (R version 3.4.4 (2018-03-15) ).

> df*1
  p1_1 p1_2 p1_3 p1_4 p1_5 p1_6 p1_7 p1_8 p1_9 p1_10 p1_11
1    1    0    1    0    1    1    1    0    1     1     0
2    0    1    1   NA   NA   NA   NA    0    0     0     0
3    0    0    0    0    0    0    0   NA   NA    NA    NA
4   NA   NA   NA    0    1    1    1    0    0     0     0
5    1    0   NA    1    0    0   NA    1    0     0    NA
6    0   NA    0    0   NA   NA    0    0   NA    NA     0
7   NA    1    1   NA    1    1    1   NA    1     1     1

I do not know if it a total "safe" command, under all different conditions / dfs.

"Submit is not a function" error in JavaScript

giving a form element a name of submit will simple shadow the submit property . make sure you don't have a form element with the name submit and you should be able to access the submit function just fine .

Difference between declaring variables before or in loop?

this is the better form

double intermediateResult;
int i = byte.MinValue;

for(; i < 1000; i++)
{
intermediateResult = i;
System.out.println(intermediateResult);
}

1) in this way declared once time both variable, and not each for cycle. 2) the assignment it's fatser thean all other option. 3) So the bestpractice rule is any declaration outside the iteration for.

How to detect my browser version and operating system using JavaScript?

For Firefox, Chrome, Opera, Internet Explorer and Safari

var ua="Mozilla/1.22 (compatible; MSIE 10.0; Windows 3.1)";
//ua = navigator.userAgent;
var b;
var browser;
if(ua.indexOf("Opera")!=-1) {

    b=browser="Opera";
}
if(ua.indexOf("Firefox")!=-1 && ua.indexOf("Opera")==-1) {
    b=browser="Firefox";
    // Opera may also contains Firefox
}
if(ua.indexOf("Chrome")!=-1) {
    b=browser="Chrome";
}
if(ua.indexOf("Safari")!=-1 && ua.indexOf("Chrome")==-1) {
    b=browser="Safari";
    // Chrome always contains Safari
}

if(ua.indexOf("MSIE")!=-1 && (ua.indexOf("Opera")==-1 && ua.indexOf("Trident")==-1)) {
    b="MSIE";
    browser="Internet Explorer";
    //user agent with MSIE and Opera or MSIE and Trident may exist.
}

if(ua.indexOf("Trident")!=-1) {
    b="Trident";
    browser="Internet Explorer";
}

// now for version


var version=ua.match(b+"[ /]+[0-9]+(.[0-9]+)*")[0];

console.log("broswer",browser);
console.log("version",version);

Show div #id on click with jQuery

You can use jQuery toggle to show and hide the div. The script will be like this

  <script type="text/javascript">
    jQuery(function(){
      jQuery("#music").click(function () {
        jQuery("#musicinfo").toggle("slow");
      });
    });
</script>

How to check if an option is selected?

If you're not familiar or comfortable with is(), you could just check the value of prop("selected").

As seen here:

$('#mySelectBox option').each(function() {
    if ($(this).prop("selected") == true) {
       // do something
    } else {
       // do something
    }
});?

Edit:

As @gdoron pointed out in the comments, the faster and most appropriate way to access the selected property of an option is via the DOM selector. Here is the fiddle update displaying this action.

if (this.selected == true) {

appears to work just as well! Thanks gdoron.

Android Studio: Can't start Git

Try this...

  1. Make sure, have you installed git on your machine. If not you can download(Windows user) from here and install it your system. For Mac user can download from here

  2. Get location of git.exe Get location of git.exe

  3. Test git.exe manually test

  4. Now you can set your git.exe location in android studio.

Java division by zero doesnt throw an ArithmeticException - why?

Why can't you just check it yourself and throw an exception if that is what you want.

    try {
        for (int i = 0; i < tab.length; i++) {
            tab[i] = 1.0 / tab[i];

            if (tab[i] == Double.POSITIVE_INFINITY ||
                    tab[i] == Double.NEGATIVE_INFINITY)
                throw new ArithmeticException();
        }
    } catch (ArithmeticException ae) {
        System.out.println("ArithmeticException occured!");
    }

What is a superfast way to read large files line-by-line in VBA?

My take on it...obviously, you've got to do something with the data you read in. If it involves writing it to the sheet, that'll be deadly slow with a normal For Loop. I came up with the following based upon a rehash of some of the items there, plus some help from the Chip Pearson website.

Reading in the text file (assuming you don't know the length of the range it will create, so only the startingCell is given):

Public Sub ReadInPlainText(startCell As Range, Optional textfilename As Variant)

   If IsMissing(textfilename) Then textfilename = Application.GetOpenFilename("All Files (*.*), *.*", , "Select Text File to Read")
   If textfilename = "" Then Exit Sub

   Dim filelength As Long
   Dim filenumber As Integer
   filenumber = FreeFile
   filelength = filelen(textfilename)
   Dim text As String
   Dim textlines As Variant

   Open textfilename For Binary Access Read As filenumber

   text = Space(filelength)
   Get #filenumber, , text

   'split the file with vbcrlf
   textlines = Split(text, vbCrLf) 

   'output to range
   Dim outputRange As Range
   Set outputRange = startCell
   Set outputRange = outputRange.Resize(UBound(textlines), 1)
   outputRange.Value = Application.Transpose(textlines)

   Close filenumber
 End Sub

Conversely, if you need to write out a range to a text file, this does it quickly in one print statement (note: the file 'Open' type here is in text mode, not binary..unlike the read routine above).

Public Sub WriteRangeAsPlainText(ExportRange As Range, Optional textfilename As Variant)
   If IsMissing(textfilename) Then textfilename = Application.GetSaveAsFilename(FileFilter:="Text Files (*.txt), *.txt")
   If textfilename = "" Then Exit Sub

   Dim filenumber As Integer
   filenumber = FreeFile
   Open textfilename For Output As filenumber

   Dim textlines() As Variant, outputvar As Variant

   textlines = Application.Transpose(ExportRange.Value)
   outputvar = Join(textlines, vbCrLf)
   Print #filenumber, outputvar
   Close filenumber
End Sub

How to initialize var?

you can't initialise var with null, var needs to be initialised as a type otherwise it cannot be inferred, if you think you need to do this maybe you can post the code it is probable that there is another way to do what you are attempting.

Can you call ko.applyBindings to bind a partial view?

While Niemeyer's answer is a more correct answer to the question, you could also do the following:

<div>
  <input data-bind="value: VMA.name" />
</div>

<div>
  <input data-bind="value: VMB.name" />
</div>

<script type="text/javascript">
  var viewModels = {
     VMA: {name: ko.observable("Bob")},
     VMB: {name: ko.observable("Ted")}
  };

  ko.applyBindings(viewModels);
</script>

This means you don't have to specify the DOM element, and you can even bind multiple models to the same element, like this:

<div>
  <input data-bind="value: VMA.name() + ' and ' + VMB.name()" />
</div>

What is the proper REST response code for a valid request but an empty data?

Just an addition from a developer that struggled many times with this situation. As you might have noticed it is always a discussion whether you return a 404 or 200 or 204 when a particular resource does not exist. The discussion above shows that this topic is pretty confusing and opinion based ( while there is a http-status-code standard existing ). I personally recommend, as it was not mentioned yet I guess, no matter how you decide DOCUMENT IT IN YOUR API-DEFINITION. Of course a client-side developer has in mind when he/she uses your particular "REST"- api to use his/her knowledge about Rest and expects that your api works this way. I guess you see the trap. Therefor I use a readme where I explicitly define in which cases I use which status code. This doesn't mean that I use some random definion. I always try to use the standard but to avoid such cases I document my usage. The client might think you are wrong in some specific cases but as it is documented, there is no need for additional discussions what saves time for you and the developer.

One sentence to the Ops question: 404 is a code that always comes in my mind when I think back about starting to develop backend-applications and I configured something wrong in my controller-route so that my Controller method is not called. With that in mind, I think if the request does reach your code in a Controller method, the client did a valid request and the request endpoint was found. So this is an indication not to use 404. If the db query returns not found, I return 200 but with an empty body.

Get data from file input in JQuery

input element, of type file

<input id="fileInput" type="file" />

On your input change use the FileReader object and read your input file property:

$('#fileInput').on('change', function () {
    var fileReader = new FileReader();
    fileReader.onload = function () {
      var data = fileReader.result;  // data <-- in this var you have the file data in Base64 format
    };
    fileReader.readAsDataURL($('#fileInput').prop('files')[0]);
});

FileReader will load your file and in fileReader.result you have the file data in Base64 format (also the file content-type (MIME), text/plain, image/jpg, etc)

Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything

Python 3.6+ provides built-in convenience methods to find and decode the plain text body as in @Todor Minakov's answer. You can use the EMailMessage.get_body() and get_content() methods:

msg = email.message_from_string(s, policy=email.policy.default)
body = msg.get_body(('plain',))
if body:
    body = body.get_content()
print(body)

Note this will give None if there is no (obvious) plain text body part.

If you are reading from e.g. an mbox file, you can give the mailbox constructor an EmailMessage factory:

mbox = mailbox.mbox(mboxfile, factory=lambda f: email.message_from_binary_file(f, policy=email.policy.default), create=False)
for msg in mbox:
    ...

Note you must pass email.policy.default as the policy, since it's not the default...

How to escape indicator characters (i.e. : or - ) in YAML

I came here trying to get my Azure DevOps Command Line task working. The thing that worked for me was using the pipe (|) character. Using > did not work.

Example:

steps:
- task: CmdLine@2
  inputs:
    script: |
      echo "Selecting Mono version..."
      /bin/bash -c "sudo $AGENT_HOMEDIRECTORY/scripts/select-xamarin-sdk.sh 5_18_1"
      echo "Selecting Xcode version..."
      /bin/bash -c "echo '##vso[task.setvariable variable=MD_APPLE_SDK_ROOT;]'/Applications/Xcode_10.2.1.app;sudo xcode-select --switch /Applications/Xcode_10.2.1.app/Contents/Developer"

Rotating and spacing axis labels in ggplot2

The ggpubr package offers a shortcut that does the right thing by default (right align text, middle align text box to tick):

library(ggplot2)
diamonds$cut <- paste("Super Dee-Duper", as.character(diamonds$cut))
q <- qplot(cut, carat, data = diamonds, geom = "boxplot")
q + ggpubr::rotate_x_text()

Created on 2018-11-06 by the reprex package (v0.2.1)

Found with a GitHub search for the relevant argument names: https://github.com/search?l=R&q=element_text+angle+90+vjust+org%3Acran&type=Code

Byte Array to Image object

BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytes));

UUID max character length

This is the perfect kind of field to define as CHAR 36, by the way, not VARCHAR 36, since each value will have the exact same length. And you'll use less storage space, since you don't need to store the data length for each value, just the value.

Change onClick attribute with javascript

You are not actually changing the function.

onClick is assigned to a function (Which is a reference to something, a function pointer in this case). The values passed to it don't matter and cannot be utilised in any manner.

Another problem is your variable color seems out of nowhere.

Ideally, inside the function you should put this logic and let it figure out what to write. (on/off etc etc)

JavaFX "Location is required." even though it is in the same package

The root directory for the loader is in the 'resources' folder for a maven project. So if you have src/main/java then the fxml file path should start from: src/main/resources

https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html

Removing padding gutter from grid columns in Bootstrap 4

You can use this css code to get gutterless grid in bootstrap.

.no-gutter.row,
.no-gutter.container,
.no-gutter.container-fluid{
  margin-left: 0;
  margin-right: 0;
}

.no-gutter>[class^="col-"]{
  padding-left: 0;
  padding-right: 0;
}

How to programmatically close a JFrame

setVisible(false); //you can't see me!
dispose(); //Destroy the JFrame object

Not too tricky.

C++ cast to derived class

dynamic_cast should be what you are looking for.

EDIT:

DerivedType m_derivedType = m_baseType; // gives same error

The above appears to be trying to invoke the assignment operator, which is probably not defined on type DerivedType and accepting a type of BaseType.

DerivedType * m_derivedType = (DerivedType*) & m_baseType; // gives same error

You are on the right path here but the usage of the dynamic_cast will attempt to safely cast to the supplied type and if it fails, a NULL will be returned.

Going on memory here, try this (but note the cast will return NULL as you are casting from a base type to a derived type):

DerivedType * m_derivedType = dynamic_cast<DerivedType*>(&m_baseType);

If m_baseType was a pointer and actually pointed to a type of DerivedType, then the dynamic_cast should work.

Hope this helps!

How do I rename a column in a SQLite database table?

Since version 2018-09-15 (3.25.0) sqlite supports renaming columns

https://sqlite.org/changes.html

Why would we call cin.clear() and cin.ignore() after reading input?

The cin.clear() clears the error flag on cin (so that future I/O operations will work correctly), and then cin.ignore(10000, '\n') skips to the next newline (to ignore anything else on the same line as the non-number so that it does not cause another parse failure). It will only skip up to 10000 characters, so the code is assuming the user will not put in a very long, invalid line.

How I can check if an object is null in ruby on rails 2?

You can use the simple not flag to validate that. Example

if !@objectname

This will return true if @objectname is nil. You should not use dot operator or a nil value, else it will throw

*** NoMethodError Exception: undefined method `isNil?' for nil:NilClass

An ideal nil check would be like:

!@objectname || @objectname.nil? || @objectname.empty?

Responsive Images with CSS

um responsive is simple

  • first off create a class named cell give it the property of display:table-cell
  • then @ max-width:700px do {display:block; width:100%; clear:both}

and that's it no absolute divs ever; divs needs to be 100% then max-width: - desired width - for inner framming. A true responsive sites has less than 9 lines of css anything passed that you are in a world of shit and over complicated things.

PS : reset.css style sheets are what makes css blinds there was a logical reason why they gave default styles in the first place.

How can I show a message box with two buttons?

It can be done, I found it elsewhere on the web...this is no way my work ! :)

    Option Explicit
' Import
Private Declare Function GetCurrentThreadId Lib "kernel32" () As Long

Private Declare Function SetDlgItemText Lib "user32" _
    Alias "SetDlgItemTextA" _
    (ByVal hDlg As Long, _
     ByVal nIDDlgItem As Long, _
     ByVal lpString As String) As Long

Private Declare Function SetWindowsHookEx Lib "user32" _
    Alias "SetWindowsHookExA" _
    (ByVal idHook As Long, _
     ByVal lpfn As Long, _
     ByVal hmod As Long, _
     ByVal dwThreadId As Long) As Long

Private Declare Function UnhookWindowsHookEx Lib "user32" _
    (ByVal hHook As Long) As Long

' Handle to the Hook procedure
Private hHook As Long

' Hook type
Private Const WH_CBT = 5
Private Const HCBT_ACTIVATE = 5

' Constants
Public Const IDOK = 1
Public Const IDCANCEL = 2
Public Const IDABORT = 3
Public Const IDRETRY = 4
Public Const IDIGNORE = 5
Public Const IDYES = 6
Public Const IDNO = 7

Public Sub MsgBoxSmile()
    ' Set Hook
    hHook = SetWindowsHookEx(WH_CBT, _
                             AddressOf MsgBoxHookProc, _
                             0, _
                             GetCurrentThreadId)

    ' Run MessageBox
    MsgBox "Smiling Message Box", vbYesNo, "Message Box Hooking"
End Sub

Private Function MsgBoxHookProc(ByVal lMsg As Long, _
                                ByVal wParam As Long, _
                                ByVal lParam As Long) As Long

    If lMsg = HCBT_ACTIVATE Then
        SetDlgItemText wParam, IDYES, "Yes   :-)"
        SetDlgItemText wParam, IDNO, "No   :-("

        ' Release the Hook
        UnhookWindowsHookEx hHook
    End If

    MsgBoxHookProc = False
End Function

How can I wait for 10 second without locking application UI in android

You can use this:

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    public void run() {
     // Actions to do after 10 seconds
    }
}, 10000);

For Stop the Handler, You can try this: handler.removeCallbacksAndMessages(null);

How to sort ArrayList<Long> in decreasing order?

Comparator<Long> comparator = Collections.reverseOrder();
Collections.sort(arrayList, comparator);

Change background color of iframe issue

just building on what Chetabahana wrote, I found that adding a short delay to the JS function helped on a site I was working on. It meant that the function kicked in after the iframe loaded. You can play around with the delay.

var delayInMilliseconds = 500; // half a second

setTimeout(function() { 

   var iframe = document.getElementsByTagName('iframe')[0];
   iframe.style.background = 'white';
   iframe.contentWindow.document.body.style.backgroundColor = 'white';

}, delayInMilliseconds);

I hope this helps!

Get div tag scroll position using JavaScript

you use the scrollTop attribute

var position = document.getElementById('id').scrollTop;

Sample database for exercise

This is an online database but you can try with the stackoverflow database: https://data.stackexchange.com/stackoverflow/query/new

You also can download its dumps here:

https://archive.org/download/stackexchange

How to overlay density plots in R?

I took the above lattice example and made a nifty function. There is probably a better way to do this with reshape via melt/cast. (Comment or edit if you see an improvement.)

multi.density.plot=function(data,main=paste(names(data),collapse = ' vs '),...){
  ##combines multiple density plots together when given a list
  df=data.frame();
  for(n in names(data)){
    idf=data.frame(x=data[[n]],label=rep(n,length(data[[n]])))
    df=rbind(df,idf)
  }
  densityplot(~x,data=df,groups = label,plot.points = F, ref = T, auto.key = list(space = "right"),main=main,...)
}

Example usage:

multi.density.plot(list(BN1=bn1$V1,BN2=bn2$V1),main='BN1 vs BN2')

multi.density.plot(list(BN1=bn1$V1,BN2=bn2$V1))

SVN "Already Locked Error"

I am not using AnkhSVN but got a similar problem after cancelling a Tortoise SVN update. It left two directories "already locked". Similar to Roman C's solution. Use Get lock to to lock one file in each directory that is "already locked" and then release those locks, then do a cleanup on the highest directory. That seemed to fix the problem.

AJAX cross domain call

You can use YQL to do the request without needing to host your own proxy. I have made a simple function to make it easier to run commands:

function RunYQL(command, callback){
     callback_name = "__YQL_callback_"+(new Date()).getTime();
     window[callback_name] = callback;
     a = document.createElement('script');
     a.src = "http://query.yahooapis.com/v1/public/yql?q="
             +escape(command)+"&format=json&callback="+callback_name;
     a.type = "text/javascript";
     document.getElementsByTagName("head")[0].appendChild(a);
}

If you have jQuery, you may use $.getJSON instead.

A sample may be this:

RunYQL('select * from html where url="http://www.google.com/"',
       function(data){/* actions */}
);

Auto increment primary key in SQL Server Management Studio 2012

Perhaps I'm missing something but why doesn't this work with the SEQUENCE object? Is this not what you're looking for?

Example:

CREATE SCHEMA blah.
GO

CREATE SEQUENCE blah.blahsequence
START WITH 1
INCREMENT BY 1
NO CYCLE;

CREATE TABLE blah.de_blah_blah
(numbers bigint PRIMARY KEY NOT NULL
......etc

When referencing the squence in say an INSERT command just use:

NEXT VALUE FOR blah.blahsequence

More information and options for SEQUENCE

Find all special characters in a column in SQL Server 2008

The following transact SQL script works for all languages (international). The solution is not to check for alphanumeric but to check for not containing special characters.

DECLARE @teststring nvarchar(max)
SET @teststring = 'Test''Me'
SELECT 'IS ALPHANUMERIC: ' + @teststring
WHERE @teststring NOT LIKE '%[-!#%&+,./:;<=>@`{|}~"()*\\\_\^\?\[\]\'']%' {ESCAPE '\'}

How print out the contents of a HashMap<String, String> in ascending order based on its values?

You can use a list of the entry set rather than the key set and it is a more natural choice given you are sorting based on the value. This avoids a lot of unneeded lookups in the sorting and printing of the entries.

Map<String, String> map = ...
List<Map.Entry<String, String>> listOfEntries = new ArrayList<Map.Entry<String, String>>(map.entrySet());
Collections.sort(listOfEntries, new SortByValueComparator());
for(Map.Entry<String, String> entry: listOfEntries)
   System.out.println(entry);

static class SortByValueComparator implements Comparator<Map.Entry<String, String>> {
   public int compareTo(Map.Entry<String, String> e1, Map.Entry<String, String> e2) {
       return e1.getValue().compateTo(e2.getValue());
   }
}

How do JavaScript closures work?

I know there are plenty of solutions already, but I guess that this small and simple script can be useful to demonstrate the concept:

// makeSequencer will return a "sequencer" function
var makeSequencer = function() {
    var _count = 0; // not accessible outside this function
    var sequencer = function () {
        return _count++;
    }
    return sequencer;
}

var fnext = makeSequencer();
var v0 = fnext();     // v0 = 0;
var v1 = fnext();     // v1 = 1;
var vz = fnext._count // vz = undefined

How to make a <div> appear in front of regular text/tables

You can use the stacking index of the div to make it appear on top of anything else. Make it a larger value that other elements and it well be on top of others.

use z-index property. See Specifying the stack level: the 'z-index' property and

Elaborate description of Stacking Contexts

Something like

#divOnTop { z-index: 1000; }

<div id="divOnTop">I am on top</div>

What you have to look out for will be IE6. In IE 6 some elements like <select> will be placed on top of an element with z-index value higher than the <select>. You can have a workaround for this by placing an <iframe> behind the div.

See this Internet Explorer z-index bug?

how to get selected row value in the KendoUI

If you want to select particular element use below code

var gridRowData = $("<your grid name>").data("kendoGrid");
var selectedItem = gridRowData.dataItem(gridRowData.select());
var quote = selectedItem["<column name>"];

How to move screen without moving cursor in Vim?

my mnemonic for scrolling...

Adding to other answers also pay attention to ze and zs, meaning: move screen to the left/right of the cursor (without moving the cursor)

+-------------------------------+
^                               |
|c-e (keep cursor)              |
|H(igh)             zt (top)    |
|                   ^           |
|           ze      |      zs   |
|M(iddle)  zh/zH <--zz--> zl/zL |
|                   |           |
|                   v           |
|L(ow)              zb (bottom) |
|c-y (keep cursor)              |
v                               |
+-------------------------------+

also look at the position of h and l and t and b and (with qwertz keyboard) c-e and c-y (also the "y" somehow points to the bottom) on the keyboard to remember where the screen is moving.

How do I set bold and italic on UILabel of iPhone/iPad?

sectionLabel.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:18];

There is a list of font names that you can set in place of 'fontWithName' attribute.The link is here

Get File Path (ends with folder)

In the VBA Editor's Tools menu, click References... scroll down to "Microsoft Shell Controls And Automation" and choose it.

Sub FolderSelection()
    Dim MyPath As String
    MyPath = SelectFolder("Select Folder", "")
    If Len(MyPath) Then
        MsgBox MyPath
    Else
        MsgBox "Cancel was pressed"
    End If
End Sub

'Both arguements are optional. The first is the dialog caption and
'the second is is to specify the top-most visible folder in the
'hierarchy. The default is "My Computer."

Function SelectFolder(Optional Title As String, Optional TopFolder _
                         As String) As String
    Dim objShell As New Shell32.Shell
    Dim objFolder As Shell32.Folder

'If you use 16384 instead of 1 on the next line,
'files are also displayed
    Set objFolder = objShell.BrowseForFolder _
                            (0, Title, 1, TopFolder)
    If Not objFolder Is Nothing Then
        SelectFolder = objFolder.Items.Item.Path
    End If
End Function

Source Link.

Excel 2010 VBA Referencing Specific Cells in other worksheets

I am going to give you a simplistic answer that hopefully will help you with VBA in general. The easiest way to learn how VBA works and how to reference and access elements is to record your macro then edit it in the VBA editor. This is how I learned VBA. It is based on visual basic so all the programming conventions of VB apply. Recording the macro lets you see how to access and do things.

you could use something like this:

var result = 0
Sheets("Sheet1").Select
result = Range("A1").Value * Range("B1").Value
Sheets("Sheet2").Select
Range("D1").Value = result

Alternatively you can also reference a cell using Cells(1,1).Value This way you can set variables and increment them as you wish. I think I am just not clear on exactly what you are trying to do but i hope this helps.

Find files in a folder using Java

  • Matcher.find and Files.walk methods could be an option to search files in more flexible way
  • String.format combines regular expressions to create search restrictions
  • Files.isRegularFile checks if a path is't directory, symbolic link, etc.

Usage:

//Searches file names (start with "temp" and extension ".txt")
//in the current directory and subdirectories recursively
Path initialPath = Paths.get(".");
PathUtils.searchRegularFilesStartsWith(initialPath, "temp", ".txt").
                                       stream().forEach(System.out::println);

Source:

public final class PathUtils {

    private static final String startsWithRegex = "(?<![_ \\-\\p{L}\\d\\[\\]\\(\\) ])";
    private static final String endsWithRegex = "(?=[\\.\\n])";
    private static final String containsRegex = "%s(?:[^\\/\\\\]*(?=((?i)%s(?!.))))";

    public static List<Path> searchRegularFilesStartsWith(final Path initialPath, 
                             final String fileName, final String fileExt) throws IOException {
        return searchRegularFiles(initialPath, startsWithRegex + fileName, fileExt);
    }

    public static List<Path> searchRegularFilesEndsWith(final Path initialPath, 
                             final String fileName, final String fileExt) throws IOException {
        return searchRegularFiles(initialPath, fileName + endsWithRegex, fileExt);
    }

    public static List<Path> searchRegularFilesAll(final Path initialPath) throws IOException {
        return searchRegularFiles(initialPath, "", "");
    }

    public static List<Path> searchRegularFiles(final Path initialPath,
                             final String fileName, final String fileExt)
            throws IOException {
        final String regex = String.format(containsRegex, fileName, fileExt);
        final Pattern pattern = Pattern.compile(regex);
        try (Stream<Path> walk = Files.walk(initialPath.toRealPath())) {
            return walk.filter(path -> Files.isRegularFile(path) &&
                                       pattern.matcher(path.toString()).find())
                    .collect(Collectors.toList());
        }
    }

    private PathUtils() {
    }
}

Try startsWith regex for \txt\temp\tempZERO0.txt:

(?<![_ \-\p{L}\d\[\]\(\) ])temp(?:[^\/\\]*(?=((?i)\.txt(?!.))))

Try endsWith regex for \txt\temp\ZERO0temp.txt:

temp(?=[\\.\\n])(?:[^\/\\]*(?=((?i)\.txt(?!.))))

Try contains regex for \txt\temp\tempZERO0tempZERO0temp.txt:

temp(?:[^\/\\]*(?=((?i)\.txt(?!.))))

Key existence check in HashMap

You can also use the computeIfAbsent() method in the HashMap class.

In the following example, map stores a list of transactions (integers) that are applied to the key (the name of the bank account). To add 2 transactions of 100 and 200 to checking_account you can write:

HashMap<String, ArrayList<Integer>> map = new HashMap<>();
map.computeIfAbsent("checking_account", key -> new ArrayList<>())
   .add(100)
   .add(200);

This way you don't have to check to see if the key checking_account exists or not.

  • If it does not exist, one will be created and returned by the lambda expression.
  • If it exists, then the value for the key will be returned by computeIfAbsent().

Really elegant!

How do I encode URI parameter values?

Mmhh I know you've already discarded URLEncoder, but despite of what the docs say, I decided to give it a try.

You said:

For example, given an input:

http://google.com/resource?key=value

I expect the output:

http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue

So:

C:\oreyes\samples\java\URL>type URLEncodeSample.java
import java.net.*;

public class URLEncodeSample {
    public static void main( String [] args ) throws Throwable {
        System.out.println( URLEncoder.encode( args[0], "UTF-8" ));
    }
}

C:\oreyes\samples\java\URL>javac URLEncodeSample.java

C:\oreyes\samples\java\URL>java URLEncodeSample "http://google.com/resource?key=value"
http%3A%2F%2Fgoogle.com%2Fresource%3Fkey%3Dvalue

As expected.

What would be the problem with this?

Clear a terminal screen for real

Compile this app.

#include <iostream>
#include <cstring>

int main()
{
  char str[1000];
  memset(str, '\n', 999);
  str[999] = 0;
  std::cout << str << std::endl;
  return 0;
}

How do I make the first letter of a string uppercase in JavaScript?

A one-liner:

_x000D_
_x000D_
'string'.replace(/(^[a-z])/,function (p) { return p.toUpperCase(); } )
_x000D_
_x000D_
_x000D_

How to concatenate strings in a Windows batch file?

What about:

@echo off
set myvar="the list: "
for /r %%i in (*.doc) DO call :concat %%i
echo %myvar%
goto :eof

:concat
set myvar=%myvar% %1;
goto :eof

Getting the source HTML of the current page from chrome extension

Inject a script into the page you want to get the source from and message it back to the popup....

manifest.json

{
  "name": "Get pages source",
  "version": "1.0",
  "manifest_version": 2,
  "description": "Get pages source from a popup",
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": ["tabs", "<all_urls>"]
}

popup.html

<!DOCTYPE html>
<html style=''>
<head>
<script src='popup.js'></script>
</head>
<body style="width:400px;">
<div id='message'>Injecting Script....</div>
</body>
</html>

popup.js

chrome.runtime.onMessage.addListener(function(request, sender) {
  if (request.action == "getSource") {
    message.innerText = request.source;
  }
});

function onWindowLoad() {

  var message = document.querySelector('#message');

  chrome.tabs.executeScript(null, {
    file: "getPagesSource.js"
  }, function() {
    // If you try and inject into an extensions page or the webstore/NTP you'll get an error
    if (chrome.runtime.lastError) {
      message.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
    }
  });

}

window.onload = onWindowLoad;

getPagesSource.js

// @author Rob W <http://stackoverflow.com/users/938089/rob-w>
// Demo: var serialized_html = DOMtoString(document);

function DOMtoString(document_root) {
    var html = '',
        node = document_root.firstChild;
    while (node) {
        switch (node.nodeType) {
        case Node.ELEMENT_NODE:
            html += node.outerHTML;
            break;
        case Node.TEXT_NODE:
            html += node.nodeValue;
            break;
        case Node.CDATA_SECTION_NODE:
            html += '<![CDATA[' + node.nodeValue + ']]>';
            break;
        case Node.COMMENT_NODE:
            html += '<!--' + node.nodeValue + '-->';
            break;
        case Node.DOCUMENT_TYPE_NODE:
            // (X)HTML documents are identified by public identifiers
            html += "<!DOCTYPE " + node.name + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' "' + node.systemId + '"' : '') + '>\n';
            break;
        }
        node = node.nextSibling;
    }
    return html;
}

chrome.runtime.sendMessage({
    action: "getSource",
    source: DOMtoString(document)
});

How to check if a list is empty in Python?

I like Zarembisty's answer. Although, if you want to be more explicit, you can always do:

if len(my_list) == 0:
    print "my_list is empty"

postgresql port confusion 5433 or 5432?

For me in PgAdmin 4 on Mac OS High Sierra, Clicking the PostrgreSQL10 database under Servers in the left column, then the Properties tab, showed 5433 as the port under Connection. (I don't know why, because I chose 5432 during install). Anyway, I clicked the Edit icon under the Properties tab, change that to 5432, saved, and that solved the problem. Go figure.

How to use LINQ Distinct() with multiple fields

Distinct method returns distinct elements from a sequence.

If you take a look on its implementation with Reflector, you'll see that it creates DistinctIterator for your anonymous type. Distinct iterator adds elements to Set when enumerating over collection. This enumerator skips all elements which are already in Set. Set uses GetHashCode and Equals methods for defining if element already exists in Set.

How GetHashCode and Equals implemented for anonymous type? As it stated on msdn:

Equals and GetHashCode methods on anonymous types are defined in terms of the Equals and GetHashcode methods of the properties, two instances of the same anonymous type are equal only if all their properties are equal.

So, you definitely should have distinct anonymous objects, when iterating on distinct collection. And result does not depend on how many fields you use for your anonymous type.

Why does dividing two int not yield the right value when assigned to double?

When you divide two integers, the result will be an integer, irrespective of the fact that you store it in a double.

How to use Python to login to a webpage and retrieve cookies for later usage?

import urllib, urllib2, cookielib

username = 'myuser'
password = 'mypassword'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()

resp.read() is the straight html of the page you want to open, and you can use opener to view any page using your session cookie.

Java: Converting String to and from ByteBuffer and associated problems

Check out the CharsetEncoder and CharsetDecoder API descriptions - You should follow a specific sequence of method calls to avoid this problem. For example, for CharsetEncoder:

  1. Reset the encoder via the reset method, unless it has not been used before;
  2. Invoke the encode method zero or more times, as long as additional input may be available, passing false for the endOfInput argument and filling the input buffer and flushing the output buffer between invocations;
  3. Invoke the encode method one final time, passing true for the endOfInput argument; and then
  4. Invoke the flush method so that the encoder can flush any internal state to the output buffer.

By the way, this is the same approach I am using for NIO although some of my colleagues are converting each char directly to a byte in the knowledge they are only using ASCII, which I can imagine is probably faster.

How to avoid annoying error "declared and not used"

I ran into this issue when I wanted to temporarily disable the sending of an email while working on another part of the code.

Commenting the use of the service triggered a lot of cascade errors, so instead of commenting I used a condition

if false {
    // Technically, svc still be used so no yelling
    _, err = svc.SendRawEmail(input) 
    Check(err)
}

IntelliJ IDEA JDK configuration on Mac OS

Just tried this recently and when trying to select the JDK... /System/Library/Java/JavaVirtualMachines/ appears as empty when opening&selecting through IntelliJ. Therefore i couldn't select the JDK...

I've found that to workaround this, when the finder windows open (pressing [+] JDK) just use the shortcut Shift + CMD + G to specify the path. (/System/Library/Java/JavaVirtualMachines/1.6.0.jdk in my case)

And voila, IntelliJ can find everything from that point on.

How can I get a precise time, for example in milliseconds in Objective-C?

CFAbsoluteTimeGetCurrent() returns the absolute time as a double value, but I don't know what its precision is -- it might only update every dozen milliseconds, or it might update every microsecond, I don't know.

How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp?

None of the answers so far explains how to download the various variants of that font so that you can serve them from your own website (WWW server).

While this might seem like a minor issue from the technical perspective, it is a big issue from the legal perspective, at least if you intend to present your pages to any EU citizen (or even, if you do that by accident). This is even true for companies which reside in the US (or any country outside the EU).

If anybody is interested why this is, I'll update this answer and give some more details here, but at the moment, I don't want to waste too much space off-topic.

Having said this:

I've downloaded all versions (regular, outlined, rounded, sharp, two-tone) of that font following two very easy steps (it was @Aj334's answer to his own question which put me on the right track) (example: "outlined" variant):

  1. Get the CSS from the Google CDN by directly letting your browser fetch the CSS URL, i.e. copy the following URL into your browser's location bar:

    https://fonts.googleapis.com/css?family=Material+Icons+Outlined
    

    This will return a page which looks like this (at least in Firefox 70.0.1 at the time of writing this):

    /* fallback */
    @font-face {
      font-family: 'Material Icons Outlined';
      font-style: normal;
      font-weight: 400;
      src: url(https://fonts.gstatic.com/s/materialiconsoutlined/v14/gok-H7zzDkdnRel8-DQ6KAXJ69wP1tGnf4ZGhUce.woff2) format('woff2');
    }
    
    .material-icons-outlined {
      font-family: 'Material Icons Outlined';
      font-weight: normal;
      font-style: normal;
      font-size: 24px;
      line-height: 1;
      letter-spacing: normal;
      text-transform: none;
      display: inline-block;
      white-space: nowrap;
      word-wrap: normal;
      direction: ltr;
      -moz-font-feature-settings: 'liga';
      -moz-osx-font-smoothing: grayscale;
    }
    
  2. Find the line starting with src: in the above code, and let your browser fetch the URL contained in that line, i.e. copy the following URL into your browser's location bar:

    https://fonts.gstatic.com/s/materialiconsoutlined/v14/gok-H7zzDkdnRel8-DQ6KAXJ69wP1tGnf4ZGhUce.woff2
    

    Now the browser will download that .woff2 file and offer to save it locally (at least, Firefox did).

Two final remarks:

Of course, you can download the other variants of that font using the same method. In the first step, just replace the character sequence Outlined in the URL by the character sequences Round (yes, really, although here it's called "Rounded" in the left navigation menu), Sharp or Two+Tone, respectively. The result page will look nearly the same each time, but the URL in the src: line of course is different for each variant.

Finally, in step 1, you even can use that URL:

https://fonts.googleapis.com/css?family=Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone|Material+Icons+Round|Material+Icons+Sharp

This will return the CSS for all variants in one page, which then contains five src: lines, each one with another URL designating where the respective font is located.

How to create directory automatically on SD card

File sdcard = Environment.getExternalStorageDirectory();
File f=new File(sdcard+"/dor");
f.mkdir();

this will create a folder named dor in your sdcard. then to fetch file for eg- filename.json which is manually inserted in dor folder. Like:

 File file1 = new File(sdcard,"/dor/fitness.json");
 .......
 .....

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

and don't forget to add code in manifest

AngularJS: ng-show / ng-hide not working with `{{ }}` interpolation

Try wrapping expression with:

$scope.$apply(function() {
   $scope.foo.bar=true;
})

ASP.NET MVC on IIS 7.5

Yet another reason this can happen - your RouteConfig.cs or WebApiConfig.cs are invalid.

In my case, I had a route defined as such (note the parenthesis instead of curly brace):

...
routeTemplate: "api/(something}"
...

Import a module from a relative path

In my opinion the best choice is to put __ init __.py in the folder and call the file with

from dirBar.Bar import *

It is not recommended to use sys.path.append() because something might gone wrong if you use the same file name as the existing python package. I haven't test that but that will be ambiguous.

Can you do a For Each Row loop using MySQL?

Not a for each exactly, but you can do nested SQL

SELECT 
    distinct a.ID, 
    a.col2, 
    (SELECT 
        SUM(b.size) 
    FROM 
        tableb b 
    WHERE 
        b.id = a.col3)
FROM
    tablea a

How to horizontally center an unordered list of unknown width?

One more solution:

#footer { display:table; margin:0 auto; }
#footer li { display:table-cell; padding: 0px 10px; }

Then ul doesn't jump to the next line in case of zooming text.

C++11 reverse range-based for-loop

Got this example from cppreference. It works with:

GCC 10.1+ with flag -std=c++20

#include <ranges>
#include <iostream>
 
int main()
{
    static constexpr auto il = {3, 1, 4, 1, 5, 9};
 
    std::ranges::reverse_view rv {il};
    for (int i : rv)
        std::cout << i << ' ';
 
    std::cout << '\n';
 
    for(int i : il | std::views::reverse)
        std::cout << i << ' ';
}

Safely turning a JSON string into an object

The easiest way using parse() method:

var response = '{"result":true,"count":1}';
var JsonObject= JSON.parse(response);

Then you can get the values of the JSON elements, for example:

var myResponseResult = JsonObject.result;
var myResponseCount = JsonObject.count;

Using jQuery as described in the jQuery.parseJSON() documentation:

JSON.parse(jsonString);

How to access ssis package variables inside script component

  • On the front properties page of the variable script, amend the ReadOnlyVariables (or ReadWriteVariables) property and select the variables you are interested in. This will enable the selected variables within the script task
  • Within code you will now have access to read the variable as

    string myString = Variables.MyVariableName.ToString();

How to include "zero" / "0" results in COUNT aggregate?

if you do the outer join (with the count), and then use this result as a sub-table, you can get 0 as expected (thanks to the nvl function)

Ex:

select P.person_id, nvl(A.nb_apptmts, 0) from 
(SELECT person.person_id
FROM person) P
LEFT JOIN 
(select person_id, count(*) as nb_apptmts
from appointment 
group by person_id) A
ON P.person_id = A.person_id

Removing spaces from string

String  input = EditTextinput.getText().toString();
input = input.replace(" ", "");

Sometimes you would want to remove only the spaces at the beginning or end of the String (not the ones in the middle). If that's the case you can use trim:

input = input.trim();

What is the proper declaration of main in C++?

Details on return values and their meaning

Per 3.6.1 ([basic.start.main]):

A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling std::exit with the return value as the argument. If control reaches the end of main without encountering a return statement, the effect is that of executing

return 0;

The behavior of std::exit is detailed in section 18.5 ([support.start.term]), and describes the status code:

Finally, control is returned to the host environment. If status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.

Multiplying Two Columns in SQL Server

select InitialPayment * MonthlyPayRate as SomeRandomCalculation from Payment

Get list of JSON objects with Spring RestTemplate

You can create POJO for each entry like,

class BitPay{
private String code;
private String name;
private double rate;
}

then using ParameterizedTypeReference of List of BitPay you can use as:

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<List<Employee>> response = restTemplate.exchange(
  "https://bitpay.com/api/rates",
  HttpMethod.GET,
  null,
  new ParameterizedTypeReference<List<BitPay>>(){});
List<Employee> employees = response.getBody();

Android replace the current fragment with another fragment

Then provided your button is showing and the click event is being fired you can call the following in your click event:

final FragmentTransaction ft = getFragmentManager().beginTransaction(); 
ft.replace(R.id.details, new NewFragmentToReplace(), "NewFragmentTag"); 
ft.commit(); 

and if you want to go back to the DetailsFragment on clicking back ensure you add the above transaction to the back stack, i.e.

ft.addToBackStack(null);

Or am I missing something? Alternatively some people suggest that your activity gets the click event for the button and it has responsibility for replacing the fragments in your details pane.

How do I check if a variable exists?

catch is called except in Python. other than that it's fine for such simple cases. There's the AttributeError that can be used to check if an object has an attribute.

What is the Swift equivalent of respondsToSelector?

The equivalent is the ? operator:

var value: NSNumber? = myQuestionableObject?.importantMethod()

importantMethod will only be called if myQuestionableObject exists and implements it.

Is a new line = \n OR \r\n?

If you are programming in PHP, it is useful to split lines by \n and then trim() each line (provided you don't care about whitespace) to give you a "clean" line regardless.

foreach($line in explode("\n", $data))
{
    $line = trim($line);
    ...
}

Converting file size in bytes to human-readable string

let bytes = 1024 * 10 * 10 * 10;

console.log(getReadableFileSizeString(bytes))

will return 1000.0?? instead of 1MB

How to allow only a number (digits and decimal point) to be typed in an input?

You could easily use the ng-pattern.

ng-pattern="/^[1-9][0-9]{0,2}(?:,?[0-9]{3}){0,3}(?:\.[0-9]{1,2})?$/"

cmake error 'the source does not appear to contain CMakeLists.txt'

Since you add .. after cmake, it will jump up and up (just like cd ..) in the directory. But if you want to run cmake under the same folder with CMakeLists.txt, please use . instead of ...

How to set different colors in HTML in one statement?

Use the span tag

<style>
    .redText
    {
        color:red;
    }
    .blackText
    {
        color:black;
        font-weight:bold;
    }
</style>

<span class="redText">My Name is:</span>&nbsp;<span class="blackText">Tintincute</span>

It's also a good idea to avoid inline styling. Use a custom CSS class instead.

Origin <origin> is not allowed by Access-Control-Allow-Origin

Since they are running on different ports, they are different JavaScript origin. It doesn't matter that they are on the same machine/hostname.

You need to enable CORS on the server (localhost:8080). Check out this site: http://enable-cors.org/

All you need to do is add an HTTP header to the server:

Access-Control-Allow-Origin: http://localhost:3000

Or, for simplicity:

Access-Control-Allow-Origin: *

Thought don't use "*" if your server is trying to set cookie and you use withCredentials = true

when responding to a credentialed request, server must specify a domain, and cannot use wild carding.

You can read more about withCredentials here

How to remove multiple indexes from a list at the same time?

You need to do this in a loop, there is no built-in operation to remove a number of indexes at once.

Your example is actually a contiguous sequence of indexes, so you can do this:

del my_list[2:6]

which removes the slice starting at 2 and ending just before 6.

It isn't clear from your question whether in general you need to remove an arbitrary collection of indexes, or if it will always be a contiguous sequence.

If you have an arbitrary collection of indexes, then:

indexes = [2, 3, 5]
for index in sorted(indexes, reverse=True):
    del my_list[index]

Note that you need to delete them in reverse order so that you don't throw off the subsequent indexes.

Generating random numbers in Objective-C

I thought I could add a method I use in many projects.

- (NSInteger)randomValueBetween:(NSInteger)min and:(NSInteger)max {
    return (NSInteger)(min + arc4random_uniform(max - min + 1));
}

If I end up using it in many files I usually declare a macro as

#define RAND_FROM_TO(min, max) (min + arc4random_uniform(max - min + 1))

E.g.

NSInteger myInteger = RAND_FROM_TO(0, 74) // 0, 1, 2,..., 73, 74

Note: Only for iOS 4.3/OS X v10.7 (Lion) and later

Google Map API - Removing Markers

According to Google documentation they said that this is the best way to do it. First create this function to find out how many markers there are/

   function setMapOnAll(map1) {
    for (var i = 0; i < markers.length; i++) {
      markers[i].setMap(map1);
    }
  }

Next create another function to take away all these markers

 function clearMarker(){
setMapOnAll(null);
}

Then create this final function to erase all the markers when ever this function is called upon.

 function delateMarkers(){
clearMarker()
markers = []
//console.log(markers) This is just if you want to

}

Hope that helped good luck

PHP: Split string

$string_val = 'a.b';

$parts = explode('.', $string_val);

print_r($parts);

Docs: http://us.php.net/manual/en/function.explode.php

segmentation fault : 11

Run your program with valgrind of linked to efence. That will tell you where the pointer is being dereferenced and most likely fix your problem if you fix all the errors they tell you about.

How do I display an alert dialog on Android?

Alert dialog with edit text

AlertDialog.Builder builder = new AlertDialog.Builder(context);//Context is activity context
final EditText input = new EditText(context);
builder.setTitle(getString(R.string.remove_item_dialog_title));
        builder.setMessage(getString(R.string.dialog_message_remove_item));
 builder.setTitle(getString(R.string.update_qty));
            builder.setMessage("");
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT);
            input.setLayoutParams(lp);
            input.setHint(getString(R.string.enter_qty));
            input.setTextColor(ContextCompat.getColor(context, R.color.textColor));
            input.setInputType(InputType.TYPE_CLASS_NUMBER);
            input.setText("String in edit text you want");
            builder.setView(input);
   builder.setPositiveButton(getString(android.R.string.ok),
                (dialog, which) -> {

//Positive button click event
  });

 builder.setNegativeButton(getString(android.R.string.cancel),
                (dialog, which) -> {
//Negative button click event
                });
        AlertDialog dialog = builder.create();
        dialog.show();

(413) Request Entity Too Large | uploadReadAheadSize

I was having the same issue with IIS 7.5 with a WCF REST Service. Trying to upload via POST any file above 65k and it would return Error 413 "Request Entity too large".

The first thing you need to understand is what kind of binding you've configured in the web.config. Here's a great article...

BasicHttpBinding vs WsHttpBinding vs WebHttpBinding

If you have a REST service then you need to configure it as "webHttpBinding". Here's the fix:

<system.serviceModel>

<bindings>
   <webHttpBinding>
    <binding 
      maxBufferPoolSize="2147483647" 
      maxReceivedMessageSize="2147483647" 
      maxBufferSize="2147483647" transferMode="Streamed">
    </binding>  
   </webHttpBinding>
</bindings>

Copy multiple files in Python

import os
import shutil
os.chdir('C:\\') #Make sure you add your source and destination path below

dir_src = ("C:\\foooo\\")
dir_dst = ("C:\\toooo\\")

for filename in os.listdir(dir_src):
    if filename.endswith('.txt'):
        shutil.copy( dir_src + filename, dir_dst)
    print(filename)

Using partial views in ASP.net MVC 4

Change the code where you load the partial view to:

@Html.Partial("_CreateNote", new QuickNotes.Models.Note())

This is because the partial view is expecting a Note but is getting passed the model of the parent view which is the IEnumerable

Git pull after forced update

To receive the new commits

git fetch

Reset

You can reset the commit for a local branch using git reset.

To change the commit of a local branch:

git reset origin/master --hard

Be careful though, as the documentation puts it:

Resets the index and working tree. Any changes to tracked files in the working tree since <commit> are discarded.

If you want to actually keep whatever changes you've got locally - do a --soft reset instead. Which will update the commit history for the branch, but not change any files in the working directory (and you can then commit them).

Rebase

You can replay your local commits on top of any other commit/branch using git rebase:

git rebase -i origin/master

This will invoke rebase in interactive mode where you can choose how to apply each individual commit that isn't in the history you are rebasing on top of.

If the commits you removed (with git push -f) have already been pulled into the local history, they will be listed as commits that will be reapplied - they would need to be deleted as part of the rebase or they will simply be re-included into the history for the branch - and reappear in the remote history on the next push.

Use the help git command --help for more details and examples on any of the above (or other) commands.

Get the distance between two geo points

private float getDistance(double lat1, double lon1, double lat2, double lon2) {
        float[] distance = new float[2];
        Location.distanceBetween(lat1, lon1, lat2, lon2, distance);
        return distance[0];
    }

Nested JSON: How to add (push) new items to an object?

library is an object, not an array. You push things onto arrays. Unlike PHP, Javascript makes a distinction.

Your code tries to make a string that looks like the source code for a key-value pair, and then "push" it onto the object. That's not even close to how it works.

What you want to do is add a new key-value pair to the object, where the key is the title and the value is another object. That looks like this:

library[title] = {"foregrounds" : foregrounds, "backgrounds" : backgrounds};

"JSON object" is a vague term. You must be careful to distinguish between an actual object in memory in your program, and a fragment of text that is in JSON format.

Command to collapse all sections of code?

If you mean shortcut then

CTRL + M + M: This one will collapse the region your cursor is at whether its a method, namespace or whatever for collapsing code blocks, regions and methods. The first will collapse only the block/method or region your cursor is at while the second will collapse the entire region you are at.

http://www.dev102.com/2008/05/06/11-more-visual-studio-shortcuts-you-should-know/

How to convert a string of numbers to an array of numbers?

You can use Array.map to convert each element into a number.

var a = "1,2,3,4";

var b = a.split(',').map(function(item) {
    return parseInt(item, 10);
});

Check the Docs


Or more elegantly as pointed out by User: thg435

var b = a.split(',').map(Number);

Where Number() would do the rest:check here


Note: For older browsers that don't support map, you can add an implementation yourself like:

Array.prototype.map = Array.prototype.map || function(_x) {
    for(var o=[], i=0; i<this.length; i++) { 
        o[i] = _x(this[i]); 
    }
    return o;
};

What's the @ in front of a string in C#?

The explanation is simple. To represent the string "string\", the compiler needs "string\\" because \ is an escape character. If you use @"string\" instead, you can forget about \\.

Equivalent of LIMIT for DB2

There are 2 solutions to paginate efficiently on a DB2 table :

1 - the technique using the function row_number() and the clause OVER which has been presented on another post ("SELECT row_number() OVER ( ORDER BY ... )"). On some big tables, I noticed sometimes a degradation of performances.

2 - the technique using a scrollable cursor. The implementation depends of the language used. That technique seems more robust on big tables.

I presented the 2 techniques implemented in PHP during a seminar next year. The slide is available on this link : http://gregphplab.com/serendipity/uploads/slides/DB2_PHP_Best_practices.pdf

Sorry but this document is only in french.

How to PUT a json object with an array using curl

Try using a single quote instead of double quotes along with -g

Following scenario worked for me

curl -g -d '{"collection":[{"NumberOfParcels":1,"Weight":1,"Length":1,"Width":1,"Height":1}]}" -H "Accept: application/json" -H "Content-Type: application/json" --user [email protected]:123456 -X POST  https://yoururl.com

WITH

curl -g -d "{'collection':[{'NumberOfParcels':1,'Weight':1,'Length':1,'Width':1,'Height':1}]}" -H "Accept: application/json" -H "Content-Type: application/json" --user [email protected]:123456 -X POST  https://yoururl.com

This especially resolved my error curl command error : bad url colon is first character

Deadly CORS when http://localhost is the origin

Quick and dirty Chrome extension fix:

Moesif Orign & CORS Changer

However, Chrome does support cross-origin requests from localhost. Make sure to add a header for Access-Control-Allow-Origin for localhost.

How to change an image on click using CSS alone?

This introduces a new paradigm to HTML/CSS, but using an <input readonly="true"> would allow you to append an input:focus selector to then alter the background-image

This of course would require applying specific CSS to the input itself to override browser defaults but it does go to show that click actions can indeed be triggered without the use of Javascript.

What is The Rule of Three?

Basically if you have a destructor (not the default destructor) it means that the class that you defined has some memory allocation. Suppose that the class is used outside by some client code or by you.

    MyClass x(a, b);
    MyClass y(c, d);
    x = y; // This is a shallow copy if assignment operator is not provided

If MyClass has only some primitive typed members a default assignment operator would work but if it has some pointer members and objects that do not have assignment operators the result would be unpredictable. Therefore we can say that if there is something to delete in destructor of a class, we might need a deep copy operator which means we should provide a copy constructor and assignment operator.

Apply style to cells of first row

Use tr:first-child to take the first tr:

.category_table tr:first-child td {
    vertical-align: top;
}

If you have nested tables, and you don't want to apply styles to the inner rows, add some child selectors so only the top-level tds in the first top-level tr get the styles:

.category_table > tbody > tr:first-child > td {
    vertical-align: top;
}

Bundler: Command not found

You need to add the ruby gem executable directory to your path

export PATH=$PATH:/opt/ruby-enterprise-1.8.7-2010.02/bin

AngularJS Error: $injector:unpr Unknown Provider

This error is also appears when one accidntally injects $scope into theirs factory:

angular.module('m', [])
    .factory('util', function ($scope) { // <-- this '$scope' gives 'Unknown provider' when one attempts to inject 'util'
       // ...
    });

Why does fatal error "LNK1104: cannot open file 'C:\Program.obj'" occur when I compile a C++ project in Visual Studio?

I had the same problem.It caused by a "," in the name of a folder of additional library path.It solved by changing the additional library path.

Can I set subject/content of email using mailto:?

The mailto: URL scheme is defined in RFC 2368. Also, the convention for encoding information into URLs and URIs is defined in RFC 1738 and then RFC 3986. These prescribe how to include the body and subject headers into a URL (URI):

mailto:[email protected]?subject=current-issue&body=send%20current-issue

Specifically, you must percent-encode the email address, subject, and body and put them into the format above. Percent-encoded text is legal for use in HTML, however this URL must be entity encoded for use in an href attribute, according to the HTML4 standard:

<a href="mailto:[email protected]?subject=current-issue&amp;body=send%20current-issue">Send email</a>

And most generally, here is a simple PHP script that encodes per the above.

<?php
$encodedTo = rawurlencode($message->to);
$encodedSubject = rawurlencode($message->subject);
$encodedBody = rawurlencode($message->body);
$uri = "mailto:$encodedTo?subject=$encodedSubject&body=$encodedBody";
$encodedUri = htmlspecialchars($uri);
echo "<a href=\"$encodedUri\">Send email</a>";
?>

MySQL: View with Subquery in the FROM Clause Limitation

I had the same problem. I wanted to create a view to show information of the most recent year, from a table with records from 2009 to 2011. Here's the original query:

SELECT a.* 
FROM a 
JOIN ( 
  SELECT a.alias, MAX(a.year) as max_year 
  FROM a 
  GROUP BY a.alias
) b 
ON a.alias=b.alias and a.year=b.max_year

Outline of solution:

  1. create a view for each subquery
  2. replace subqueries with those views

Here's the solution query:

CREATE VIEW v_max_year AS 
  SELECT alias, MAX(year) as max_year 
  FROM a 
  GROUP BY a.alias;

CREATE VIEW v_latest_info AS 
  SELECT a.* 
  FROM a 
  JOIN v_max_year b 
  ON a.alias=b.alias and a.year=b.max_year;

It works fine on mysql 5.0.45, without much of a speed penalty (compared to executing the original sub-query select without any views).