Programs & Examples On #M2eclipse

m2eclipse is a Plug-in for the Eclipse IDE that defines Eclipse Project structures by analyzing Maven Project models

web.xml is missing and <failOnMissingWebXml> is set to true

Create WEB-INF folder in src/webapp, and include web.xml page inside the WEB-INF folder then

How do I set the eclipse.ini -vm option?

-vm

C:\Program Files\Java\jdk1.5.0_06\bin\javaw.exe

Remember, no quotes, no matter if your path has spaces (as opposed to command line execution).

See here: Find the JRE for Eclipse

Maven2: Missing artifact but jars are in place

My case following procedure solve the issue

1- enter image description here

2- check the active profile enter image description here

m2eclipse error

I solved this by running mvn -U install from command line and then "Maven->Update Project" from Eclipse

How to solve maven 2.6 resource plugin dependency?

If a download fails for some reason Maven will not try to download it within a certain time frame (it leaves a file with a timestamp).

To fix this you can either

  • Clear (parts of) your .m2 repo
  • Run maven with -U to force an update

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

There is a documentation in SLf4J site to resolve this. I followed that and added slf4j-simple-1.6.1.jar to my aplication along with slf4j-api-1.6.1.jar which i already had.This solved my problem

slf4j

"Faceted Project Problem (Java Version Mismatch)" error message

I encountered this issue while running an app on Java 1.6 while I have all three versions of Java 6,7,8 for different apps.I accessed the Navigator View and manually removed the unwanted facet from the facet.core.xml .Clean build and wallah!

<?xml version="1.0" encoding="UTF-8"?>

<fixed facet="jst.java"/>

<fixed facet="jst.web"/>

<installed facet="jst.web" version="2.4"/>

<installed facet="jst.java" version="6.0"/>

<installed facet="jst.utility" version="1.0"/>

What causes imported Maven project in Eclipse to use Java 1.5 instead of Java 1.6 by default and how can I ensure it doesn't?

Here is the root cause of java 1.5:

Also note that at present the default source setting is 1.5 and the default target setting is 1.5, independently of the JDK you run Maven with. If you want to change these defaults, you should set source and target.

Reference : Apache Mavem Compiler Plugin

Following are the details:

Plain pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
             http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>

    <groupId>com.pluralsight</groupId>
    <artifactId>spring_sample</artifactId>
    <version>1.0-SNAPSHOT</version>

</project>

Following plugin is taken from an expanded POM version(Effective POM),

This can be get by this command from the command line C:\mvn help:effective-pom I just put here a small snippet instead of an entire pom.

    <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <executions>
      <execution>
        <id>default-compile</id>
        <phase>compile</phase>
        <goals>
          <goal>compile</goal>
        </goals>
      </execution>
      <execution>
        <id>default-testCompile</id>
        <phase>test-compile</phase>
        <goals>
          <goal>testCompile</goal>
        </goals>
      </execution>
    </executions>
  </plugin>

Even here you don't see where is the java version defined, lets dig more...

Download the plugin, Apache Maven Compiler Plugin » 3.1 as its available in jar and open it in any file compression tool like 7-zip

Traverse the jar and findout

plugin.xml

file inside folder

maven-compiler-plugin-3.1.jar\META-INF\maven\

Now you will see the following section in the file,

      <configuration>
    <basedir implementation="java.io.File" default-value="${basedir}"/>
    <buildDirectory implementation="java.io.File" default-value="${project.build.directory}"/>
    <classpathElements implementation="java.util.List" default-value="${project.testClasspathElements}"/>
    <compileSourceRoots implementation="java.util.List" default-value="${project.testCompileSourceRoots}"/>
    <compilerId implementation="java.lang.String" default-value="javac">${maven.compiler.compilerId}</compilerId>
    <compilerReuseStrategy implementation="java.lang.String" default-value="${reuseCreated}">${maven.compiler.compilerReuseStrategy}</compilerReuseStrategy>
    <compilerVersion implementation="java.lang.String">${maven.compiler.compilerVersion}</compilerVersion>
    <debug implementation="boolean" default-value="true">${maven.compiler.debug}</debug>
    <debuglevel implementation="java.lang.String">${maven.compiler.debuglevel}</debuglevel>
    <encoding implementation="java.lang.String" default-value="${project.build.sourceEncoding}">${encoding}</encoding>
    <executable implementation="java.lang.String">${maven.compiler.executable}</executable>
    <failOnError implementation="boolean" default-value="true">${maven.compiler.failOnError}</failOnError>
    <forceJavacCompilerUse implementation="boolean" default-value="false">${maven.compiler.forceJavacCompilerUse}</forceJavacCompilerUse>
    <fork implementation="boolean" default-value="false">${maven.compiler.fork}</fork>
    <generatedTestSourcesDirectory implementation="java.io.File" default-value="${project.build.directory}/generated-test-sources/test-annotations"/>
    <maxmem implementation="java.lang.String">${maven.compiler.maxmem}</maxmem>
    <meminitial implementation="java.lang.String">${maven.compiler.meminitial}</meminitial>
    <mojoExecution implementation="org.apache.maven.plugin.MojoExecution">${mojoExecution}</mojoExecution>
    <optimize implementation="boolean" default-value="false">${maven.compiler.optimize}</optimize>
    <outputDirectory implementation="java.io.File" default-value="${project.build.testOutputDirectory}"/>
    <showDeprecation implementation="boolean" default-value="false">${maven.compiler.showDeprecation}</showDeprecation>
    <showWarnings implementation="boolean" default-value="false">${maven.compiler.showWarnings}</showWarnings>
    <skip implementation="boolean">${maven.test.skip}</skip>
    <skipMultiThreadWarning implementation="boolean" default-value="false">${maven.compiler.skipMultiThreadWarning}</skipMultiThreadWarning>
    <source implementation="java.lang.String" default-value="1.5">${maven.compiler.source}</source>
    <staleMillis implementation="int" default-value="0">${lastModGranularityMs}</staleMillis>
    <target implementation="java.lang.String" default-value="1.5">${maven.compiler.target}</target>
    <testSource implementation="java.lang.String">${maven.compiler.testSource}</testSource>
    <testTarget implementation="java.lang.String">${maven.compiler.testTarget}</testTarget>
    <useIncrementalCompilation implementation="boolean" default-value="true">${maven.compiler.useIncrementalCompilation}</useIncrementalCompilation>
    <verbose implementation="boolean" default-value="false">${maven.compiler.verbose}</verbose>
    <mavenSession implementation="org.apache.maven.execution.MavenSession" default-value="${session}"/>
    <session implementation="org.apache.maven.execution.MavenSession" default-value="${session}"/>
  </configuration>

Look at the above code and find out the following 2 lines

    <source implementation="java.lang.String" default-value="1.5">${maven.compiler.source}</source>
    <target implementation="java.lang.String" default-value="1.5">${maven.compiler.target}</target>

Good luck.

m2eclipse not finding maven dependencies, artifacts not found

I had this issue for dependencies that were created in other projects. Downloaded thirdparty dependencies showed up fine in the build path, but not a library that I had created.

SOLUTION: In the project that is not building correctly, right-click on the project and choose Properties, and then Maven. Uncheck the box labeled "Resolve dependencies from Workspace projects", hit Apply, and then OK. Right-click again on your project and do a Maven->Update Snapshots (or Update Dependencies) and your errors should go away when your project rebuilds (automatically if you have auto-build enabled).

How to fix error "Updating Maven Project". Unsupported IClasspathEntry kind=4?

  1. Right-click on your project, select Maven -> Remove Maven Nature.

  2. Open you terminal, go to your project folder and do mvn eclipse:clean

  3. Right click on your Project and select “Configure -> Convert into Maven Project”

Now you got “Unsupported IClasspathEntry kind=4 Eclipse Scala” disappear.

Maven: best way of linking custom external JAR to my project?

update We have since just installed our own Nexus server, much easier and cleaner.

At our company we had some jars that we some jars that were common but were not hosted in any maven repositories, nor did we want to have them in local storage. We created a very simple mvn (public) repo on Github (but you can host it on any server or locally):
note that this is only ideal for managing a few rarely chaning jar files

  1. Create repo on GitHub:
    https://github.com/<user_name>/mvn-repo/

  2. Add Repository in pom.xml
    (Make note that the full path raw file will be a bit different than the repo name)

    <repository>
        <id>project-common</id>
        <name>Project Common</name>
        <url>https://github.com/<user_name>/mvn-repo/raw/master/</url>
    </repository>
    
  3. Add dependency to host (Github or private server)
    a. All you need to know is that files are stored in the pattern mentioned by @glitch
    /groupId/artifactId/version/artifactId-version.jar
    b. On your host create the folders to match this pattern.
    i.e if you have a jar file named service-sdk-0.0.1.jar, create the folder service-sdk/service-sdk/0.0.1/ and place the jar file service-sdk-0.0.1.jar into it.
    c. Test it by trying to download the jar from a browser (in our case: https://github.com/<user_name>/mvn-repo/raw/master/service-sdk/service-sdk/0.0.1/service-sdk-0.0.1.jar

  4. Add dependency to your pom.xml file:

    <dependency>
        <groupId>service-sdk</groupId>
        <artifactId>service-sdk</artifactId>
        <version>0.0.1</version>
    </dependency>
    
  5. Enjoy

Java compiler level does not match the version of the installed Java project facet

In Eclipse, right click on your project, go to Maven> Update projetc. Wait and the error will disappear. This is already configured correctly the version of Java for this project.

enter image description here

How to solve "Plugin execution not covered by lifecycle configuration" for Spring Data Maven Builds

I had this problem today. I was using STS 3.4 with its bundled Roo 1.2.4. Later I tried with Eclipse Kepler and Roo 1.2.5, same error.

I've changed my pom.xml adding pluginTemplates tag after build and before plugins declaration but didn't work.

What made the magic for me:

  • Using jdk 1.7.0_51
  • Downloaded Roo 1.2.5
  • Downloaded Maven 3.2.1 (if not, when executes "perform eclipse" this error appears "error=2, no such file or directory")
  • Configured JDK, Roo and Maven bin directories on my PATH:

    export PATH=/opt/jdk1.7.0_51/bin:$PATH export PATH=/opt/spring-roo-1.2.5.RELEASE/bin:$PATH export PATH=/opt/apache-maven-3.2.1/bin:$PATH

Made my configuration as following: (http://docs.spring.io/spring-roo/reference/html/beginning.html)

$ mkdir hello 
$ cd hello
$ roo.sh
roo> project --topLevelPackage com.foo
roo> jpa setup --provider HIBERNATE --database HYPERSONIC_PERSISTENT 
roo> web mvc setup
roo> perform eclipse

Open with Eclipse (nothing of STS, but I guess it works): Import -> Existing Projects into Workspace

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of its dependencies could not be resolved

I was getting the same issue.

I just installed the m2e (Maven2Eclipse)plugin from below site:

http://www.eclipse.org/m2e/

Eclipse>Help>Install New Software>Available Software Sites>Add

Name: m2e (any name is OK)
Location:m2e - http://download.eclipse.org/technology/m2e/releases/

Under Install Window> Work with:

Select this new location and Add all the plugins that appear. Eclipse restart and it was running properly with no previous errors.

An internal error occurred during: "Updating Maven Project". java.lang.NullPointerException

In case it helps anyone, in addition to deleting .settings and .project, I had to delete .classpath and .factorypath before being able to import the project successfully into Eclipse.

Missing Maven dependencies in Eclipse project

So I'm about 4 or 5 years late to this party, but I had this issue after pulling from our repo, and none of the other solutions from this thread worked out in my case to get rid of these warnings/errors.

This worked for me:

From Eclipse go to to Window -> Preferences -> Maven (expand) -> Errors/Warnings. The last option reads "Plugin execution not covered by lifecycle configuration" - use the drop-down menu for this option and toggle "Ignore", then Apply, then OK. (At "Requires updating Maven Projects" prompt say OK).

Further Info:

This may not necessarily "fix" the underlying issue(s), and may not qualify as "best practice" by some, however it should remove/supress these warnings from appearing in Eclipse and let you move forward at least. Specifically - I was working with Eclipse Luna Service Release 1 (4.4.1) w/ Spring Dashboard & Spring IDE Core (3.6.3), and m2e (1.5) installed, running on Arch Linux and OpenJDK 1.7. I imported my project as an existing maven project and selected OK when warned about existing warnings/errors (to deal with them later).

Suppress/Remove "Plugin Execution not covered..." warnings Eclipse-Maven

(Sorry, I'm not a designer, but added picture for clarity.)

Maven plugin in Eclipse - Settings.xml file is missing

The settings file is never created automatically, you must create it yourself, whether you use embedded or "real" maven.

Create it at the following location <your home folder>/.m2/settings.xml e.g. C:\Users\YourUserName\.m2\settings.xml on Windows or /home/YourUserName/.m2/settings.xml on Linux

Here's an empty skeleton you can use:

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <localRepository/>
  <interactiveMode/>
  <usePluginRegistry/>
  <offline/>
  <pluginGroups/>
  <servers/>
  <mirrors/>
  <proxies/>
  <profiles/>
  <activeProfiles/>
</settings>

If you use Eclipse to edit it, it will give you auto-completion when editing it.

And here's the Maven settings.xml Reference page

m2e lifecycle-mapping not found

Try using the build/pluginManagement section, e.g. :

<pluginManagement>
    <plugins>
        <plugin>
            <groupId>org.eclipse.m2e</groupId>
            <artifactId>lifecycle-mapping</artifactId>
            <version>1.0.0</version>
            <configuration>
                <lifecycleMappingMetadata>
                    <pluginExecutions>
                        <pluginExecution>
                            <pluginExecutionFilter>
                                <groupId>org.bsc.maven</groupId>
                                <artifactId>maven-processor-plugin</artifactId>
                                <versionRange>[2.0.2,)</versionRange>
                                <goals>
                                    <goal>process</goal>
                                </goals>
                            </pluginExecutionFilter>
                            <action>
                                <execute />
                            </action>
                        </pluginExecution>
                    </pluginExecutions>                         
                </lifecycleMappingMetadata>
            </configuration>
        </plugin>
    </plugins>
</pluginManagement>

Here's an example to generate bundle manifest during incremental compilation inside Eclipse :

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.eclipse.m2e</groupId>
                <artifactId>lifecycle-mapping</artifactId>
                <version>1.0.0</version>
                <configuration>
                    <lifecycleMappingMetadata>
                        <pluginExecutions>
                            <pluginExecution>
                                <pluginExecutionFilter>
                                    <groupId>org.apache.felix</groupId>
                                    <artifactId>maven-bundle-plugin</artifactId>
                                    <versionRange>[1.0.0,)</versionRange>
                                    <goals>
                                        <goal>manifest</goal>
                                    </goals>
                                </pluginExecutionFilter>
                                <action>
                                    <execute />
                                </action>
                            </pluginExecution>
                        </pluginExecutions>
                    </lifecycleMappingMetadata>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
                <encoding>UTF-8</encoding>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.felix</groupId>
            <artifactId>maven-bundle-plugin</artifactId>
            <version>2.3.7</version>
            <extensions>true</extensions>
            <configuration>
                <instructions>
                </instructions>
            </configuration>
            <executions>
                <execution>
                    <id>manifest</id>
                    <phase>process-classes</phase>
                    <goals>
                        <goal>manifest</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

versionRange is required, if omitted m2e (as of 1.1.0) will throw NullPointerException.

How to update maven repository in Eclipse?

Right-click on your project and choose Maven > Update Snapshots. In addition to that you can set "update Maven projects on startup" in Window > Preferences > Maven

UPDATE: In latest versions of Eclipse: Maven > Update Project. Make sure "Force Update of Snapshots/Releases" is checked.

How to configure Eclipse build path to use Maven dependencies?

I had a slight variation that caused some issues - multiple sub projects within one project. In this case I needed to go into each individual folder that contained a POM, execute the mvn eclipse:eclipse command and then manually copy/merge the classpath entries into my project classpath file.

An internal error occurred during: "Updating Maven Project". Unsupported IClasspathEntry kind=4

I had to do it slightly different to work for me:

  1. rightclick project, remove maven nature (or in newer eclipse, "Maven->Disable Maven Nature")
  2. mvn eclipse:clean (with project open in eclipse/STS)
  3. delete the project in eclipse (but do not delete the sources)
  4. Import existing Maven project

maven-dependency-plugin (goals "copy-dependencies", "unpack") is not supported by m2e

Despite answer from CaioToOn above, I still had problems getting this to work initially.

After multiple attempts, finally got it working. Am pasting my final version here - hoping it will benefit somebody else.

    <build> 
        <plugins>
            <!--
            Copy all Maven Dependencies (-MD) into libMD/ folder to use in classpath via shellscript
             --> 
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.8</version>
                <executions>
                    <execution>
                        <id>copy</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/libMD</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <!--  
        Above maven-dependepcy-plugin gives a validation error in m2e. 
        To fix that, add the plugin management step below. Per: http://stackoverflow.com/a/12109018
        -->
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.eclipse.m2e</groupId>
                    <artifactId>lifecycle-mapping</artifactId>
                    <version>1.0.0</version>
                    <configuration>
                        <lifecycleMappingMetadata>
                            <pluginExecutions>
                                <pluginExecution>
                                    <pluginExecutionFilter>
                                        <groupId>org.apache.maven.plugins</groupId>
                                        <artifactId>maven-dependency-plugin</artifactId>
                                        <versionRange>[2.0,)</versionRange>
                                        <goals>
                                            <goal>copy-dependencies</goal>
                                        </goals>
                                    </pluginExecutionFilter>
                                    <action>
                                        <execute />
                                    </action>
                                </pluginExecution>
                            </pluginExecutions>
                        </lifecycleMappingMetadata>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

Maven "build path specifies execution environment J2SE-1.5", even though I changed it to 1.7

When creating a maven project in eclipse, the build path is set to JDK 1.5 regardless of settings, which is probably a bug in new project or m2e.

Failed to resolve version for org.apache.maven.archetypes

I too had same problem but after searching solved this. go to menu --> window-->preferences-->maven-->Installations-->add--> in place of installation home add path to the directory in which you installed maven-->finish-->check the box of newly added content-->apply-->ok. now create new maven project but remember try with different group id and artifact id.

How to deal with missing src/test/java source folder in Android/Maven project?

This is a bug in the Android Connector for M2E (m2e-android) that was recently fixed:

https://github.com/rgladwell/m2e-android/commit/2b490f900153cd34fff1cec47fe5aeffabe44d87

This fix has been merged and will be available with the next release. In the meantime you can test the new fix by installing from the following update site:

http://rgladwell.github.com/m2e-android/updates/master/

No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

I tried most of the answers without success. What worked for me was (after following https://stackoverflow.com/a/21279068/2408893):

  • right click on project -> Properties
  • select Java Build Path
  • select the JRE System Library
  • click edit
  • In execution environment select a jdk

enter image description here

  • click Finish
  • build and run

Plugin execution not covered by lifecycle configuration (JBossas 7 EAR archetype)

You need to understand the content in M2E_plugin_execution_not_covered and follow the steps mentioned below:

  • Pick org.eclipse.m2e.lifecyclemapping.defaults jar from the eclipse plugin folder
  • Extract it and open lifecycle-mapping-metadata.xml where you can find all the pluginExecutions.
  • Add the pluginExecutions of your plugins which are shown as errors with <ignore/> under <action> tags.

eg: for write-project-properties error, add this snippet under the <pluginExecutions> section of the lifecycle-mapping-metadata.xml file:

 <pluginExecution>
    <pluginExecutionFilter>
       <groupId>org.codehaus.mojo</groupId>
       <artifactId>properties-maven-plugin</artifactId>
       <versionRange>1.0-alpha-2</versionRange>
       <goals>
         <goal>write-project-properties</goal>
       </goals>
    </pluginExecutionFilter>
     <action>
       <ignore />
     </action>
   </pluginExecution>
  • Replace that XML file in the JAR
  • Replace the updated JAR in Eclipse's plugin folder
  • Restart Eclipse

You should see no errors in the future for any project.

Compiler error "archive for required library could not be read" - Spring Tool Suite

Read the issue in Problems section,identify which dependency not able to read, then go the maven repository .m2\repository -> 1)check the dependencies and delete it from the folder 2)go to STS/Eclipse -> click on maven -> update project ->select the force update of snapshots/releases and click on ok.

or delete the dependencies from the .m2/repository and rebuild the maven --> update the maven project

How to reposition Chrome Developer Tools

As of october 2014, Version 39.0.2171.27 beta (64-bit)

I needed to go in the Chrome Web Developper pan into "Settings" and uncheck Split panels vertically when docked to right

How to make fixed header table inside scrollable div?

I think you need something like this ?

Like this

.....
<style>
.table{width: 500px;height: 200px;border-collapse:collapse;}
.table-wrap{max-height: 200px;width:100%;overflow-y:auto;overflow-x:hidden;}
.table-dalam{height:300px;width:500px;border-collapse:collapse;}
.td-nya{border-left:1px solid white;border-right:1px solid grey;border-bottom:1px solid    grey;}

</style>

<table class="table">
<thead>
    <tr>
    <th>Judul1</th>
    <th>Judul2</th>
    <th>Judul3</th>
    <th>Judul4</th>
   </tr>
 </thead>
 <tbody>
   <tr>
      <td colspan="4">
      <div class="table-wrap" >
      <table class="table-dalam">
         <tbody>
             <?php foreach(range(1,10) as $i): ?>
                 <tr >
                     <td class="td-nya">td1 </td>
                     <td class="td-nya">td2</td>
                     <td class="td-nya">td2</td>
                     <td class="td-nya">td2</td>
                 </tr> 
            <?php endforeach;?>
        </tbody>
       </table>
     </div>
   </td>
 </tr>
  </tbody>
 </table>

Source

Singletons vs. Application Context in Android?

From: Developer > reference - Application

There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.

Automatic prune with Git fetch or pull

Since git 1.8.5 (Q4 2013):

"git fetch" (hence "git pull" as well) learned to check "fetch.prune" and "remote.*.prune" configuration variables and to behave as if the "--prune" command line option was given.

That means that, if you set remote.origin.prune to true:

git config remote.origin.prune true

Any git fetch or git pull will automatically prune.

Note: Git 2.12 (Q1 2017) will fix a bug related to this configuration, which would make git remote rename misbehave.
See "How do I rename a git remote?".


See more at commit 737c5a9:

Without "git fetch --prune", remote-tracking branches for a branch the other side already has removed will stay forever.
Some people want to always run "git fetch --prune".

To accommodate users who want to either prune always or when fetching from a particular remote, add two new configuration variables "fetch.prune" and "remote.<name>.prune":

  • "fetch.prune" allows to enable prune for all fetch operations.
  • "remote.<name>.prune" allows to change the behaviour per remote.

The latter will naturally override the former, and the --[no-]prune option from the command line will override the configured default.

Since --prune is a potentially destructive operation (Git doesn't keep reflogs for deleted references yet), we don't want to prune without users consent, so this configuration will not be on by default.

Binding List<T> to DataGridView in WinForm

Yes, it is possible to do with out rebinding by implementing INotifyPropertyChanged Interface.

Pretty Simple example is available here,

http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx

No Activity found to handle Intent : android.intent.action.VIEW

If you are also getting this error when trying to open a web page from your android app it is because your url looks like this:

www.google.com

instead of: https://www.google.com or http://www.google.com

add this code to your Activity/Fragment:

 public void openWebPage(String url) {

    Uri webpage = Uri.parse(url);

    if (!url.startsWith("http://") && !url.startsWith("https://")) {
        webpage = Uri.parse("http://" + url);
    }

    Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

just pass your url to openWebPage(). If it is already prefixed with https:// or http:// then you are good to go, else the if statement handles that for you

Create Generic method constraining T to an Enum

Just for completeness, the following is a Java solution. I am certain the same could be done in C# as well. It avoids having to specify the type anywhere in code - instead, you specify it in the strings you are trying to parse.

The problem is that there isn't any way to know which enumeration the String might match - so the answer is to solve that problem.

Instead of accepting just the string value, accept a String that has both the enumeration and the value in the form "enumeration.value". Working code is below - requires Java 1.8 or later. This would also make the XML more precise as in you would see something like color="Color.red" instead of just color="red".

You would call the acceptEnumeratedValue() method with a string containing the enum name dot value name.

The method returns the formal enumerated value.

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;


public class EnumFromString {

    enum NumberEnum {One, Two, Three};
    enum LetterEnum {A, B, C};


    Map<String, Function<String, ? extends Enum>> enumsByName = new HashMap<>();

    public static void main(String[] args) {
        EnumFromString efs = new EnumFromString();

        System.out.print("\nFirst string is NumberEnum.Two - enum is " + efs.acceptEnumeratedValue("NumberEnum.Two").name());
        System.out.print("\nSecond string is LetterEnum.B - enum is " + efs.acceptEnumeratedValue("LetterEnum.B").name());

    }

    public EnumFromString() {
        enumsByName.put("NumberEnum", s -> {return NumberEnum.valueOf(s);});
        enumsByName.put("LetterEnum", s -> {return LetterEnum.valueOf(s);});
    }

    public Enum acceptEnumeratedValue(String enumDotValue) {

        int pos = enumDotValue.indexOf(".");

        String enumName = enumDotValue.substring(0, pos);
        String value = enumDotValue.substring(pos + 1);

        Enum enumeratedValue = enumsByName.get(enumName).apply(value);

        return enumeratedValue;
    }


}

Check synchronously if file/directory exists in Node.js

The documents on fs.stat() says to use fs.access() if you are not going to manipulate the file. It did not give a justification, might be faster or less memeory use?

I use node for linear automation, so I thought I share the function I use to test for file existence.

var fs = require("fs");

function exists(path){
    //Remember file access time will slow your program.
    try{
        fs.accessSync(path);
    } catch (err){
        return false;
    }
    return true;
}

Check if a value is in an array or not with Excel VBA

You can brute force it like this:

Public Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
    Dim i
    For i = LBound(arr) To UBound(arr)
        If arr(i) = stringToBeFound Then
            IsInArray = True
            Exit Function
        End If
    Next i
    IsInArray = False

End Function

Use like

IsInArray("example", Array("example", "someother text", "more things", "and another"))

Need to make a clickable <div> button

There are two solutions posted on that page. The one with lower votes I would recommend if possible.

If you are using HTML5 then it is perfectly valid to put a div inside of a. As long as the div doesn't also contain some other specific elements like other link tags.

<a href="Music.html">
  <div id="music" class="nav">
    Music I Like
  </div>
</a>

The solution you are confused about actually makes the link as big as its container div. To make it work in your example you just need to add position: relative to your div. You also have a small syntax error which is that you have given the span a class instead of an id. You also need to put your span inside the link because that is what the user is clicking on. I don't think you need the z-index at all from that example.

div { position: relative; }
.hyperspan {
    position:absolute;
    width:100%;
    height:100%;
    left:0;
    top:0;
}

<div id="music" class="nav">Music I Like 
    <a href="http://www.google.com"> 
        <span class="hyperspan"></span>
    </a>   
</div>

http://jsfiddle.net/rBKXM/9

When you give absolute positioning to an element it bases its location and size after the first parent it finds that is relatively positioned. If none, then it uses the document. By adding relative to the parent div you tell the span to only be as big as that.

Format cell color based on value in another sheet and cell

I've done this before with conditional formatting. It's a great way to visually inspect the cells in a workbook and spot the outliers in your data.

scipy.misc module has no attribute imread?

In case anyone encountering the same issue, please uninstall scipy and install scipy==1.1.0

$ pip uninstall scipy

$ pip install scipy==1.1.0

Adding default parameter value with type hint in Python

If you're using typing (introduced in Python 3.5) you can use typing.Optional, where Optional[X] is equivalent to Union[X, None]. It is used to signal that the explicit value of None is allowed . From typing.Optional:

def foo(arg: Optional[int] = None) -> None:
    ...

Facebook Android Generate Key Hash

If you are releasing, use the keystore you used to export your app with and not the debug.keystore.

How do I delete multiple rows in Entity Framework (without foreach)

EF 6.=>

var assignmentAddedContent = dbHazirBot.tbl_AssignmentAddedContent.Where(a =>
a.HazirBot_CategoryAssignmentID == categoryAssignment.HazirBot_CategoryAssignmentID);
dbHazirBot.tbl_AssignmentAddedContent.RemoveRange(assignmentAddedContent);
dbHazirBot.SaveChanges();

How to drop all stored procedures at once in SQL Server database?

I think this is the simplest way:

DECLARE @sql VARCHAR(MAX)='';

SELECT @sql=@sql+'drop procedure ['+name +'];' FROM sys.objects 
WHERE type = 'p' AND  is_ms_shipped = 0

exec(@sql);

Best Way to Refresh Adapter/ListView on Android

If you are using LoaderManager try with this statement:

getLoaderManager().restartLoader(0, null, this);

Rename multiple files in a folder, add a prefix (Windows)

Based on @ofer.sheffer answer this command will mass rename and append the current date to the filename. ie "file.txt" becomes "20180329 - file.txt" for all files in the current folder

for %a in (*.*) do ren "%a" "%date:~-4,4%%date:~-7,2%%date:~-10,2% - %a"

How to crop an image in OpenCV using Python

Note that, image slicing is not creating a copy of the cropped image but creating a pointer to the roi. If you are loading so many images, cropping the relevant parts of the images with slicing, then appending into a list, this might be a huge memory waste.

Suppose you load N images each is >1MP and you need only 100x100 region from the upper left corner.

Slicing:

X = []
for i in range(N):
    im = imread('image_i')
    X.append(im[0:100,0:100]) # This will keep all N images in the memory. 
                              # Because they are still used.

Alternatively, you can copy the relevant part by .copy(), so garbage collector will remove im.

X = []
for i in range(N):
    im = imread('image_i')
    X.append(im[0:100,0:100].copy()) # This will keep only the crops in the memory. 
                                     # im's will be deleted by gc.

After finding out this, I realized one of the comments by user1270710 mentioned that but it took me quite some time to find out (i.e., debugging etc). So, I think it worths mentioning.

Sum values in a column based on date

Use pivot tables, it will definitely save you time. If you are using excel 2007+ use tables (structured references) to keep your table dynamic. However if you insist on using functions, go with Smandoli's suggestion. Again, if you are on 2007+ use SUMIFS, it's faster compared to SUMIF.

Twitter Bootstrap - add top space between rows

Ok just to let you know what's happened then, i fixed using some new classes as Acyra says above:

.top5 { margin-top:5px; }
.top7 { margin-top:7px; }
.top10 { margin-top:10px; }
.top15 { margin-top:15px; }
.top17 { margin-top:17px; }
.top30 { margin-top:30px; }

whenever i want i do <div class="row top7"></div>

for better responsive you can add margin-top:7% instead of 5px for example :D

What is the best Java email address validation method?

Les Hazlewood has written a very thorough RFC 2822 compliant email validator class using Java regular expressions. You can find it at http://www.leshazlewood.com/?p=23. However, its thoroughness (or the Java RE implementation) leads to inefficiency - read the comments about parsing times for long addresses.

Return array in a function

to return an array from a function , let us define that array in a structure; So it looks something like this

struct Marks{
   int list[5];
}

Now let us create variables of the type structure.

typedef struct Marks marks;
marks marks_list;

We can pass array to a function in the following way and assign value to it:

void setMarks(int marks_array[]){
   for(int i=0;i<sizeof(marks_array)/sizeof(int);i++)
       marks_list.list[i]=marks_array[i];
}

We can also return the array. To return the array , the return type of the function should be of structure type ie marks. This is because in reality we are passing the structure that contains the array. So the final code may look like this.

marks getMarks(){
 return marks_list;
}

Merge r brings error "'by' must specify uniquely valid columns"

Rather give names of the column on which you want to merge:

exporttab <- merge(x=dwd_nogap, y=dwd_gap, by.x='x1', by.y='x2', fill=-9999)

How to set the id attribute of a HTML element dynamically with angularjs (1.x)?

You could just simply do the following

In your js

$scope.id = 0;

In your template

<div id="number-{{$scope.id}}"></div>

which will render

<div id="number-0"></div>

It is not necessary to concatenate inside double curly brackets.

How do I format date in jQuery datetimepicker?

Here you go.

$('#timePicker').datetimepicker({
   // dateFormat: 'dd-mm-yy',
   format:'DD/MM/YYYY HH:mm:ss',
    minDate: getFormattedDate(new Date())
});

function getFormattedDate(date) {
    var day = date.getDate();
    var month = date.getMonth() + 1;
    var year = date.getFullYear().toString().slice(2);
    return day + '-' + month + '-' + year;
}

You need to pass datepicker() the date formatted correctly.

How do I find the length (or dimensions, size) of a numpy matrix in python?

matrix.size according to the numpy docs returns the Number of elements in the array. Hope that helps.

Hash Table/Associative Array in VBA

I think you are looking for the Dictionary object, found in the Microsoft Scripting Runtime library. (Add a reference to your project from the Tools...References menu in the VBE.)

It pretty much works with any simple value that can fit in a variant (Keys can't be arrays, and trying to make them objects doesn't make much sense. See comment from @Nile below.):

Dim d As dictionary
Set d = New dictionary

d("x") = 42
d(42) = "forty-two"
d(CVErr(xlErrValue)) = "Excel #VALUE!"
Set d(101) = New Collection

You can also use the VBA Collection object if your needs are simpler and you just want string keys.

I don't know if either actually hashes on anything, so you might want to dig further if you need hashtable-like performance. (EDIT: Scripting.Dictionary does use a hash table internally.)

Changing one character in a string

Fastest method?

There are three ways. For the speed seekers I recommend 'Method 2'

Method 1

Given by this answer

text = 'abcdefg'
new = list(text)
new[6] = 'W'
''.join(new)

Which is pretty slow compared to 'Method 2'

timeit.timeit("text = 'abcdefg'; s = list(text); s[6] = 'W'; ''.join(s)", number=1000000)
1.0411581993103027

Method 2 (FAST METHOD)

Given by this answer

text = 'abcdefg'
text = text[:1] + 'Z' + text[2:]

Which is much faster:

timeit.timeit("text = 'abcdefg'; text = text[:1] + 'Z' + text[2:]", number=1000000)
0.34651994705200195

Method 3:

Byte array:

timeit.timeit("text = 'abcdefg'; s = bytearray(text); s[1] = 'Z'; str(s)", number=1000000)
1.0387420654296875

android: how to align image in the horizontal center of an imageview?

For me android:gravity="center" did the trick in the parent layout element.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/fullImageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:contentDescription="@string/fullImageView"
        android:layout_gravity="center" />

</LinearLayout>

How to iterate through SparseArray?

Ooor you just create your own ListIterator:

public final class SparseArrayIterator<E> implements ListIterator<E> {

private final SparseArray<E> array;
private int cursor;
private boolean cursorNowhere;

/**
 * @param array
 *            to iterate over.
 * @return A ListIterator on the elements of the SparseArray. The elements
 *         are iterated in the same order as they occur in the SparseArray.
 *         {@link #nextIndex()} and {@link #previousIndex()} return a
 *         SparseArray key, not an index! To get the index, call
 *         {@link android.util.SparseArray#indexOfKey(int)}.
 */
public static <E> ListIterator<E> iterate(SparseArray<E> array) {
    return iterateAt(array, -1);
}

/**
 * @param array
 *            to iterate over.
 * @param key
 *            to start the iteration at. {@link android.util.SparseArray#indexOfKey(int)}
 *            < 0 results in the same call as {@link #iterate(android.util.SparseArray)}.
 * @return A ListIterator on the elements of the SparseArray. The elements
 *         are iterated in the same order as they occur in the SparseArray.
 *         {@link #nextIndex()} and {@link #previousIndex()} return a
 *         SparseArray key, not an index! To get the index, call
 *         {@link android.util.SparseArray#indexOfKey(int)}.
 */
public static <E> ListIterator<E> iterateAtKey(SparseArray<E> array, int key) {
    return iterateAt(array, array.indexOfKey(key));
}

/**
 * @param array
 *            to iterate over.
 * @param location
 *            to start the iteration at. Value < 0 results in the same call
 *            as {@link #iterate(android.util.SparseArray)}. Value >
 *            {@link android.util.SparseArray#size()} set to that size.
 * @return A ListIterator on the elements of the SparseArray. The elements
 *         are iterated in the same order as they occur in the SparseArray.
 *         {@link #nextIndex()} and {@link #previousIndex()} return a
 *         SparseArray key, not an index! To get the index, call
 *         {@link android.util.SparseArray#indexOfKey(int)}.
 */
public static <E> ListIterator<E> iterateAt(SparseArray<E> array, int location) {
    return new SparseArrayIterator<E>(array, location);
}

private SparseArrayIterator(SparseArray<E> array, int location) {
    this.array = array;
    if (location < 0) {
        cursor = -1;
        cursorNowhere = true;
    } else if (location < array.size()) {
        cursor = location;
        cursorNowhere = false;
    } else {
        cursor = array.size() - 1;
        cursorNowhere = true;
    }
}

@Override
public boolean hasNext() {
    return cursor < array.size() - 1;
}

@Override
public boolean hasPrevious() {
    return cursorNowhere && cursor >= 0 || cursor > 0;
}

@Override
public int nextIndex() {
    if (hasNext()) {
        return array.keyAt(cursor + 1);
    } else {
        throw new NoSuchElementException();
    }
}

@Override
public int previousIndex() {
    if (hasPrevious()) {
        if (cursorNowhere) {
            return array.keyAt(cursor);
        } else {
            return array.keyAt(cursor - 1);
        }
    } else {
        throw new NoSuchElementException();
    }
}

@Override
public E next() {
    if (hasNext()) {
        if (cursorNowhere) {
            cursorNowhere = false;
        }
        cursor++;
        return array.valueAt(cursor);
    } else {
        throw new NoSuchElementException();
    }
}

@Override
public E previous() {
    if (hasPrevious()) {
        if (cursorNowhere) {
            cursorNowhere = false;
        } else {
            cursor--;
        }
        return array.valueAt(cursor);
    } else {
        throw new NoSuchElementException();
    }
}

@Override
public void add(E object) {
    throw new UnsupportedOperationException();
}

@Override
public void remove() {
    if (!cursorNowhere) {
        array.remove(array.keyAt(cursor));
        cursorNowhere = true;
        cursor--;
    } else {
        throw new IllegalStateException();
    }
}

@Override
public void set(E object) {
    if (!cursorNowhere) {
        array.setValueAt(cursor, object);
    } else {
        throw new IllegalStateException();
    }
}
}

How to modify existing XML file with XmlDocument and XmlNode in C#

You need to do something like this:

// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");

// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");

// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
   // grab the "id" attribute
   XmlAttribute idAttribute = aNode.Attributes["id"];

   // check if that attribute even exists...
   if (idAttribute != null)
   {
      // if yes - read its current value
      string currentValue = idAttribute.Value;

      // here, you can now decide what to do - for demo purposes,
      // I just set the ID value to a fixed value if it was empty before
      if (string.IsNullOrEmpty(currentValue))
      {
         idAttribute.Value = "515";
      }
   }
}

// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");

How to delete cookies on an ASP.NET website

Though this is an old thread, i thought if someone is still searching for solution in the future.

HttpCookie mycookie = new HttpCookie("aa");
mycookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(mycookie1);

Thats what did the trick for me.

Java escape JSON String?

The best method would be using some JSON library, e.g. Jackson ( http://jackson.codehaus.org ).

But if this is not an option simply escape msget before adding it to your string:

The wrong way to do this is

String msgetEscaped = msget.replaceAll("\"", "\\\"");

Either use (as recommended in the comments)

String msgetEscaped = msget.replace("\"", "\\\"");

or

String msgetEscaped = msget.replaceAll("\"", "\\\\\"");

A sample with all three variants can be found here: http://ideone.com/Nt1XzO

How to install libusb in Ubuntu

Usually to use the library you need to install the dev version.

Try

sudo apt-get install libusb-1.0-0-dev

Split long commands in multiple lines through Windows batch file

The rule for the caret is:

A caret at the line end, appends the next line, the first character of the appended line will be escaped.

You can use the caret multiple times, but the complete line must not exceed the maximum line length of ~8192 characters (Windows XP, Windows Vista, and Windows 7).

echo Test1
echo one ^
two ^
three ^
four^
*
--- Output ---
Test1
one two three four*

echo Test2
echo one & echo two
--- Output ---
Test2
one
two

echo Test3
echo one & ^
echo two
--- Output ---
Test3
one
two

echo Test4
echo one ^
& echo two
--- Output ---
Test4
one & echo two

To suppress the escaping of the next character you can use a redirection.

The redirection has to be just before the caret. But there exist one curiosity with redirection before the caret.

If you place a token at the caret the token is removed.

echo Test5
echo one <nul ^
& echo two
--- Output ---
Test5
one
two


echo Test6
echo one <nul ThisTokenIsLost^
& echo two
--- Output ---
Test6
one
two

And it is also possible to embed line feeds into the string:

setlocal EnableDelayedExpansion
set text=This creates ^

a line feed
echo Test7: %text%
echo Test8: !text!
--- Output ---
Test7: This creates
Test8: This creates
a line feed

The empty line is important for the success. This works only with delayed expansion, else the rest of the line is ignored after the line feed.

It works, because the caret at the line end ignores the next line feed and escapes the next character, even if the next character is also a line feed (carriage returns are always ignored in this phase).

HttpGet with HTTPS : SSLPeerUnverifiedException

Method returning a "secureClient" (in a Java 7 environnement - NetBeans IDE and GlassFish Server: port https by default 3920 ), hope this could help :

public DefaultHttpClient secureClient() {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    SSLSocketFactory sf;

    KeyStore trustStore;
    FileInputStream trustStream = null;
    File truststoreFile;
    // java.security.cert.PKIXParameters for the trustStore
    PKIXParameters pkixParamsTrust;

    KeyStore keyStore;
    FileInputStream keyStream = null;
    File keystoreFile;
    // java.security.cert.PKIXParameters for the keyStore
    PKIXParameters pkixParamsKey;

    try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        truststoreFile = new File(TRUSTSTORE_FILE);
        keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystoreFile = new File(KEYSTORE_FILE);
        try {
            trustStream = new FileInputStream(truststoreFile);
            keyStream = new FileInputStream(keystoreFile);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            trustStore.load(trustStream, PASSWORD.toCharArray());
            keyStore.load(keyStream, PASSWORD.toCharArray());
        } catch (IOException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (CertificateException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            pkixParamsTrust = new PKIXParameters(trustStore);
            // accepts Server certificate generated with keytool and (auto) signed by SUN
            pkixParamsTrust.setPolicyQualifiersRejected(false);
        } catch (InvalidAlgorithmParameterException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            pkixParamsKey = new PKIXParameters(keyStore);
            // accepts Client certificate generated with keytool and (auto) signed by SUN
            pkixParamsKey.setPolicyQualifiersRejected(false);
        } catch (InvalidAlgorithmParameterException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            sf = new SSLSocketFactory(trustStore);
            ClientConnectionManager manager = httpclient.getConnectionManager();
            manager.getSchemeRegistry().register(new Scheme("https", 3920, sf));
        } catch (KeyManagementException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnrecoverableKeyException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }

    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyStoreException ex) {
        Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
    }
    // use the httpclient for any httpRequest
    return httpclient;
}

How to do a SOAP Web Service call from Java class?

Or just use Apache CXF's wsdl2java to generate objects you can use.

It is included in the binary package you can download from their website. You can simply run a command like this:

$ ./wsdl2java -p com.mynamespace.for.the.api.objects -autoNameResolution http://www.someurl.com/DefaultWebService?wsdl

It uses the wsdl to generate objects, which you can use like this (object names are also grabbed from the wsdl, so yours will be different a little):

DefaultWebService defaultWebService = new DefaultWebService();
String res = defaultWebService.getDefaultWebServiceHttpSoap11Endpoint().login("webservice","dadsadasdasd");
System.out.println(res);

There is even a Maven plug-in which generates the sources: https://cxf.apache.org/docs/maven-cxf-codegen-plugin-wsdl-to-java.html

Note: If you generate sources using CXF and IDEA, you might want to look at this: https://stackoverflow.com/a/46812593/840315

Get css top value as number not as string?

You can use the parseInt() function to convert the string to a number, e.g:

parseInt($('#elem').css('top'));

Update: (as suggested by Ben): You should give the radix too:

parseInt($('#elem').css('top'), 10);

Forces it to be parsed as a decimal number, otherwise strings beginning with '0' might be parsed as an octal number (might depend on the browser used).

Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android

This problem occurs when you dont have the gradle wrapper into your SDK tools.

Like the previous responses said, you can update to last cordova-android version (it works), but if you want to keep working with [email protected] and [email protected], just copy the folder from android studio ex.;

cd /Applications/Android\ Studio.app/Contents/plugins/android/lib/
cp -r templates/ $ANDROID_HOME/tools/templates
chmod +x $ANDROID_HOME/tools/templates/gradle/wrapper/gradlew

In my case, I am using the cordova-plugin-fcm and it was tested with old version of cordova-android, so I can not use [email protected] (not yet).

Java IOException "Too many open files"

You're obviously not closing your file descriptors before opening new ones. Are you on windows or linux?

How to vertically align an image inside a div

http://jsfiddle.net/MBs64/

.frame {
    height: 35px;      /* Equals maximum image height */
    width: 160px;
    border: 1px solid red;
    text-align: center;
    margin: 1em 0;
    display: table-cell;
    vertical-align: middle;
}
img {
    background: #3A6F9A;
    display: block;
    max-height: 35px;
    max-width: 160px;
}

The key property is display: table-cell; for .frame. Div.frame is displayed as inline with this, so you need to wrap it in a block element.

This works in Firefox, Opera, Chrome, Safari and Internet Explorer 8 (and later).

UPDATE

For Internet Explorer 7 we need to add a CSS expression:

*:first-child+html img {
    position: relative;
    top: expression((this.parentNode.clientHeight-this.clientHeight)/2+"px");
}

Get the index of a certain value in an array in PHP

The problem is that you don't have a numerical index on your array.
Using array_values() will create a zero indexed array that you can then search using array_search() bypassing the need to use a for loop.

$list = ['string1', 'string2', 'string3'];
$index = array_search('string2',array_values($list));

How to convert a Kotlin source file to a Java source file

As @louis-cad mentioned "Kotlin source -> Java's byte code -> Java source" is the only solution so far.

But I would like to mention the way, which I prefer: using Jadx decompiler for Android.

It allows to see the generates code for closures and, as for me, resulting code is "cleaner" then one from IntelliJ IDEA decompiler.

Normally when I need to see Java source code of any Kotlin class I do:

  • Generate apk: ./gradlew assembleDebug
  • Open apk using Jadx GUI: jadx-gui ./app/build/outputs/apk/debug/app-debug.apk

In this GUI basic IDE functionality works: class search, click to go declaration. etc.

Also all the source code could be saved and then viewed using other tools like IntelliJ IDEA.

Javascript loading CSV file into an array

I highly recommend looking into this plugin:

http://github.com/evanplaice/jquery-csv/

I used this for a project handling large CSV files and it handles parsing a CSV into an array quite well. You can use this to call a local file that you specify in your code, also, so you are not dependent on a file upload.

Once you include the plugin above, you can essentially parse the CSV using the following:

$.ajax({
    url: "pathto/filename.csv",
    async: false,
    success: function (csvd) {
        data = $.csv.toArrays(csvd);
    },
    dataType: "text",
    complete: function () {
        // call a function on complete 
    }
});

Everything will then live in the array data for you to manipulate as you need. I can provide further examples for handling the array data if you need.

There are a lot of great examples available on the plugin page to do a variety of things, too.

How do I refresh a DIV content?

Complete working code would look like this:

<script> 
$(document).ready(function(){
setInterval(function(){
      $("#here").load(window.location.href + " #here" );
}, 3000);
});
</script>

<div id="here">dynamic content ?</div>

self reloading div container refreshing every 3 sec.

What is correct content-type for excel files?

Do keep in mind that the file.getContentType could also output application/octet-stream instead of the required application/vnd.openxmlformats-officedocument.spreadsheetml.sheet when you try to upload the file that is already open.

Getting value GET OR POST variable using JavaScript?

When i had the issue i saved the value into a hidden input:

in html body:

    <body>
    <?php 
    if (isset($_POST['Id'])){
      $fid= $_POST['Id']; 
    }
    ?>

... then put the hidden input on the page and write the value $fid with php echo

    <input type=hidden id ="fid" name=fid value="<?php echo $fid ?>">

then in $(document).ready( function () {

    var postId=document.getElementById("fid").value;

so i got my hidden url parameter in php an js.

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

I tried the steps here:

http://jyotirbhandari.blogspot.com/2011/09/java-error-invalidalgorithmparameterexc.html

And, that fixed the issue. I made some minor tweaks - I set the two parameters using System.getProperty...

Is there a performance difference between i++ and ++i in C?

Here's an additional observation if you're worried about micro optimisation. Decrementing loops can 'possibly' be more efficient than incrementing loops (depending on instruction set architecture e.g. ARM), given:

for (i = 0; i < 100; i++)

On each loop you you will have one instruction each for:

  1. Adding 1 to i.
  2. Compare whether i is less than a 100.
  3. A conditional branch if i is less than a 100.

Whereas a decrementing loop:

for (i = 100; i != 0; i--)

The loop will have an instruction for each of:

  1. Decrement i, setting the CPU register status flag.
  2. A conditional branch depending on CPU register status (Z==0).

Of course this works only when decrementing to zero!

Remembered from the ARM System Developer's Guide.

How to extract closed caption transcript from YouTube video?

Following document says only the owner of the channel can do this via standard youtube interface: https://developers.google.com/youtube/2.0/developers_guide_protocol_captions?hl=en

Cheap fix: You can click on the "interactive transscript" button - and copy the content this way. Of course you lose the milliseconds this way.

Extremely cheap fix: A shared youtube account - so that multiple people can edit and upload caption files.

Challenging solution: The youtube API allows downloading and uploading of caption files via HTTP... You may write a youtube API application to provide a browser user interface for uploading or downloading for ANY user or particular users.

Here is an example project for this in java http://apiblog.youtube.com/2011/01/youtube-captions-uploader-web-app.html

Here is very simple example of a working upload for everybody: http://yt-captions-uploader.appspot.com/

List of phone number country codes

Because nikolaDev's answer appeared to be useful, but incomplete and with some possible formatting errors, I put this list together using this Wikipedia page as the source for the data.

Wikipedia: https://en.wikipedia.org/wiki/List_of_mobile_telephone_prefixes_by_country

Full json file: List of mobile telephone prefixes by country (JSON formatted)

Angular 5 Scroll to top on every Route click

From Angular Version 6+ No need to use window.scroll(0,0)

For Angular version 6+ from @docs
Represents options to configure the router.

interface ExtraOptions {
  enableTracing?: boolean
  useHash?: boolean
  initialNavigation?: InitialNavigation
  errorHandler?: ErrorHandler
  preloadingStrategy?: any
  onSameUrlNavigation?: 'reload' | 'ignore'
  scrollPositionRestoration?: 'disabled' | 'enabled' | 'top'
  anchorScrolling?: 'disabled' | 'enabled'
  scrollOffset?: [number, number] | (() => [number, number])
  paramsInheritanceStrategy?: 'emptyOnly' | 'always'
  malformedUriErrorHandler?: (error: URIError, urlSerializer: UrlSerializer, url: string) => UrlTree
  urlUpdateStrategy?: 'deferred' | 'eager'
  relativeLinkResolution?: 'legacy' | 'corrected'
}

One can use scrollPositionRestoration?: 'disabled' | 'enabled' | 'top' in

Example:

RouterModule.forRoot(routes, {
    scrollPositionRestoration: 'enabled'|'top' 
});

And if one requires to manually control the scrolling, No need to use window.scroll(0,0) Instead from Angular V6 common package has introduced ViewPortScoller.

abstract class ViewportScroller {
  static ngInjectableDef: defineInjectable({ providedIn: 'root', factory: () => new BrowserViewportScroller(inject(DOCUMENT), window) })
  abstract setOffset(offset: [number, number] | (() => [number, number])): void
  abstract getScrollPosition(): [number, number]
  abstract scrollToPosition(position: [number, number]): void
  abstract scrollToAnchor(anchor: string): void
  abstract setHistoryScrollRestoration(scrollRestoration: 'auto' | 'manual'): void
}

Usage is pretty Straightforward Example:

import { Router } from '@angular/router';
import {  ViewportScroller } from '@angular/common'; //import
export class RouteService {

  private applicationInitialRoutes: Routes;
  constructor(
    private router: Router;
    private viewPortScroller: ViewportScroller//inject
  )
  {
   this.router.events.pipe(
            filter(event => event instanceof NavigationEnd))
            .subscribe(() => this.viewPortScroller.scrollToPosition([0, 0]));
}

How to print to console when using Qt

If you are printing to stderr using the stdio library, a call to fflush(stderr) should flush the buffer and get you real-time logging.

Nodejs convert string into UTF-8

When you want to change the encoding you always go from one into another. So you might go from Mac Roman to UTF-8 or from ASCII to UTF-8.

It's as important to know the desired output encoding as the current source encoding. For example if you have Mac Roman and you decode it from UTF-16 to UTF-8 you'll just make it garbled.

If you want to know more about encoding this article goes into a lot of details:

What Every Programmer Absolutely, Positively Needs To Know About Encodings And Character Sets To Work With Text

The npm pacakge encoding which uses node-iconv or iconv-lite should allow you to easily specify which source and output encoding you want:

var resultBuffer = encoding.convert(nameString, 'ASCII', 'UTF-8');

Java Round up Any Number

Assuming a as double and we need a rounded number with no decimal place . Use Math.round() function.
This goes as my solution .

double a = 0.99999;
int rounded_a = (int)Math.round(a);
System.out.println("a:"+rounded_a );

Output : 
a:1

How can I uninstall an application using PowerShell?

Here is the PowerShell script using msiexec:

echo "Getting product code"
$ProductCode = Get-WmiObject win32_product -Filter "Name='Name of my Software in Add Remove Program Window'" | Select-Object -Expand IdentifyingNumber
echo "removing Product"
# Out-Null argument is just for keeping the power shell command window waiting for msiexec command to finish else it moves to execute the next echo command
& msiexec /x $ProductCode | Out-Null
echo "uninstallation finished"

Setting format and value in input type="date"

Please check this https://stackoverflow.com/a/9519493/1074944 and try this way also $('input[type="date"]').datepicker().prop('type','text'); check the demo

How do I remove documents using Node.js Mongoose?

using remove() method you can able to remove.

getLogout(data){
        return this.sessionModel
        .remove({session_id: data.sid})
        .exec()
        .then(data =>{
            return "signup successfully"
        })
    }

How to exit a 'git status' list in a terminal?

:q

that's a less command, actually. It uses the same commands as vi.

Is there a way to link someone to a YouTube Video in HD 1080p quality?

To link to a YouTube video so it plays in HD by default, use the following URL:

https://www.youtube.com/v/VIDEOID?version=3&vq=hd1080

Change VIDEOID to the YouTube video ID that you want to link to. When someone follows the link, it will display the highest-resolution available (up to 1080p) in full-screen mode. Unfortunately, vq=hd1080 does not work on the normal YouTube site (with comments and related videos).

Override back button to act like home button

if it helps someone else, I had an activity with 2 layouts that I toggled on and off for visibilty, trying to emulate a kind of page1 > page2 structure. if they were on page 2 and pressed the back button I wanted them to go back to page 1, if they pressed the back button on page 1 it should still work as normal. Its pretty basic but it works

@Override
public void onBackPressed() {
// check if page 2 is open
    RelativeLayout page2layout = (RelativeLayout)findViewById(R.id.page2layout);
    if(page2layout.getVisibility() == View.VISIBLE){
        togglePageLayout(); // my method to toggle the views
        return;
    }else{
        super.onBackPressed(); // allows standard use of backbutton for page 1
    }

}

hope it helps someone, cheers

How do I compute the intersection point of two lines?

Can't stand aside,

So we have linear system:

A1 * x + B1 * y = C1
A2 * x + B2 * y = C2

let's do it with Cramer's rule, so solution can be found in determinants:

x = Dx/D
y = Dy/D

where D is main determinant of the system:

A1 B1
A2 B2

and Dx and Dy can be found from matricies:

C1 B1
C2 B2

and

A1 C1
A2 C2

(notice, as C column consequently substitues the coef. columns of x and y)

So now the python, for clarity for us, to not mess things up let's do mapping between math and python. We will use array L for storing our coefs A, B, C of the line equations and intestead of pretty x, y we'll have [0], [1], but anyway. Thus, what I wrote above will have the following form further in the code:

for D

L1[0] L1[1]
L2[0] L2[1]

for Dx

L1[2] L1[1]
L2[2] L2[1]

for Dy

L1[0] L1[2]
L2[0] L2[2]

Now go for coding:

line - produces coefs A, B, C of line equation by two points provided,
intersection - finds intersection point (if any) of two lines provided by coefs.

from __future__ import division 

def line(p1, p2):
    A = (p1[1] - p2[1])
    B = (p2[0] - p1[0])
    C = (p1[0]*p2[1] - p2[0]*p1[1])
    return A, B, -C

def intersection(L1, L2):
    D  = L1[0] * L2[1] - L1[1] * L2[0]
    Dx = L1[2] * L2[1] - L1[1] * L2[2]
    Dy = L1[0] * L2[2] - L1[2] * L2[0]
    if D != 0:
        x = Dx / D
        y = Dy / D
        return x,y
    else:
        return False

Usage example:

L1 = line([0,1], [2,3])
L2 = line([2,3], [0,4])

R = intersection(L1, L2)
if R:
    print "Intersection detected:", R
else:
    print "No single intersection point detected"

How to determine the Schemas inside an Oracle Data Pump Export file

The running the impdp command to produce an sqlfile, you will need to run it as a user which has the DATAPUMP_IMP_FULL_DATABASE role.

Or... run it as a low privileged user and use the MASTER_ONLY=YES option, then inspect the master table. e.g.

select value_t 
from SYS_IMPORT_TABLE_01 
where name = 'CLIENT_COMMAND' 
and process_order = -59;

col object_name for a30
col processing_status head STATUS for a6
col processing_state head STATE for a5
select distinct
  object_schema,
  object_name,
  object_type,
  object_tablespace,
  process_order,
  duplicate,
  processing_status,
  processing_state
from sys_import_table_01
where process_order > 0
and object_name is not null
order by object_schema, object_name
/

http://download.oracle.com/otndocs/products/database/enterprise_edition/utilities/pdf/oow2011_dp_mastering.pdf

How to pass arguments to addEventListener listener function?

If I'm not mistaken using calling the function with bind actually creates a new function that is returned by the bind method. This will cause you problems later or if you would like to remove the event listener, as it's basically like an anonymous function:

// Possible:
function myCallback() { /* code here */ }
someObject.addEventListener('event', myCallback);
someObject.removeEventListener('event', myCallback);

// Not Possible:
function myCallback() { /* code here */ }
someObject.addEventListener('event', function() { myCallback });
someObject.removeEventListener('event', /* can't remove anonymous function */);

So take that in mind.

If you are using ES6 you could do the same as suggested but a bit cleaner:

someObject.addEventListener('event', () => myCallback(params));

Get only the Date part of DateTime in mssql

We can use this method:

CONVERT(VARCHAR(10), GETDATE(), 120)

Last parameter changes the format to only to get time or date in specific formats.

How to set my default shell on Mac?

How to get the latest version of bash on modern macOS (tested on Mojave).

brew install bash
which bash | sudo tee -a /etc/shells
chsh -s $(which bash)

Then you are ready to get vim style tab completion which is only available on bash>=4 (current version in brew is 5.0.2

# If there are multiple matches for completion, Tab should cycle through them
bind 'TAB':menu-complete

# Display a list of the matching files
bind "set show-all-if-ambiguous on"

# Perform partial completion on the first Tab press,
# only start cycling full results on the second Tab press
bind "set menu-complete-display-prefix on"

Stop all active ajax requests in jQuery

I extended mkmurray and SpYk3HH answer above so that xhrPool.abortAll can abort all pending requests of a given url :

$.xhrPool = [];
$.xhrPool.abortAll = function(url) {
    $(this).each(function(i, jqXHR) { //  cycle through list of recorded connection
        console.log('xhrPool.abortAll ' + jqXHR.requestURL);
        if (!url || url === jqXHR.requestURL) {
            jqXHR.abort(); //  aborts connection
            $.xhrPool.splice(i, 1); //  removes from list by index
        }
    });
};
$.ajaxSetup({
    beforeSend: function(jqXHR) {
        $.xhrPool.push(jqXHR); //  add connection to list
    },
    complete: function(jqXHR) {
        var i = $.xhrPool.indexOf(jqXHR); //  get index for current connection completed
        if (i > -1) $.xhrPool.splice(i, 1); //  removes from list by index
    }
});
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
    console.log('ajaxPrefilter ' + options.url);
    jqXHR.requestURL = options.url;
});

Usage is same except that abortAll can now optionally accept a url as a parameter and will cancel only pending calls to that url

Add a user control to a wpf window

This is how I got it to work:

User Control WPF

<UserControl x:Class="App.ProcessView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>

    </Grid>
</UserControl>

User Control C#

namespace App {
    /// <summary>
    /// Interaction logic for ProcessView.xaml
    /// </summary>
    public partial class ProcessView : UserControl // My custom User Control
    {
        public ProcessView()
        {
            InitializeComponent();
        }
    } }

MainWindow WPF

<Window x:Name="RootWindow" x:Class="App.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:app="clr-namespace:App"
        Title="Some Title" Height="350" Width="525" Closing="Window_Closing_1" Icon="bouncer.ico">
    <Window.Resources>
        <app:DateConverter x:Key="dateConverter"/>
    </Window.Resources>
    <Grid>
        <ListView x:Name="listView" >
            <ListView.ItemTemplate>
                <DataTemplate>
                    <app:ProcessView />
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>
</Window>

Android Studio - No JVM Installation found

In my case

In Control Panel -> System -> Advanced system settings -> Environment Variables there is no JDK_HOME OR JAVA_HOME

SO

I added an entry named: JDK_HOME pointing to: C:\Program Files\Java\jdk1.8.0_25\ (you have to point this to your JDK instalation path)

And all seems to work fine now

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Be sure to remember to invoke json.loads() on the contents of the file, as opposed to the file path of that JSON:

json_file_path = "/path/to/example.json"

with open(json_file_path, 'r') as j:
     contents = json.loads(j.read())

I think a lot of people are guilty of doing this every once in a while (myself included):

contents = json.loads(json_file_path)

How to save final model using keras?

The model has a save method, which saves all the details necessary to reconstitute the model. An example from the keras documentation:

from keras.models import load_model

model.save('my_model.h5')  # creates a HDF5 file 'my_model.h5'
del model  # deletes the existing model

# returns a compiled model
# identical to the previous one
model = load_model('my_model.h5')

How to update value of a key in dictionary in c#?

Have you tried just

dictionary["cat"] = 5;

:)

Update

dictionary["cat"] = 5+2;
dictionary["cat"] = dictionary["cat"]+2;
dictionary["cat"] += 2;

Beware of non-existing keys :)

SQL Count for each date

When you cast a DateTime to an int it "truncates" at noon, you might want to strip the day out like so

cast(DATEADD(DAY, DATEDIFF(DAY, 0, created_date), 0) as int) as DayBucket

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in

use global scope on your $con and put it inside your getPosts() function like so.

function getPosts() {
global $con;
$query = mysqli_query($con,"SELECT * FROM Blog");
while($row = mysqli_fetch_array($query))
    {
        echo "<div class=\"blogsnippet\">";
        echo "<h4>" . $row['Title'] . "</h4>" . $row['SubHeading'];
        echo "</div>";
    }
}

Java: How can I compile an entire directory structure of code ?

You have to know all the directories, or be able to use wildcard ..

javac dir1/*.java dir2/*.java dir3/dir4/*.java dir3/dir5/*.java dir6/*src/*.java

SQL "select where not in subquery" returns no results

Table1 or Table2 has some null values for common_id. Use this query instead:

select *
from Common
where common_id not in (select common_id from Table1 where common_id is not null)
and common_id not in (select common_id from Table2 where common_id is not null)

View JSON file in Browser

json-ie.reg. for IE

try this url

http://www.jsonviewer.com/

Error:Execution failed for task ':app:transformClassesWithDexForDebug'

I solved it! It's a collection of configuration and update. Add these variables where they fit in build.gradle

android {
packagingOptions {
    exclude 'META-INF/ASL2.0'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/NOTICE'
}
dexOptions {
    javaMaxHeapSize "4g"
}
defaultConfig {
    multiDexEnabled true
}
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_7
    targetCompatibility JavaVersion.VERSION_1_7
}
}

Then update to Java 8 http://tecadmin.net/install-oracle-java-8-jdk-8-ubuntu-via-ppa/ and all will be solved! It's because of the buildTools update and new Android studio. Nothing else will fail.

How to find a whole word in a String in java

Use regex + word boundaries as others answered.

"I will come and meet you at the 123woods".matches(".*\\b123woods\\b.*");

will be true.

"I will come and meet you at the 123woods".matches(".*\\bwoods\\b.*");

will be false.

VBA Public Array : how to?

You are using the wrong type. The Array(...) function returns a Variant, not a String.

Thus, in the Declaration section of your module (it does not need to be a different module!), you define

Public colHeader As Variant

and somewhere at the beginning of your program code (for example, in the Workbook_Open event) you initialize it with

colHeader = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")

Another (simple) alternative would be to create a function that returns the array, e.g. something like

Public Function GetHeaders() As Variant
    GetHeaders = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")
End Function

This has the advantage that you do not need to initialize the global variable and the drawback that the array is created again on every function call.

How to render html with AngularJS templates

In angular 4+ we can use innerHTML property instead of ng-bind-html.

In my case, it's working and I am using angular 5.

<div class="chart-body" [innerHTML]="htmlContent"></div>

In.ts file

let htmlContent = 'This is the `<b>Bold</b>` text.';

Using a global variable with a thread

You just need to declare a as a global in thread2, so that you aren't modifying an a that is local to that function.

def thread2(threadname):
    global a
    while True:
        a += 1
        time.sleep(1)

In thread1, you don't need to do anything special, as long as you don't try to modify the value of a (which would create a local variable that shadows the global one; use global a if you need to)>

def thread1(threadname):
    #global a       # Optional if you treat a as read-only
    while a < 10:
        print a

How to create JSON string in C#

If you're trying to create a web service to serve data over JSON to a web page, consider using the ASP.NET Ajax toolkit:

http://www.asp.net/learn/ajax/tutorial-05-cs.aspx

It will automatically convert your objects served over a webservice to json, and create the proxy class that you can use to connect to it.

add elements to object array

You can't. However, you can replace the array with a new one which contains the extra element.

But it is easier and gives better performance to use an List<T> (uses interface IList) for this. List<T> does not resize the array every time you add an item - instead it doubles it when needed.

Try:

class Student
{
    IList<Subject> subjects = new List<Subject>();
}

class Subject
{
    string Name;
    string referenceBook;
}

Now you can say:

someStudent.subjects.Add(new Subject());

Find and replace words/lines in a file

You can use Java's Scanner class to parse words of a file and process them in your application, and then use a BufferedWriter or FileWriter to write back to the file, applying the changes.

I think there is a more efficient way of getting the iterator's position of the scanner at some point, in order to better implement editting. But since files are either open for reading, or writing, I'm not sure regarding that.

In any case, you can use libraries already available for parsing of XML files, which have all of this implemented already and will allow you to do what you want easily.

Date difference in years using C#

I found this at TimeSpan for years, months and days:

DateTime target_dob = THE_DOB;
DateTime true_age = DateTime.MinValue + ((TimeSpan)(DateTime.Now - target_dob )); // Minimum value as 1/1/1
int yr = true_age.Year - 1;

"Mixed content blocked" when running an HTTP AJAX operation in an HTTPS page

If you load a page in your browser using HTTPS, the browser will refuse to load any resources over HTTP. As you've tried, changing the API URL to have HTTPS instead of HTTP typically resolves this issue. However, your API must not allow for HTTPS connections. Because of this, you must either force HTTP on the main page or request that they allow HTTPS connections.

Note on this: The request will still work if you go to the API URL instead of attempting to load it with AJAX. This is because the browser is not loading a resource from within a secured page, instead it's loading an insecure page and it's accepting that. In order for it to be available through AJAX, though, the protocols should match.

Calculate percentage Javascript

For percent increase and decrease, using 2 different methods:

_x000D_
_x000D_
const a = 541
const b = 394

// Percent increase 
console.log(
  `Increase (from ${b} to ${a}) => `,
  (((a/b)-1) * 100).toFixed(2) + "%",
)

// Percent decrease
console.log(
  `Decrease (from ${a} to ${b}) => `,
  (((b/a)-1) * 100).toFixed(2) + "%",
)

// Alternatives, using .toLocaleString() 
console.log(
  `Increase (from ${b} to ${a}) => `,
  ((a/b)-1).toLocaleString('fullwide', {maximumFractionDigits:2, style:'percent'}),
)

console.log(
  `Decrease (from ${a} to ${b}) => `,
  ((b/a)-1).toLocaleString('fullwide', {maximumFractionDigits:2, style:'percent'}),
)
_x000D_
_x000D_
_x000D_

Calling a rest api with username and password - how to

Here is the solution for Rest API

class Program
{
    static void Main(string[] args)
    {
        BaseClient clientbase = new BaseClient("https://website.com/api/v2/", "username", "password");
        BaseResponse response = new BaseResponse();
        BaseResponse response = clientbase.GetCallV2Async("Candidate").Result;
    }


    public async Task<BaseResponse> GetCallAsync(string endpoint)
    {
        try
        {
            HttpResponseMessage response = await client.GetAsync(endpoint + "/").ConfigureAwait(false);
            if (response.IsSuccessStatusCode)
            {
                baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
                baseresponse.StatusCode = (int)response.StatusCode;
            }
            else
            {
                baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
                baseresponse.StatusCode = (int)response.StatusCode;
            }
            return baseresponse;
        }
        catch (Exception ex)
        {
            baseresponse.StatusCode = 0;
            baseresponse.ResponseMessage = (ex.Message ?? ex.InnerException.ToString());
        }
        return baseresponse;
    }
}


public class BaseResponse
{
    public int StatusCode { get; set; }
    public string ResponseMessage { get; set; }
}

public class BaseClient
{
    readonly HttpClient client;
    readonly BaseResponse baseresponse;

    public BaseClient(string baseAddress, string username, string password)
    {
        HttpClientHandler handler = new HttpClientHandler()
        {
            Proxy = new WebProxy("http://127.0.0.1:8888"),
            UseProxy = false,
        };

        client = new HttpClient(handler);
        client.BaseAddress = new Uri(baseAddress);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var byteArray = Encoding.ASCII.GetBytes(username + ":" + password);

        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

        baseresponse = new BaseResponse();

    }
}

What does "yield break;" do in C#?

Tells the iterator that it's reached the end.

As an example:

public interface INode
{
    IEnumerable<Node> GetChildren();
}

public class NodeWithTenChildren : INode
{
    private Node[] m_children = new Node[10];

    public IEnumerable<Node> GetChildren()
    {
        for( int n = 0; n < 10; ++n )
        {
            yield return m_children[ n ];
        }
    }
}

public class NodeWithNoChildren : INode
{
    public IEnumerable<Node> GetChildren()
    {
        yield break;
    }
}

Delete from a table based on date

or an ORACLE version:

delete
  from table_name
 where trunc(table_name.date) > to_date('01/01/2009','mm/dd/yyyy') 

Assign output of a program to a variable using a MS batch file

You could use a batch macro for simple capturing of command outputs, a bit like the behaviour of the bash shell.

The usage of the macro is simple and looks like

%$set% VAR=application arg1 arg2

And it works even with pipes

%$set% allDrives="wmic logicaldisk get name /value | findstr "Name""

The macro uses the variable like an array and stores each line in a separate index.
In the sample of %$set% allDrives="wmic logicaldisk there will the following variables created:

allDrives.Len=5
allDrives.Max=4
allDrives[0]=Name=C:
allDrives[1]=Name=D:
allDrives[2]=Name=F:
allDrives[3]=Name=G:
allDrives[4]=Name=Z:
allDrives=<contains the complete text with line feeds>

To use it, it's not important to understand how the macro itself works.

The full example

@echo off
setlocal

call :initMacro

%$set% ipOutput="ipconfig"
call :ShowVariable ipOutput
echo First line is %ipOutput[0]%

echo( 
%$set% driveNames="wmic logicaldisk get name /value | findstr "Name""
call :ShowVariable driveNames

exit /b

:ShowVariable
setlocal EnableDelayedExpansion
for /L %%n in (0 1 !%~1.max!) do (
    echo %%n: !%~1[%%n]!
)
echo(
exit /b

:initMacro
if "!!"=="" (
    echo ERROR: Delayed Expansion must be disabled while defining macros
    (goto) 2>nul
    (goto) 2>nul
)
(set LF=^
%=empty=%
)
(set \n=^^^
%=empty=%
)

set $set=FOR /L %%N in (1 1 2) dO IF %%N==2 ( %\n%
    setlocal EnableDelayedExpansion                                 %\n%
    for /f "tokens=1,* delims== " %%1 in ("!argv!") do (            %\n%
        endlocal                                                    %\n%
        endlocal                                                    %\n%
        set "%%~1.Len=0"                                            %\n%
        set "%%~1="                                                 %\n%
        if "!!"=="" (                                               %\n%
            %= Used if delayed expansion is enabled =%              %\n%
                setlocal DisableDelayedExpansion                    %\n%
                for /F "delims=" %%O in ('"%%~2 | findstr /N ^^"') do ( %\n%
                if "!!" NEQ "" (                                    %\n%
                    endlocal                                        %\n%
                    )                                               %\n%
                setlocal DisableDelayedExpansion                    %\n%
                set "line=%%O"                                      %\n%
                setlocal EnableDelayedExpansion                     %\n%
                set pathExt=:                                       %\n%
                set path=;                                          %\n%
                set "line=!line:^=^^!"                              %\n%
                set "line=!line:"=q"^""!"                           %\n%
                call set "line=%%line:^!=q""^!%%"                   %\n%
                set "line=!line:q""=^!"                             %\n%
                set "line="!line:*:=!""                             %\n%
                for /F %%C in ("!%%~1.Len!") do (                   %\n%
                    FOR /F "delims=" %%L in ("!line!") Do (         %\n%
                        endlocal                                    %\n%
                        endlocal                                    %\n%
                        set "%%~1[%%C]=%%~L" !                      %\n%
                        if %%C == 0 (                               %\n%
                            set "%%~1=%%~L" !                       %\n%
                        ) ELSE (                                    %\n%
                            set "%%~1=!%%~1!!LF!%%~L" !             %\n%
                        )                                           %\n%
                    )                                               %\n%
                    set /a %%~1.Len+=1                              %\n%
                )                                                   %\n%
            )                                                       %\n%
        ) ELSE (                                                    %\n%
            %= Used if delayed expansion is disabled =%             %\n%
            for /F "delims=" %%O in ('"%%~2 | findstr /N ^^"') do ( %\n%
                setlocal DisableDelayedExpansion                    %\n%
                set "line=%%O"                                      %\n%
                setlocal EnableDelayedExpansion                     %\n%
                set "line="!line:*:=!""                             %\n%
                for /F %%C in ("!%%~1.Len!") DO (                   %\n%
                    FOR /F "delims=" %%L in ("!line!") DO (         %\n%
                        endlocal                                    %\n%
                        endlocal                                    %\n%
                        set "%%~1[%%C]=%%~L"                        %\n%
                    )                                               %\n%
                    set /a %%~1.Len+=1                              %\n%
                )                                                   %\n%
            )                                                       %\n%
        )                                                           %\n%
        set /a %%~1.Max=%%~1.Len-1                                  %\n%
)                                                                   %\n%
    ) else setlocal DisableDelayedExpansion^&set argv=

goto :eof

Why do 64-bit DLLs go to System32 and 32-bit DLLs to SysWoW64 on 64-bit Windows?

Ran into the same issue and researched this for a few minutes.

I was taught to use Windows 3.1 and DOS, remember those days? Shortly after I worked with Macintosh computers strictly for some time, then began to sway back to Windows after buying a x64-bit machine.

There are actual reasons behind these changes (some would say historical significance), that are necessary for programmers to continue their work.

Most of the changes are mentioned above:

  • Program Files vs Program Files (x86)

    In the beginning the 16/86bit files were written on, '86' Intel processors.

  • System32 really means System64 (on 64-bit Windows)

    When developers first started working with Windows7, there were several compatibility issues where other applications where stored.

  • SysWOW64 really means SysWOW32

    Essentially, in plain english, it means 'Windows on Windows within a 64-bit machine'. Each folder is indicating where the DLLs are located for applications it they wish to use them.

Here are two links with all the basic info you need:

Hope this clears things up!

jQuery AJAX submit form

You can also use FormData (But not available in IE):

var formData = new FormData(document.getElementsByName('yourForm')[0]);// yourForm: form selector        
$.ajax({
    type: "POST",
    url: "yourURL",// where you wanna post
    data: formData,
    processData: false,
    contentType: false,
    error: function(jqXHR, textStatus, errorMessage) {
        console.log(errorMessage); // Optional
    },
    success: function(data) {console.log(data)} 
});

This is how you use FormData.

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

This function is not made to be used for the English language. I translated the words in English. This needs more fixing before using for English.

function ago($d) {
$ts = time() - strtotime(str_replace("-","/",$d));

        if($ts>315360000) $val = round($ts/31536000,0).' year';
        else if($ts>94608000) $val = round($ts/31536000,0).' years';
        else if($ts>63072000) $val = ' two years';
        else if($ts>31536000) $val = ' a year';

        else if($ts>24192000) $val = round($ts/2419200,0).' month';
        else if($ts>7257600) $val = round($ts/2419200,0).' months';
        else if($ts>4838400) $val = ' two months';
        else if($ts>2419200) $val = ' a month';


        else if($ts>6048000) $val = round($ts/604800,0).' week';
        else if($ts>1814400) $val = round($ts/604800,0).' weeks';
        else if($ts>1209600) $val = ' two weeks';
        else if($ts>604800) $val = ' a week';

        else if($ts>864000) $val = round($ts/86400,0).' day';
        else if($ts>259200) $val = round($ts/86400,0).' days';
        else if($ts>172800) $val = ' two days';
        else if($ts>86400) $val = ' a day';

        else if($ts>36000) $val = round($ts/3600,0).' year';
        else if($ts>10800) $val = round($ts/3600,0).' years';
        else if($ts>7200) $val = ' two years';
        else if($ts>3600) $val = ' a year';

        else if($ts>600) $val = round($ts/60,0).' minute';
        else if($ts>180) $val = round($ts/60,0).' minutes';
        else if($ts>120) $val = ' two minutes';
        else if($ts>60) $val = ' a minute';

        else if($ts>10) $val = round($ts,0).' second';
        else if($ts>2) $val = round($ts,0).' seconds';
        else if($ts>1) $val = ' two seconds';
        else $val = $ts.' a second';


        return $val;
    }

Is there a way to break a list into columns?

The mobile-first way is to use CSS Columns to create an experience for smaller screens then use Media Queries to increase the number of columns at each of your layout's defined breakpoints.

_x000D_
_x000D_
ul {_x000D_
  column-count: 2;_x000D_
  column-gap: 2rem;_x000D_
}_x000D_
@media screen and (min-width: 768px)) {_x000D_
  ul {_x000D_
    column-count: 3;_x000D_
    column-gap: 5rem;_x000D_
  }_x000D_
}
_x000D_
<ul>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Android: how to hide ActionBar on certain activities

Replace AndroidManifest.xml

android:theme="@style/FullscreenTheme"

to

android:theme="@style/Theme.Design.NoActionBar"

Bootstrap 3: Offset isn't working?

Which version of bootstrap are you using? The early versions of Bootstrap 3 (3.0, 3.0.1) didn't work with this functionality.

col-md-offset-0 should be working as seen in this bootstrap example found here (http://getbootstrap.com/css/#grid-responsive-resets):

<div class="row">
   <div class="col-sm-5 col-md-6">.col-sm-5 .col-md-6</div>
   <div class="col-sm-5 col-sm-offset-2 col-md-6 col-md-offset-0">.col-sm-5 .col-sm-offset-2 .col-md-6 .col-md-offset-0</div>
</div>

Unique Key constraints for multiple columns in Entity Framework

I assume you always want EntityId to be the primary key, so replacing it by a composite key is not an option (if only because composite keys are far more complicated to work with and because it is not very sensible to have primary keys that also have meaning in the business logic).

The least you should do is create a unique key on both fields in the database and specifically check for unique key violation exceptions when saving changes.

Additionally you could (should) check for unique values before saving changes. The best way to do that is by an Any() query, because it minimizes the amount of transferred data:

if (context.Entities.Any(e => e.FirstColumn == value1 
                           && e.SecondColumn == value2))
{
    // deal with duplicate values here.
}

Beware that this check alone is never enough. There is always some latency between the check and the actual commit, so you'll always need the unique constraint + exception handling.

How do I reset a sequence in Oracle?

Here's a more robust procedure for altering the next value returned by a sequence, plus a whole lot more.

  • First off it protects against SQL injection attacks since none of the strings passed in are used to directly create any of the dynamic SQL statements,
  • Second it prevents the next sequence value from being set outside the bounds of the min or max sequence values. The next_value will be != min_value and between min_value and max_value.
  • Third it takes the current (or proposed) increment_by setting as well as all the other sequence settings into account when cleaning up.
  • Fourth all parameters except the first are optional and unless specified take on the current sequence setting as defaults. If no optional parameters are specified no action is taken.
  • Finally if you try altering a sequence that doesn't exist (or is not owned by the current user) it will raise an ORA-01403: no data found error.

Here's the code:

CREATE OR REPLACE PROCEDURE alter_sequence(
    seq_name      user_sequences.sequence_name%TYPE
  , next_value    user_sequences.last_number%TYPE := null
  , increment_by  user_sequences.increment_by%TYPE := null
  , min_value     user_sequences.min_value%TYPE := null
  , max_value     user_sequences.max_value%TYPE := null
  , cycle_flag    user_sequences.cycle_flag%TYPE := null
  , cache_size    user_sequences.cache_size%TYPE := null
  , order_flag    user_sequences.order_flag%TYPE := null)
  AUTHID CURRENT_USER
AS
  l_seq user_sequences%rowtype;
  l_old_cache user_sequences.cache_size%TYPE;
  l_next user_sequences.min_value%TYPE;
BEGIN
  -- Get current sequence settings as defaults
  SELECT * INTO l_seq FROM user_sequences WHERE sequence_name = seq_name;

  -- Update target settings
  l_old_cache := l_seq.cache_size;
  l_seq.increment_by := nvl(increment_by, l_seq.increment_by);
  l_seq.min_value    := nvl(min_value, l_seq.min_value);
  l_seq.max_value    := nvl(max_value, l_seq.max_value);
  l_seq.cycle_flag   := nvl(cycle_flag, l_seq.cycle_flag);
  l_seq.cache_size   := nvl(cache_size, l_seq.cache_size);
  l_seq.order_flag   := nvl(order_flag, l_seq.order_flag);

  IF next_value is NOT NULL THEN
    -- Determine next value without exceeding limits
    l_next := LEAST(GREATEST(next_value, l_seq.min_value+1),l_seq.max_value);

    -- Grab the actual latest seq number
    EXECUTE IMMEDIATE
        'ALTER SEQUENCE '||l_seq.sequence_name
            || ' INCREMENT BY 1'
            || ' MINVALUE '||least(l_seq.min_value,l_seq.last_number-l_old_cache)
            || ' MAXVALUE '||greatest(l_seq.max_value,l_seq.last_number)
            || ' NOCACHE'
            || ' ORDER';
    EXECUTE IMMEDIATE 
      'SELECT '||l_seq.sequence_name||'.NEXTVAL FROM DUAL'
    INTO l_seq.last_number;

    l_next := l_next-l_seq.last_number-1;

    -- Reset the sequence number
    IF l_next <> 0 THEN
      EXECUTE IMMEDIATE 
        'ALTER SEQUENCE '||l_seq.sequence_name
            || ' INCREMENT BY '||l_next
            || ' MINVALUE '||least(l_seq.min_value,l_seq.last_number)
            || ' MAXVALUE '||greatest(l_seq.max_value,l_seq.last_number)
            || ' NOCACHE'
            || ' ORDER';
      EXECUTE IMMEDIATE 
        'SELECT '||l_seq.sequence_name||'.NEXTVAL FROM DUAL'
      INTO l_next;
    END IF;
  END IF;

  -- Prepare Sequence for next use.
  IF COALESCE( cycle_flag
             , next_value
             , increment_by
             , min_value
             , max_value
             , cache_size
             , order_flag) IS NOT NULL
  THEN
    EXECUTE IMMEDIATE 
      'ALTER SEQUENCE '||l_seq.sequence_name
          || ' INCREMENT BY '||l_seq.increment_by
          || ' MINVALUE '||l_seq.min_value
          || ' MAXVALUE '||l_seq.max_value
          || CASE l_seq.cycle_flag
             WHEN 'Y' THEN ' CYCLE' ELSE ' NOCYCLE' END
          || CASE l_seq.cache_size
             WHEN 0 THEN ' NOCACHE'
             ELSE ' CACHE '||l_seq.cache_size END
          || CASE l_seq.order_flag
             WHEN 'Y' THEN ' ORDER' ELSE ' NOORDER' END;
  END IF;
END;

Java NIO: What does IOException: Broken pipe mean?

Broken pipe simply means that the connection has failed. It is reasonable to assume that this is unrecoverable, and to then perform any required cleanup actions (closing connections, etc). I don't believe that you would ever see this simply due to the connection not yet being complete.

If you are using non-blocking mode then the SocketChannel.connect method will return false, and you will need to use the isConnectionPending and finishConnect methods to insure that the connection is complete. I would generally code based upon the expectation that things will work, and then catch exceptions to detect failure, rather than relying on frequent calls to "isConnected".

DateTime.TryParse issue with dates of yyyy-dd-MM format

If you give the user the opportunity to change the date/time format, then you'll have to create a corresponding format string to use for parsing. If you know the possible date formats (i.e. the user has to select from a list), then this is much easier because you can create those format strings at compile time.

If you let the user do free-format design of the date/time format, then you'll have to create the corresponding DateTime format strings at runtime.

Splitting a string at every n-th character

import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        for (String part : getParts("foobarspam", 3)) {
            System.out.println(part);
        }
    }
    private static List<String> getParts(String string, int partitionSize) {
        List<String> parts = new ArrayList<String>();
        int len = string.length();
        for (int i=0; i<len; i+=partitionSize)
        {
            parts.add(string.substring(i, Math.min(len, i + partitionSize)));
        }
        return parts;
    }
}

How to view UTF-8 Characters in VIM or Gvim

this work for me and do not need change any config file

vim --cmd "set encoding=utf8" --cmd "set fileencoding=utf8" fileToOpen

Best way to implement multi-language/globalization in large .NET project

+1 Database

Forms in your app can even re-translate themselves on the fly if corrections are made to the database.

We used a system where all the controls were mapped in an XML file (one per form) to language resource IDs, but all the IDs were in the database.

Basically, instead of having each control hold the ID (implementing an interface, or using the tag property in VB6), we used the fact that in .NET, the control tree was easily discoverable through reflection. A process when the form loaded would build the XML file if it was missing. The XML file would map the controls to their resource IDs, so this simply needed to be filled in and mapped to the database. This meant that there was no need to change the compiled binary if something was not tagged, or if it needed to be split to another ID (some words in English which might be used as both nouns and verbs might need to translate to two different words in the dictionary and not be re-used, but you might not discover this during initial assignment of IDs). But the fact is that the whole translation process becomes completely independent of your binary (every form has to inherit from a base form which knows how to translate itself and all its controls).

The only ones where the app gets more involved is when a phase with insertion points is used.

The database translation software was your basic CRUD maintenance screen with various workflow options to facilitate going through the missing translations, etc.

How do I prevent and/or handle a StackOverflowException?

I would suggest creating a wrapper around XmlWriter object, so it would count amount of calls to WriteStartElement/WriteEndElement, and if you limit amount of tags to some number (f.e. 100), you would be able to throw a different exception, for example - InvalidOperation.

That should solve the problem in the majority of the cases

public class LimitedDepthXmlWriter : XmlWriter
{
    private readonly XmlWriter _innerWriter;
    private readonly int _maxDepth;
    private int _depth;

    public LimitedDepthXmlWriter(XmlWriter innerWriter): this(innerWriter, 100)
    {
    }

    public LimitedDepthXmlWriter(XmlWriter innerWriter, int maxDepth)
    {
        _maxDepth = maxDepth;
        _innerWriter = innerWriter;
    }

    public override void Close()
    {
        _innerWriter.Close();
    }

    public override void Flush()
    {
        _innerWriter.Flush();
    }

    public override string LookupPrefix(string ns)
    {
        return _innerWriter.LookupPrefix(ns);
    }

    public override void WriteBase64(byte[] buffer, int index, int count)
    {
        _innerWriter.WriteBase64(buffer, index, count);
    }

    public override void WriteCData(string text)
    {
        _innerWriter.WriteCData(text);
    }

    public override void WriteCharEntity(char ch)
    {
        _innerWriter.WriteCharEntity(ch);
    }

    public override void WriteChars(char[] buffer, int index, int count)
    {
        _innerWriter.WriteChars(buffer, index, count);
    }

    public override void WriteComment(string text)
    {
        _innerWriter.WriteComment(text);
    }

    public override void WriteDocType(string name, string pubid, string sysid, string subset)
    {
        _innerWriter.WriteDocType(name, pubid, sysid, subset);
    }

    public override void WriteEndAttribute()
    {
        _innerWriter.WriteEndAttribute();
    }

    public override void WriteEndDocument()
    {
        _innerWriter.WriteEndDocument();
    }

    public override void WriteEndElement()
    {
        _depth--;

        _innerWriter.WriteEndElement();
    }

    public override void WriteEntityRef(string name)
    {
        _innerWriter.WriteEntityRef(name);
    }

    public override void WriteFullEndElement()
    {
        _innerWriter.WriteFullEndElement();
    }

    public override void WriteProcessingInstruction(string name, string text)
    {
        _innerWriter.WriteProcessingInstruction(name, text);
    }

    public override void WriteRaw(string data)
    {
        _innerWriter.WriteRaw(data);
    }

    public override void WriteRaw(char[] buffer, int index, int count)
    {
        _innerWriter.WriteRaw(buffer, index, count);
    }

    public override void WriteStartAttribute(string prefix, string localName, string ns)
    {
        _innerWriter.WriteStartAttribute(prefix, localName, ns);
    }

    public override void WriteStartDocument(bool standalone)
    {
        _innerWriter.WriteStartDocument(standalone);
    }

    public override void WriteStartDocument()
    {
        _innerWriter.WriteStartDocument();
    }

    public override void WriteStartElement(string prefix, string localName, string ns)
    {
        if (_depth++ > _maxDepth) ThrowException();

        _innerWriter.WriteStartElement(prefix, localName, ns);
    }

    public override WriteState WriteState
    {
        get { return _innerWriter.WriteState; }
    }

    public override void WriteString(string text)
    {
        _innerWriter.WriteString(text);
    }

    public override void WriteSurrogateCharEntity(char lowChar, char highChar)
    {
        _innerWriter.WriteSurrogateCharEntity(lowChar, highChar);
    }

    public override void WriteWhitespace(string ws)
    {
        _innerWriter.WriteWhitespace(ws);
    }

    private void ThrowException()
    {
        throw new InvalidOperationException(string.Format("Result xml has more than {0} nested tags. It is possible that xslt transformation contains an endless recursive call.", _maxDepth));
    }
}

FPDF utf-8 encoding (HOW-TO)

just edit the function cell in the fpdf.php file, look for the line that looks like this

function cell ($w, $h = 0, $txt = '', $border = 0, $ln = 0, $align = '', $fill = false, $link = '')
{ 

after finding the line

write after the {,

$txt = utf8_decode($txt);

save the file and ready, the accents and the utf8 encoding will be working :)

How to force browser to download file?

This is from a php script which solves the problem perfectly with every browser I've tested (FF since 3.5, IE8+, Chrome)

header("Content-Disposition: attachment; filename=\"".$fname_local."\"");
header("Content-Type: application/force-download");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($fname));

So as far as I can see, you're doing everything correctly. Have you checked your browser settings?

Check if input is number or letter javascript

Use Regular Expression to match for only letters. It's also good to have knowledge about, if you ever need to do something more complicated, like make sure it's a certain count of numbers.

function checkInp()
{
    var x=document.forms["myForm"]["age"].value;
    var regex=/^[a-zA-Z]+$/;
    if (!x.match(regex))
    {
        alert("Must input string");
        return false;
    }
}

Even better would be to deny anything but numbers:

function checkInp()
{
    var x=document.forms["myForm"]["age"].value;
    var regex=/^[0-9]+$/;
    if (x.match(regex))
    {
        alert("Must input numbers");
        return false;
    }
}

Running stages in parallel with Jenkins workflow / pipeline

As @Quartz mentioned, you can do something like

stage('Tests') {
    parallel(
        'Unit Tests': {
            container('node') {
                sh("npm test --cat=unit")
            }
        },
        'API Tests': {
            container('node') {
                sh("npm test --cat=acceptance")
            }
        }
    )
}

input type=file show only button

Resolved with the following code:

<div style="overflow: hidden;width:83px;"> <input style='float:right;' name="userfile" id="userfile" type="file"/> </div>

How to find difference between two columns data?

There are many ways of doing this (and I encourage you to look them up as they will be more efficient generally) but the simplest way of doing this is to use a non-set operation to define the value of the third column:

SELECT
    t1.previous
    ,t1.present
    ,(t1.present - t1.previous) as difference
FROM #TEMP1 t1

Note, this style of selection is considered bad practice because it requires the query plan to reselect the value of the first two columns to logically determine the third (a violation of set theory that SQL is based on). Though it is more complicated, if you plan on using this to evaluate more than the values you listed in your example, I would investigate using an APPLY clause. http://technet.microsoft.com/en-us/library/ms175156(v=sql.105).aspx

Inherit CSS class

As others have already mentioned, there is no concept of OOP inheritance in CSS. But, i have always used a work around for this.

Let's say i have two buttons, and except the background image URL, all other attributes are common. This is how i did it.

/*button specific attributes*/
.button1 {
    background-image: url("../Images/button1.gif");
}
/*button specific attributes*/
.button2 {
    background-image: url("../Images/button2.gif");
}

/*These are the shared attributes */
.button1, .button2 {
    cursor: pointer;
    background-repeat: no-repeat;
    width: 25px;
    height: 20px;
    border: 0;
}

Hope this helps somebody.

How to "pull" from a local branch into another one?

If you are looking for a brand new pull from another branch like from local to master you can follow this.

git commit -m "Initial Commit"
git add .
git pull --rebase git_url
git push origin master

#1227 - Access denied; you need (at least one of) the SUPER privilege(s) for this operation

In case you are uploading an sql file on cpanel, then try and replace root with your cpanel username in your sql file.

in the case above you could write

CREATE DEFINER = control_panel_username@localhost FUNCTION fnc_calcWalkedDistance

then upload the file. Hope it helps

How to verify that a specific method was not called using Mockito?

Even more meaningful :

import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;

// ...

verify(dependency, never()).someMethod();

The documentation of this feature is there §4 "Verifying exact number of invocations / at least x / never", and the never javadoc is here.

Spaces cause split in path with PowerShell

  1. enter the root C drive by entering command

C:

  1. type cd and then press Tab key, it will toggle through all available locations and press enter when you have reached the desired one

cd {press tab}

How to check if a number is between two values?

It's an old question, however might be useful for someone like me.

lodash has _.inRange() function https://lodash.com/docs/4.17.4#inRange

Example:

_.inRange(3, 2, 4);
// => true

Please note that this method utilizes the Lodash utility library, and requires access to an installed version of Lodash.

Increment a value in Postgres

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill';

If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill'
  AND total = 203;

How to display all methods of an object?

You can use Object.getOwnPropertyNames() to get all properties that belong to an object, whether enumerable or not. For example:

console.log(Object.getOwnPropertyNames(Math));
//-> ["E", "LN10", "LN2", "LOG2E", "LOG10E", "PI", ...etc ]

You can then use filter() to obtain only the methods:

console.log(Object.getOwnPropertyNames(Math).filter(function (p) {
    return typeof Math[p] === 'function';
}));
//-> ["random", "abs", "acos", "asin", "atan", "ceil", "cos", "exp", ...etc ]

In ES3 browsers (IE 8 and lower), the properties of built-in objects aren't enumerable. Objects like window and document aren't built-in, they're defined by the browser and most likely enumerable by design.

From ECMA-262 Edition 3:

Global Object
There is a unique global object (15.1), which is created before control enters any execution context. Initially the global object has the following properties:

• Built-in objects such as Math, String, Date, parseInt, etc. These have attributes { DontEnum }.
• Additional host defined properties. This may include a property whose value is the global object itself; for example, in the HTML document object model the window property of the global object is the global object itself.

As control enters execution contexts, and as ECMAScript code is executed, additional properties may be added to the global object and the initial properties may be changed.

I should point out that this means those objects aren't enumerable properties of the Global object. If you look through the rest of the specification document, you will see most of the built-in properties and methods of these objects have the { DontEnum } attribute set on them.


Update: a fellow SO user, CMS, brought an IE bug regarding { DontEnum } to my attention.

Instead of checking the DontEnum attribute, [Microsoft] JScript will skip over any property in any object where there is a same-named property in the object's prototype chain that has the attribute DontEnum.

In short, beware when naming your object properties. If there is a built-in prototype property or method with the same name then IE will skip over it when using a for...in loop.

Java split string to array

Try this

String[] array = values.split("\\|",-1); 

Get the IP Address of local computer

You can use gethostname followed by gethostbyname to get your local interface internal IP.

This returned IP may be different from your external IP though. To get your external IP you would have to communicate with an external server that will tell you what your external IP is. Because the external IP is not yours but it is your routers.

//Example: b1 == 192, b2 == 168, b3 == 0, b4 == 100
struct IPv4
{
    unsigned char b1, b2, b3, b4;
};

bool getMyIP(IPv4 & myIP)
{
    char szBuffer[1024];

    #ifdef WIN32
    WSADATA wsaData;
    WORD wVersionRequested = MAKEWORD(2, 0);
    if(::WSAStartup(wVersionRequested, &wsaData) != 0)
        return false;
    #endif


    if(gethostname(szBuffer, sizeof(szBuffer)) == SOCKET_ERROR)
    {
      #ifdef WIN32
      WSACleanup();
      #endif
      return false;
    }

    struct hostent *host = gethostbyname(szBuffer);
    if(host == NULL)
    {
      #ifdef WIN32
      WSACleanup();
      #endif
      return false;
    }

    //Obtain the computer's IP
    myIP.b1 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b1;
    myIP.b2 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b2;
    myIP.b3 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b3;
    myIP.b4 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b4;

    #ifdef WIN32
    WSACleanup();
    #endif
    return true;
}

You can also always just use 127.0.0.1 which represents the local machine always.

Subnet mask in Windows:

You can get the subnet mask (and gateway and other info) by querying subkeys of this registry entry:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces

Look for the registry value SubnetMask.

Other methods to get interface information in Windows:

You could also retrieve the information you're looking for by using: WSAIoctl with this option: SIO_GET_INTERFACE_LIST

How do I set the classpath in NetBeans?

  1. Right-click your Project.
  2. Select Properties.
  3. On the left-hand side click Libraries.
  4. Under Compile tab - click Add Jar/Folder button.

Or

  1. Expand your Project.
  2. Right-click Libraries.
  3. Select Add Jar/Folder.

How to Detect cause of 503 Service Temporarily Unavailable error and handle it?

There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).

Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.

Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.

Module is not available, misspelled or forgot to load (but I didn't)

I had the same error but i resolved it, it was a syntax error in the AngularJS provider

Make text wrap in a cell with FPDF?

Text Wrap:

The MultiCell is used for print text with multiple lines. It has the same atributes of Cell except for ln and link.

$pdf->MultiCell( 200, 40, $reportSubtitle, 1);

Line Height:

What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).

MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])

You can read the full documentation here.

Changing Background Image with CSS3 Animations

You can use the jquery-backstretch image which allows for animated slideshows as your background-images!

https://github.com/jquery-backstretch/jquery-backstretch Scroll down to setup and all of the documentation is there.

Specifying ssh key in ansible playbook file

You can use the ansible.cfg file, it should look like this (There are other parameters which you might want to include):

[defaults]
inventory = <PATH TO INVENTORY FILE>
remote_user = <YOUR USER>
private_key_file =  <PATH TO KEY_FILE>

Hope this saves you some typing

String literals and escape characters in postgresql

Really stupid question: Are you sure the string is being truncated, and not just broken at the linebreak you specify (and possibly not showing in your interface)? Ie, do you expect the field to show as

This will be inserted \n This will not be

or

This will be inserted

This will not be

Also, what interface are you using? Is it possible that something along the way is eating your backslashes?

Spring: Why do we autowire the interface and not the implemented class?

How does spring know which polymorphic type to use.

As long as there is only a single implementation of the interface and that implementation is annotated with @Component with Spring's component scan enabled, Spring framework can find out the (interface, implementation) pair. If component scan is not enabled, then you have to define the bean explicitly in your application-config.xml (or equivalent spring configuration file).

Do I need @Qualifier or @Resource?

Once you have more than one implementation, then you need to qualify each of them and during auto-wiring, you would need to use the @Qualifier annotation to inject the right implementation, along with @Autowired annotation. If you are using @Resource (J2EE semantics), then you should specify the bean name using the name attribute of this annotation.

Why do we autowire the interface and not the implemented class?

Firstly, it is always a good practice to code to interfaces in general. Secondly, in case of spring, you can inject any implementation at runtime. A typical use case is to inject mock implementation during testing stage.

interface IA
{
  public void someFunction();
}


class B implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someBfunc()
  {
     //doing b things
  }
}


class C implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someCfunc()
  {
     //doing C things
  }
}

class MyRunner
{
     @Autowire
     @Qualifier("b") 
     IA worker;

     ....
     worker.someFunction();
}

Your bean configuration should look like this:

<bean id="b" class="B" />
<bean id="c" class="C" />
<bean id="runner" class="MyRunner" />

Alternatively, if you enabled component scan on the package where these are present, then you should qualify each class with @Component as follows:

interface IA
{
  public void someFunction();
}

@Component(value="b")
class B implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someBfunc()
  {
     //doing b things
  }
}


@Component(value="c")
class C implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someCfunc()
  {
     //doing C things
  }
}

@Component    
class MyRunner
{
     @Autowire
     @Qualifier("b") 
     IA worker;

     ....
     worker.someFunction();
}

Then worker in MyRunner will be injected with an instance of type B.

How to write UPDATE SQL with Table alias in SQL Server 2008?

The syntax for using an alias in an update statement on SQL Server is as follows:

UPDATE Q
SET Q.TITLE = 'TEST'
FROM HOLD_TABLE Q
WHERE Q.ID = 101;

The alias should not be necessary here though.

^[A-Za-Z ][A-Za-z0-9 ]* regular expression?

A lot of the answers given so far are pretty good, but you must clearly define what it is exactly that you want.

If you would like a alphabetical character followed by any number of non-white-space characters (note that it would also include numbers!) then you should use this:

^[A-Za-z]\S*$

If you would like to include only alpha-numeric characters and certain symbols, then use this:

^[A-Za-z][A-Za-z0-9!@#$%^&*]*$

Your original question looks like you are trying to include the space character as well, so you probably want something like this:

^[A-Za-z ][A-Za-z0-9!@#$%^&* ]*$

And that is my final answer!

I suggest taking some time to learn more about regular expressions. They are the greatest thing since sliced bread!

Try this syntax reference page (that site in general is very good).

Where can I get Google developer key

If you are only calling APIs that do not require user data, such as the Google Custom Search API, then API keys might be simpler to use than OAuth 2.0 access tokens. However, if your application already uses an OAuth 2.0 access token, then there is no need to generate an API key as well. Google ignores passed API keys if a passed OAuth 2.0 access token is already associated with the corresponding project.

Note: You must use either an OAuth 2.0 access token or an API key for all requests to Google APIs represented in the Google Developers Console. Not all APIs require authorized calls. To learn whether authorization is required for a specific call, see your API documentation.

Reference: https://developers.google.com/console/help/new/?hl=en_US#credentials-access-security-and-identity

Add a fragment to the URL without causing a redirect?

window.location.hash = 'something';

That is just plain JavaScript.

Your comment...

Hi, what I really need is to add only the hash... something like this: window.location.hash = '#'; but in this way nothing is added.

Try this...

window.location = '#';

Also, don't forget about the window.location.replace() method.

Xcode 10, Command CodeSign failed with a nonzero exit code

I'm unsure of what causes this issue but one method I used to resolve the porblem successfully was to run pod update on my cocoa pods.

The error (for me anyway) was showing a problem with one of the pods signing. Updating the pods resolved that signing issue.

pod update [PODNAME] //For an individual pod

or

pod update //For all pods.

Hopefully, this will help someone who is having the same "Command CodeSign failed with a nonzero exit code" error.

End of File (EOF) in C

EOF is -1 because that's how it's defined. The name is provided by the standard library headers that you #include. They make it equal to -1 because it has to be something that can't be mistaken for an actual byte read by getchar(). getchar() reports the values of actual bytes using positive number (0 up to 255 inclusive), so -1 works fine for this.

The != operator means "not equal". 0 stands for false, and anything else stands for true. So what happens is, we call the getchar() function, and compare the result to -1 (EOF). If the result was not equal to EOF, then the result is true, because things that are not equal are not equal. If the result was equal to EOF, then the result is false, because things that are equal are not (not equal).

The call to getchar() returns EOF when you reach the "end of file". As far as C is concerned, the 'standard input' (the data you are giving to your program by typing in the command window) is just like a file. Of course, you can always type more, so you need an explicit way to say "I'm done". On Windows systems, this is control-Z. On Unix systems, this is control-D.

The example in the book is not "wrong". It depends on what you actually want to do. Reading until EOF means that you read everything, until the user says "I'm done", and then you can't read any more. Reading until '\n' means that you read a line of input. Reading until '\0' is a bad idea if you expect the user to type the input, because it is either hard or impossible to produce this byte with a keyboard at the command prompt :)

Combine two columns of text in pandas dataframe

Small data-sets (< 150rows)

[''.join(i) for i in zip(df["Year"].map(str),df["quarter"])]

or slightly slower but more compact:

df.Year.str.cat(df.quarter)

Larger data sets (> 150rows)

df['Year'].astype(str) + df['quarter']

UPDATE: Timing graph Pandas 0.23.4

enter image description here

Let's test it on 200K rows DF:

In [250]: df
Out[250]:
   Year quarter
0  2014      q1
1  2015      q2

In [251]: df = pd.concat([df] * 10**5)

In [252]: df.shape
Out[252]: (200000, 2)

UPDATE: new timings using Pandas 0.19.0

Timing without CPU/GPU optimization (sorted from fastest to slowest):

In [107]: %timeit df['Year'].astype(str) + df['quarter']
10 loops, best of 3: 131 ms per loop

In [106]: %timeit df['Year'].map(str) + df['quarter']
10 loops, best of 3: 161 ms per loop

In [108]: %timeit df.Year.str.cat(df.quarter)
10 loops, best of 3: 189 ms per loop

In [109]: %timeit df.loc[:, ['Year','quarter']].astype(str).sum(axis=1)
1 loop, best of 3: 567 ms per loop

In [110]: %timeit df[['Year','quarter']].astype(str).sum(axis=1)
1 loop, best of 3: 584 ms per loop

In [111]: %timeit df[['Year','quarter']].apply(lambda x : '{}{}'.format(x[0],x[1]), axis=1)
1 loop, best of 3: 24.7 s per loop

Timing using CPU/GPU optimization:

In [113]: %timeit df['Year'].astype(str) + df['quarter']
10 loops, best of 3: 53.3 ms per loop

In [114]: %timeit df['Year'].map(str) + df['quarter']
10 loops, best of 3: 65.5 ms per loop

In [115]: %timeit df.Year.str.cat(df.quarter)
10 loops, best of 3: 79.9 ms per loop

In [116]: %timeit df.loc[:, ['Year','quarter']].astype(str).sum(axis=1)
1 loop, best of 3: 230 ms per loop

In [117]: %timeit df[['Year','quarter']].astype(str).sum(axis=1)
1 loop, best of 3: 230 ms per loop

In [118]: %timeit df[['Year','quarter']].apply(lambda x : '{}{}'.format(x[0],x[1]), axis=1)
1 loop, best of 3: 9.38 s per loop

Answer contribution by @anton-vbr

Undefined Symbols for architecture x86_64: Compiling problems

There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.

Similarity::Similarity() or Similarity::~Similarity() are just missing and you have defined the others incorrectly,

void Similarity::readData(Scanner& inStream){
}

not

void readData(Scanner& inStream){
}

etc. etc.

The second one is a function called readData, only the first is the readData method of the Similarity class.

To be clear about this, in Similarity.h

void readData(Scanner& inStream);

but in Similarity.cpp

void Similarity::readData(Scanner& inStream){
}

Difference between EXISTS and IN in SQL?

IN:

  • Works on List result set
  • Doesn’t work on subqueries resulting in Virtual tables with multiple columns
  • Compares every value in the result list
  • Performance is comparatively SLOW for larger result set of subquery

EXISTS:

  • Works on Virtual tables
  • Is used with co-related queries
  • Exits comparison when match is found
  • Performance is comparatively FAST for larger result set of subquery

PHP list of specific files in a directory

You'll be wanting to use glob()

Example:

$files = glob('/path/to/dir/*.xml');

Check image width and height before upload with Javascript

_x000D_
_x000D_
    const ValidateImg = (file) =>{_x000D_
        let img = new Image()_x000D_
        img.src = window.URL.createObjectURL(file)_x000D_
        img.onload = () => {_x000D_
            if(img.width === 100 && img.height ===100){_x000D_
                alert("Correct size");_x000D_
                return true;_x000D_
            }_x000D_
            alert("Incorrect size");_x000D_
            return true;_x000D_
        }_x000D_
    }
_x000D_
_x000D_
_x000D_

Is there a way to rollback my last push to Git?

Since you are the only user:

git reset --hard HEAD@{1}
git push -f
git reset --hard HEAD@{1}

( basically, go back one commit, force push to the repo, then go back again - remove the last step if you don't care about the commit )

Without doing any changes to your local repo, you can also do something like:

git push -f origin <sha_of_previous_commit>:master

Generally, in published repos, it is safer to do git revert and then git push

How to get all keys with their values in redis

Below is just a little variant of the script provided by @"Juuso Ohtonen".

I have add a password variable and counter so you can can check the progression of your backup. Also I replaced simple brackets [] by double brackets [[]] to prevent an error I had on macos.

1. Get the total number of keys

$ sudo redis-cli
INFO keyspace
AUTH yourpassword
INFO keyspace

2. Edit the script

#!/bin/bash

# Default to '*' key pattern, meaning all redis keys in the namespace
REDIS_KEY_PATTERN="${REDIS_KEY_PATTERN:-*}"
PASS="yourpassword"
i=1
for key in $(redis-cli -a "$PASS" --scan --pattern "$REDIS_KEY_PATTERN")
do
    echo $i.
    ((i=i+1))
    type=$(redis-cli -a "$PASS" type $key)
    if [[ $type = "list" ]]
    then
        printf "$key => \n$(redis-cli -a "$PASS" lrange $key 0 -1 | sed 's/^/  /')\n"
    elif [[ $type = "hash" ]]
    then
        printf "$key => \n$(redis-cli -a "$PASS" hgetall $key | sed 's/^/  /')\n"
    else
        printf "$key => $(redis-cli -a "$PASS" get $key)\n"
    fi
    echo
done

3. Execute the script

bash redis_print.sh > redis.bak

4. Check progression

tail redis.bak

Undo a particular commit in Git that's been pushed to remote repos

Identify the hash of the commit, using git log, then use git revert <commit> to create a new commit that removes these changes. In a way, git revert is the converse of git cherry-pick -- the latter applies the patch to a branch that's missing it, the former removes it from a branch that has it.

VBA: Convert Text to Number

This can be used to find all the numeric values (even those formatted as text) in a sheet and convert them to single (CSng function).

For Each r In Sheets("Sheet1").UsedRange.SpecialCells(xlCellTypeConstants)
    If IsNumeric(r) Then
       r.Value = CSng(r.Value)
       r.NumberFormat = "0.00"
    End If
Next

Angular2 multiple router-outlet in the same template

Yes you can as said by @tomer above. i want to add some point to @tomer answer.

  • firstly you need to provide name to the router-outlet where you want to load the second routing view in your view. (aux routing angular2.)
  • In angular2 routing few important points are here.

    • path or aux (requires exactly one of these to give the path you have to show as the url).
    • component, loader, redirectTo (requires exactly one of these, which component you want to load on routing)
    • name or as (optional) (requires exactly one of these, the name which specify at the time of routerLink)
    • data (optional, whatever you want to send with the routing that you have to get using routerParams at the receiver end.)

for more info read out here and here.

import {RouteConfig, AuxRoute} from 'angular2/router';
@RouteConfig([
  new AuxRoute({path: '/home', component: HomeCmp})
])
class MyApp {}

difference between width auto and width 100 percent

When we say

width:auto;

width will never exceed the total width of parent element. Maximum width is it's parent width. Even if we add border, padding and margin, content of element itself will become smaller in order to give space for border, padding and margin. In case if space required for border + padding + margin is greater than total width of parent element then width of content will become zero.

When we say

width:100%;

width of content of element will become 100% of parent element and from now if we add border, padding or margin then it will cause child element to exceed parent element's width and it will starts overflowing out of parent element.

Reading specific XML elements from XML file

You could use an XPath, too. A bit old fashioned but still effective:

using System.Xml;

...

XmlDocument xmlDocument;

xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);

foreach (XmlElement xmlElement in 
    xmlDocument.DocumentElement.SelectNodes("word[category='verb']"))
{
    Console.Out.WriteLine(xmlElement.OuterXml);
}

C# importing class into another class doesn't work

Well what you have to "import" (use) is the namespace of MyClass not the class name itself. If both classes are in the same namespace, you don't have to "import" it.

Definition MyClass.cs

namespace Ns1
{
    public class MyClass
    {
        ...
    }
}

Usage AnotherClass.cs

using Ns1;

namespace AnotherNs
{
    public class AnotherClass
    {
        public AnotherClass()
        {
            var myInst = new MyClass();
        }
    }
}

How to change the color of a CheckBox?

create an xml Drawable resource file under res->drawable and name it, for example, checkbox_custom_01.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item 
   android:state_checked="true"   
   android:drawable="@drawable/checkbox_custom_01_checked_white_green_32" />
  <item 
   android:state_checked="false" 
   android:drawable="@drawable/checkbox_custom_01_unchecked_gray_32" />
</selector>

Upload your custom checkbox image files (i recommend png) to your res->drawable folder.

Then go in your layout file and change your checkbox to

<CheckBox
    android:id="@+id/checkBox1"
    android:button="@drawable/checkbox_custom_01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:text="CheckBox"
    android:textSize="32dip"/>

you may customize anything, as long as android:button points to the correct XML file you created before.

NOTE TO NEWBIES: though it is not mandatory, it is nevertheless good practice to name your checkbox with a unique id throughout your whole layout tree.

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

You can use several g++ commands and then link, but the easiest is to use a traditional Makefile or some other build system: like Scons (which are often easier to set up than Makefiles).

How do I do an OR filter in a Django query?

You can use the | operator to combine querysets directly without needing Q objects:

result = Item.objects.filter(item.creator = owner) | Item.objects.filter(item.moderated = False)

(edit - I was initially unsure if this caused an extra query but @spookylukey pointed out that lazy queryset evaluation takes care of that)

How to remove focus around buttons on click

Add this in CSS:

*, ::after, ::before {
    box-sizing: border-box;
    outline: none !important;
    border: none !important;
    -webkit-box-shadow: none !important;
    box-shadow: none !important;
}

Replace spaces with dashes and make all letters lower-case

Just use the String replace and toLowerCase methods, for example:

var str = "Sonic Free Games";
str = str.replace(/\s+/g, '-').toLowerCase();
console.log(str); // "sonic-free-games"

Notice the g flag on the RegExp, it will make the replacement globally within the string, if it's not used, only the first occurrence will be replaced, and also, that RegExp will match one or more white-space characters.

Jquery insert new row into table at a certain index

Note:

$('#my_table > tbody:last').append(newRow); // this will add new row inside tbody

$("table#myTable tr").last().after(newRow);  // this will add new row outside tbody 
                                             //i.e. between thead and tbody
                                             //.before() will also work similar

is there any alternative for ng-disabled in angular2?

Yes You can either set [disabled]= "true" or if it is an radio button or checkbox then you can simply use disable

For radio button:

<md-radio-button disabled>Select color</md-radio-button>

For dropdown:

<ng-select (selected)="someFunction($event)" [disabled]="true"></ng-select>

Twitter-Bootstrap-2 logo image on top of navbar

If you do not increase the height of navbar..

 .navbar .brand {
 position: fixed;    
 overflow: visible;
 padding-left: 0;    
 padding-top: 0;
 }

see http://jsfiddle.net/petrfox/S84wP/

Spring 3 RequestMapping: Get path value

Just found that issue corresponding to my problem. Using HandlerMapping constants I was able to wrote a small utility for that purpose:

/**
 * Extract path from a controller mapping. /controllerUrl/** => return matched **
 * @param request incoming request.
 * @return extracted path
 */
public static String extractPathFromPattern(final HttpServletRequest request){


    String path = (String) request.getAttribute(
            HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
    String bestMatchPattern = (String ) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);

    AntPathMatcher apm = new AntPathMatcher();
    String finalPath = apm.extractPathWithinPattern(bestMatchPattern, path);

    return finalPath;

}

mysqli_real_connect(): (HY000/2002): No such file or directory

Try just

sudo service mysql restart

It worked for me

List all virtualenv

If you are using virtualenv or Python 3's built in venv the above answers might not work.

If you are on Linux, just locate the activate script that is always present inside a env.

locate -b '\activate' | grep "/home"

This will grab all Python virtual environments present inside your home directory.

See Demo Here

How remove border around image in css?

it's a good idea to use a reset CSS. add this at the top of your CSS file

img, a {border:none, outline: none;}

hope this helps

Execution sequence of Group By, Having and Where clause in SQL Server?

In Oracle 12c, you can run code both in either sequence below:

Where
Group By
Having

Or

Where 
Having
Group by

What's the difference between unit, functional, acceptance, and integration tests?

This is very simple.

  1. Unit testing: This is the testing actually done by developers that have coding knowledge. This testing is done at the coding phase and it is a part of white box testing. When a software comes for development, it is developed into the piece of code or slices of code known as a unit. And individual testing of these units called unit testing done by developers to find out some kind of human mistakes like missing of statement coverage etc..

  2. Functional testing: This testing is done at testing (QA) phase and it is a part of black box testing. The actual execution of the previously written test cases. This testing is actually done by testers, they find the actual result of any functionality in the site and compare this result to the expected result. If they found any disparity then this is a bug.

  3. Acceptance testing: know as UAT. And this actually done by the tester as well as developers, management team, author, writers, and all who are involved in this project. To ensure the project is finally ready to be delivered with bugs free.

  4. Integration testing: The units of code (explained in point 1) are integrated with each other to complete the project. These units of codes may be written in different coding technology or may these are of different version so this testing is done by developers to ensure that all units of the code are compatible with other and there is no any issue of integration.

How to add a scrollbar to an HTML5 table?

Instead of assuming as fixed width columns.

CSS

table.tableSection {
  display: table;
  width: 100%;
}

table.tableSection thead,
table.tableSection tbody {
  width: 100%;
}

table.tableSection thead {
  overflow-y: scroll;
  display: table;
  table-layout: fixed;
  width: calc(100% - 16px); /* assuming scrollbar width as 16px */
}

table.tableSection tbody {
  overflow: auto;
  height: 150px;
  display: block;
}

table.tableSection tr {
  width: 100%;
  text-align: left;
  display: table;
  table-layout: fixed;
}

Working Fiddle

Hibernate Union alternatives

You could use id in (select id from ...) or id in (select id from ...)

e.g. instead of non-working

from Person p where p.name="Joe"
union
from Person p join p.children c where c.name="Joe"

you could do

from Person p 
  where p.id in (select p1.id from Person p1 where p1.name="Joe") 
    or p.id in (select p2.id from Person p2 join p2.children c where c.name="Joe");

At least using MySQL, you will run into performance problems with it later, though. It's sometimes easier to do a poor man's join on two queries instead:

// use set for uniqueness
Set<Person> people = new HashSet<Person>((List<Person>) query1.list());
people.addAll((List<Person>) query2.list());
return new ArrayList<Person>(people);

It's often better to do two simple queries than one complex one.

EDIT:

to give an example, here is the EXPLAIN output of the resulting MySQL query from the subselect solution:

mysql> explain 
  select p.* from PERSON p 
    where p.id in (select p1.id from PERSON p1 where p1.name = "Joe") 
      or p.id in (select p2.id from PERSON p2 
        join CHILDREN c on p2.id = c.parent where c.name="Joe") \G
*************************** 1. row ***************************
           id: 1
  select_type: PRIMARY
        table: a
         type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 247554
        Extra: Using where
*************************** 2. row ***************************
           id: 3
  select_type: DEPENDENT SUBQUERY
        table: NULL
         type: NULL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: NULL
        Extra: Impossible WHERE noticed after reading const tables
*************************** 3. row ***************************
           id: 2
  select_type: DEPENDENT SUBQUERY
        table: a1
         type: unique_subquery
possible_keys: PRIMARY,name,sortname
          key: PRIMARY
      key_len: 4
          ref: func
         rows: 1
        Extra: Using where
3 rows in set (0.00 sec)

Most importantly, 1. row doesn't use any index and considers 200k+ rows. Bad! Execution of this query took 0.7s wheres both subqueries are in the milliseconds.

How to find a value in an array of objects in JavaScript?

I had to search a nested sitemap structure for the first leaf item that machtes a given path. I came up with the following code just using .map() .filter() and .reduce. Returns the last item found that matches the path /c.

var sitemap = {
  nodes: [
    {
      items: [{ path: "/a" }, { path: "/b" }]
    },
    {
      items: [{ path: "/c" }, { path: "/d" }]
    },
    {
      items: [{ path: "/c" }, { path: "/d" }]
    }
  ]
};

const item = sitemap.nodes
  .map(n => n.items.filter(i => i.path === "/c"))
  .reduce((last, now) => last.concat(now))
  .reduce((last, now) => now);

Edit 4n4904z07

Non-conformable arrays error in code

The problem is that omega in your case is matrix of dimensions 1 * 1. You should convert it to a vector if you wish to multiply t(X) %*% X by a scalar (that is omega)

In particular, you'll have to replace this line:

omega   = rgamma(1,a0,1) / L0

with:

omega   = as.vector(rgamma(1,a0,1) / L0)

everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.) or c(t(.)). Both are equivalent.

Here's the modified code that should work:

gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1, 
                     a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
    m0      = c(m01, m02) 
    C0      = matrix(nrow = 2, ncol = 2) 
    C0[1,1] = 1 / k01 
    C0[1,2] = 0 
    C0[2,1] = 0 
    C0[2,2] = 1 / k02 
    beta    = mvrnorm(1,m0,C0) 
    omega   = as.vector(rgamma(1,a0,1) / L0)
    draws   = matrix(ncol = 3,nrow = ndraw) 
    it      = -nburn 

    while (it < ndraw) {
        it    = it + 1 
        C1    = solve(solve(C0) + omega * t(X) %*% X) 
        m1    = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
        beta  = mvrnorm(1, m1, C1) 
        a1    = a0 + n / 2 
        L1    = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2 
        omega = as.vector(rgamma(1, a1, 1) / L1)
        if (it > 0) { 
            draws[it,1] = beta[1]
            draws[it,2] = beta[2]
            draws[it,3] = omega
        }
    }
    return(draws)
}

Efficient way of having a function only execute once in a loop

If I understand the updated question correctly, something like this should work

def function1():
    print "function1 called"

def function2():
    print "function2 called"

def function3():
    print "function3 called"

called_functions = set()
while True:
    n = raw_input("choose a function: 1,2 or 3 ")
    func = {"1": function1,
            "2": function2,
            "3": function3}.get(n)

    if func in called_functions:
        print "That function has already been called"
    else:
        called_functions.add(func)
        func()

"Items collection must be empty before using ItemsSource."

In My case, it was just an extra StackPanel inside the ListView:

<ListView Name="_details" Margin="50,0,50,0">
            <StackPanel Orientation="Vertical">
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="{Binding Location.LicenseName, StringFormat='Location: {0}'}"/>
                    <TextBlock Text="{Binding Ticket.Employee.s_name, StringFormat='Served by: {0}'}"/>
                    <TextBlock Text="{Binding Ticket.dt_create_time, StringFormat='Started at: {0}'}"/>
                    <Line StrokeThickness="2" Stroke="Gray" Stretch="Fill" Margin="0,5,0,5" />
                    <ItemsControl ItemsSource="{Binding Items}"/>
                </StackPanel>
            </StackPanel>
        </ListView>

Becomes:

<ListView Name="_details" Margin="50,0,50,0">
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="{Binding Location.LicenseName, StringFormat='Location: {0}'}"/>
                    <TextBlock Text="{Binding Ticket.Employee.s_name, StringFormat='Served by: {0}'}"/>
                    <TextBlock Text="{Binding Ticket.dt_create_time, StringFormat='Started at: {0}'}"/>
                    <Line StrokeThickness="2" Stroke="Gray" Stretch="Fill" Margin="0,5,0,5" />
                    <ItemsControl ItemsSource="{Binding Items}"/>
                </StackPanel>
        </ListView>

and all is well.

How can I find out what FOREIGN KEY constraint references a table in SQL Server?

You can also return all the information about the Foreign Keys by adapating @LittleSweetSeas answer:

SELECT 
   OBJECT_NAME(f.parent_object_id) ConsTable,
   OBJECT_NAME (f.referenced_object_id) refTable,
   COL_NAME(fc.parent_object_id,fc.parent_column_id) ColName
FROM 
   sys.foreign_keys AS f
INNER JOIN 
   sys.foreign_key_columns AS fc 
      ON f.OBJECT_ID = fc.constraint_object_id
INNER JOIN 
   sys.tables t 
      ON t.OBJECT_ID = fc.referenced_object_id
order by
ConsTable

How do I spool to a CSV formatted file using SQLPLUS?

There is a problem using sqlplus to create csv files. If you want the column headers only once in the output and there are thousands or millions of rows, you cannot set pagesize large enough not to get a repeat. The solution is to start with pagesize = 50 and parse out the headers, then issue the select again with pagesize = 0 to get the data. See bash script below:

#!/bin/bash
FOLDER="csvdata_mydb"
CONN="192.168.100.11:1521/mydb0023.world"
CNT=0376
ORD="0376"
TABLE="MY_ATTACHMENTS"

sqlplus -L logn/pswd@//${CONN}<<EOF >/dev/null
set pagesize 50;
set verify off;
set feedback off;
set long 99999;
set linesize 32767;
set trimspool on;
col object_ddl format A32000;
set colsep ,;
set underline off;
set headsep off;
spool ${ORD}${TABLE}.tmp;
select * from tblspc.${TABLE} where rownum < 2;
EOF
LINES=`wc -l ${ORD}${TABLE}.tmp | cut -f1 -d" "`
[ ${LINES} -le 3 ] && {
  echo "No Data Found in ${TABLE}."
}
[ ${LINES} -gt 3 ] && {
  cat ${ORD}${TABLE}.tmp | sed -e 's/ * / /g' -e 's/^ //' -e 's/ ,/,/g' -e 's/, /,/g' | tail -n +3 | head -n 1 > ./${ORD}${TABLE}.headers
}

sqlplus -L logn/pswd@//${CONN}<<EOF >/dev/null
set pagesize 0;
set verify off;
set feedback off;
set long 99999;
set linesize 32767;
set trimspool on;
col object_ddl format A32000;
set colsep ,;
set underline off;
set headsep off;
spool ${ORD}${TABLE}.tmp;
select * from tblspc.${TABLE};
EOF
LINES=`wc -l ${ORD}${TABLE}.tmp | cut -f1 -d" "`
[ ${LINES} -le 3 ] && {
  echo "No Data Found in ${TABLE}."
}
[ ${LINES} -gt 3 ] && {
  cat ${ORD}${TABLE}.headers > ${FOLDER}/${ORD}${TABLE}.csv
  cat ${ORD}${TABLE}.tmp | sed -e 's/ * / /g' -e 's/^ //' -e 's/ ,/,/g' -e 's/, /,/g' | tail -n +2 | head -n -1 >> ${FOLDER}/${ORD}${TABLE}.csv
}

How to add favicon.ico in ASP.NET site

for me, it didn't work without specifying the MIME in web.config, under <system.webServer><staticContent>

<mimeMap fileExtension=".ico" mimeType="image/ico" />

How to do multiline shell script in Ansible

Ansible uses YAML syntax in its playbooks. YAML has a number of block operators:

  • The > is a folding block operator. That is, it joins multiple lines together by spaces. The following syntax:

    key: >
      This text
      has multiple
      lines
    

    Would assign the value This text has multiple lines\n to key.

  • The | character is a literal block operator. This is probably what you want for multi-line shell scripts. The following syntax:

    key: |
      This text
      has multiple
      lines
    

    Would assign the value This text\nhas multiple\nlines\n to key.

You can use this for multiline shell scripts like this:

- name: iterate user groups
  shell: |
    groupmod -o -g {{ item['guid'] }} {{ item['username'] }} 
    do_some_stuff_here
    and_some_other_stuff
  with_items: "{{ users }}"

There is one caveat: Ansible does some janky manipulation of arguments to the shell command, so while the above will generally work as expected, the following won't:

- shell: |
    cat <<EOF
    This is a test.
    EOF

Ansible will actually render that text with leading spaces, which means the shell will never find the string EOF at the beginning of a line. You can avoid Ansible's unhelpful heuristics by using the cmd parameter like this:

- shell:
    cmd: |
      cat <<EOF
      This is a test.
      EOF

Pandas read_sql with parameters

The read_sql docs say this params argument can be a list, tuple or dict (see docs).

To pass the values in the sql query, there are different syntaxes possible: ?, :1, :name, %s, %(name)s (see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2 in your case I suppose).

In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2 documentation, they support the %(name)s style (and so not the :name I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:

df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
                     'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
                   db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
                   index_col=['Timestamp'])

What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?

Here's a setTimeout equivalent, mostly useful when trying to update the User Interface after a delay.

As you may know, updating the user interface can only by done from the UI thread. AsyncTask does that for you by calling its onPostExecute method from that thread.

new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // Update the User Interface
        }

    }.execute();

How do I "select Android SDK" in Android Studio?

The simplest solution for this problem:

First make sure your sdk path is currect. Then Please close current project and in android startup menu click on import project and choose your project from explorer. This will always solve my problem

How to redirect a url in NGINX

Similar to another answer here, but change the http in the rewrite to to $scheme like so:

server {
        listen 80;
        server_name test.com;
        rewrite     ^ $scheme://www.test.com$request_uri? permanent;
}

And edit your main server block server_name variable as following:

server_name  www.test.com;

I had to do this to redirect www.test.com to test.com.

RegEx match open tags except XHTML self-contained tags

It seems to me you're trying to match tags without a "/" at the end. Try this:

<([a-zA-Z][a-zA-Z0-9]*)[^>]*(?<!/)>

BAT file to open CMD in current directory

A bit late to the game but if I'm understanding your needs correctly this will help people with the same issue.

Two solutions with the same first step: First navigate to the location you keep your scripts in and copy the filepath to that directory.

First Solution:

  • Click "Start"
  • Right-click "Computer" (or "My Computer)
  • Click "Properties"
  • On the left, click "Advanced System Settings"
  • Click "Environment Variables"
  • In the "System Variables" Box, scroll down and select "PATH"
  • Click "Edit"
  • In the "Variable Value" field, scroll all the way to the right
  • If there isn't a semi-colon (;) there yet, add it.
  • Paste in the filepath you copied earlier.
  • End with a semi-colon.
  • Click "OK"
  • Click "OK" again
  • Click "OK" one last time

You can now use any of your scripts as if you were already that folder.

Second Solution: (can easily be paired with the first for extra usefulness)

On your desktop create a batch file with the following content.

@echo off
cmd /k cd "C:\your\file\path"

This will open a command window like what you tried to do.


For tons of info on windows commands check here: http://ss64.com/nt/

How to implement a tree data-structure in Java?

    // TestTree.java
// A simple test to see how we can build a tree and populate it
//
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;

public class TestTree extends JFrame {

  JTree tree;
  DefaultTreeModel treeModel;

  public TestTree( ) {
    super("Tree Test Example");
    setSize(400, 300);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
  }

  public void init( ) {
    // Build up a bunch of TreeNodes. We use DefaultMutableTreeNode because the
    // DefaultTreeModel can use it to build a complete tree.
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
    DefaultMutableTreeNode subroot = new DefaultMutableTreeNode("SubRoot");
    DefaultMutableTreeNode leaf1 = new DefaultMutableTreeNode("Leaf 1");
    DefaultMutableTreeNode leaf2 = new DefaultMutableTreeNode("Leaf 2");

    // Build our tree model starting at the root node, and then make a JTree out
    // of it.
    treeModel = new DefaultTreeModel(root);
    tree = new JTree(treeModel);

    // Build the tree up from the nodes we created.
    treeModel.insertNodeInto(subroot, root, 0);
    // Or, more succinctly:
    subroot.add(leaf1);
    root.add(leaf2);

    // Display it.
    getContentPane( ).add(tree, BorderLayout.CENTER);
  }

  public static void main(String args[]) {
    TestTree tt = new TestTree( );
    tt.init( );
    tt.setVisible(true);
  }
}

How to change line-ending settings

For me what did the trick was running the command

git config auto.crlf false

inside the folder of the project, I wanted it specifically for one project.

That command changed the file in path {project_name}/.git/config (fyi .git is a hidden folder) by adding the lines

[auto]
    crlf = false

at the end of the file. I suppose changing the file does the same trick as well.

Saving response from Requests to file

You can use the response.text to write to a file:

import requests

files = {'f': ('1.pdf', open('1.pdf', 'rb'))}
response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)
response.raise_for_status() # ensure we notice bad responses
file = open("resp_text.txt", "w")
file.write(response.text)
file.close()
file = open("resp_content.txt", "w")
file.write(response.text)
file.close()

How do I modify a MySQL column to allow NULL?

You want the following:

ALTER TABLE mytable MODIFY mycolumn VARCHAR(255);

Columns are nullable by default. As long as the column is not declared UNIQUE or NOT NULL, there shouldn't be any problems.

How do I get the last character of a string?

public char LastChar(String a){
    return a.charAt(a.length() - 1);
}

jQuery 1.9 .live() is not a function

When i will getting this error on my site .it will stop some functionality on my site, after research i find the solution for this problem ,

$colorpicker_inputs.live('focus', function(e) {
    jQuery(this).next('.farb-popup').show();
    jQuery(this).parents('li').css( {
        position : 'relative',
        zIndex : '9999'
    })
    jQuery('#tabber').css( {
        overflow : 'visible'
    });
});

$colorpicker_inputs.live('blur', function(e) {
    jQuery(this).next('.farb-popup').hide();
    jQuery(this).parents('li').css( {
        zIndex : '0'
    })
});

Should be replace 'live' to 'on' check below

    $colorpicker_inputs.on('focus', function(e) {
    jQuery(this).next('.farb-popup').show();
    jQuery(this).parents('li').css( {
        position : 'relative',
        zIndex : '9999'
    })
    jQuery('#tabber').css( {
        overflow : 'visible'
    });
});

$colorpicker_inputs.on('blur', function(e) {
    jQuery(this).next('.farb-popup').hide();
    jQuery(this).parents('li').css( {
        zIndex : '0'
    })
});

One more basic exmaple below :

.live(event, selector, function) 

Change it to :

.on(event, selector, function)

Gmail: 530 5.5.1 Authentication Required. Learn more at

You need to go here https://security.google.com/settings/security/apppasswords

then select Gmail and then select device. then click on Generate. Simply Copy & Paste password which is generated by Google.

How to "add existing frameworks" in Xcode 4?

Follow below 5 steps to add framework in your project.

  1. Click on Project Navigator.
  2. Select Targets (Black arrow in the below image).
  3. Select Build phases ( Blue arrow in the below image).
  4. Click on + Button (Green arrow in below image).
  5. Select your framework from list.

Framework

Here is the official Apple Link

How to scroll to top of a div using jQuery?

I don't know why but you have to add a setTimeout with at least for me 200ms:

setTimeout( function() {$("#DIV_ID").scrollTop(0)}, 200 );

Tested with Firefox / Chrome / Edge.

How do I pass JavaScript variables to PHP?

You cannot pass variable values from the current page JavaScript code to the current page PHP code... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.

You need to pass variables to PHP code from the HTML form using another mechanism, such as submitting the form using the GET or POST methods.

<DOCTYPE html>
<html>
  <head>
    <title>My Test Form</title>
  </head>

  <body>
    <form method="POST">
      <p>Please, choose the salary id to proceed result:</p>
      <p>
        <label for="salarieids">SalarieID:</label>
        <?php
          $query = "SELECT * FROM salarie";
          $result = mysql_query($query);
          if ($result) :
        ?>
        <select id="salarieids" name="salarieid">
          <?php
            while ($row = mysql_fetch_assoc($result)) {
              echo '<option value="', $row['salaried'], '">', $row['salaried'], '</option>'; //between <option></option> tags you can output something more human-friendly (like $row['name'], if table "salaried" have one)
            }
          ?>
        </select>
        <?php endif ?>
      </p>
      <p>
        <input type="submit" value="Sumbit my choice"/>
      </p>
    </form>

    <?php if isset($_POST['salaried']) : ?>
      <?php
        $query = "SELECT * FROM salarie WHERE salarieid = " . $_POST['salarieid'];
        $result = mysql_query($query);
        if ($result) :
      ?>
        <table>
          <?php
            while ($row = mysql_fetch_assoc($result)) {
              echo '<tr>';
              echo '<td>', $row['salaried'], '</td><td>', $row['bla-bla-bla'], '</td>' ...; // and others
              echo '</tr>';
            }
          ?>
        </table>
      <?php endif?>
    <?php endif ?>
  </body>
</html>

Convert list to dictionary using linq and not worrying about duplicates

This should work with lambda expression:

personList.Distinct().ToDictionary(i => i.FirstandLastName, i => i);

How to install mscomct2.ocx file from .cab file (Excel User Form and VBA)

You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.

  1. Just extract the .ocx file from the .cab file (it is similar to a zip)
  2. Copy to the system folder (c:\windows\sysWOW64 for 64 bit systems and c:\windows\system32 for 32 bit)
  3. Use regsvr32 through the command prompt to register the file (e.g. "regsvr32 c:\windows\sysWOW64\mscomct2.ocx")

References

List of standard lengths for database fields

If you need to consider localisation (for those of us outside the US!) and it's possible in your environment, I'd suggest:

Define data types for each component of the name - NOTE: some cultures have more than two names! Then have a type for the full name,

Then localisation becomes simple (as far as names are concerned).

The same applies to addresses, BTW - different formats!

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

I have another possible answer for those wondering why event log entries are not showing up in the History tab of Task Scheduler for certain tasks, even though All Task History is enabled, the events for those tasks are viewable in the Event Log, and all other tasks show history just fine. In my case, I had created 13 new tasks. For 5 of them, events showed fine under History, but for the other 8, the History tab was completely blank. I even verified these tasks were enabled for history individually (and logging events) using Mick Wood's post about using the Event Viewer.

Then it hit me. I suddenly realized what all 8 had in common that the other 5 did not. They all had an ampersand (&) character in the event name. I created them by exporting the first task I created, "Sync E to N", renaming the exported file name, editing the XML contents, and then importing the new task. Windows Explorer happily let me rename the task, for example, to "Sync C to N & T", and Task Scheduler happily let me import it. However, with that pesky "&" in the name, it could not retrieve its history from the event log. When I deleted the original event, renamed the xml file to "Sync C to N and T", and imported it, voila, there were all of the log entries in the History tab in Task Scheduler.

100% Min Height CSS layout

A pure CSS solution (#content { min-height: 100%; }) will work in a lot of cases, but not in all of them - especially IE6 and IE7.

Unfortunately, you will need to resort to a JavaScript solution in order to get the desired behavior. This can be done by calculating the desired height for your content <div> and setting it as a CSS property in a function:

function resizeContent() {
  var contentDiv = document.getElementById('content');
  var headerDiv = document.getElementById('header');
  // This may need to be done differently on IE than FF, but you get the idea.
  var viewPortHeight = window.innerHeight - headerDiv.clientHeight;
  contentDiv.style.height = 
    Math.max(viewportHeight, contentDiv.clientHeight) + 'px';
}

You can then set this function as a handler for onLoad and onResize events:

<body onload="resizeContent()" onresize="resizeContent()">
  . . .
</body>