Programs & Examples On #Classnotfound

0

"Failed to install the following Android SDK packages as some licences have not been accepted" error

This works for me in Windows 10:

C:
cd \Users\YOUR_USER\AppData\Local\Android\Sdk\cmdline-tools\latest\bin
sdkmanager.bat --licenses

After, yes to all

Flutter.io Android License Status Unknown

If you updated the android SDK, the licenses may have changed. Depending on how you did the update you may or may not have been prompted to accept the changes, or maybe it just doesn't save the fact that you did accept them in a way flutter can understand.

To resolve, try running

flutter doctor --android-licenses

This should prompt you to accept licenses (it may ask you first, in case just type y and press enter - although it should tell you that).

If you still have problems after doing that, it might be worth either opening a new bug in the Flutter Github repository, or adding a comment on an existing issue like this one as it may be what you're seeing.

Failed to run sdkmanager --list with Java 9

JDK 13.0.1, Android SDK 29 , Windows 10

Basically i tried everything, but the most effective and only 1 solution that worked for me was to downgrade to jdk 1.8. I dont why, it is early 2020 and have to downgrade to 1 year old jdk version against latest flutter version. Maybe problem is in windows version, cause jdk 13.0.1 worked for me on macOS 10.15.2. Hope this solution works.

Download Link (JDK 1.8.0): https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

I got the same problem after creating a new TestCase: Eclipse -> New -> JUnit Test Case. It creates a class without access level modifier. I could solve the problem by just putting a public before the class keyword.

Failed to install android-sdk: "java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema"

My Java version is 15.0.1 . For the OS Mac.

and this is how i fixed the issue.

  1. downloaded zip: jaf-1_1_1.zip from: https://download.oracle.com/otn-pub/java/jaf/1.1.1/jaf-1_1_1.zip?AuthParam=1609860571_68ca6f30491c76e81970a3849504fb6a

  2. downloaded the zip: jaxb-ri-2.3.1.zip from: https://download.oracle.com/otn-pub/java/jaf/1.1.1/jaf-1_1_1.zip?AuthParam=1609860571_68ca6f30491c76e81970a3849504fb6a

  3. unziped into a folder: ~/jars/ . exported classpath as follows

export  
 CLASSPATH=~/jars/FastInfoset.jar:~/jars/activation.jar:~/jars/codemodel.jar:~/jars/dtd-parser.jar:~/jars/istack-commons-runtime.jar:~/jars/istack-commons-tools.jar:~/jars/jaf-1.1.1:~/jars/jaf-1_1_1.zip:~/jars/javax.activation-api.jar:~/jars/jaxb-api.jar:~/jars/jaxb-jxc.jar:~/jars/jaxb-ri:~/jars/jaxb-ri-2.3.1.zip:~/jars/jaxb-runtime.jar:~/jars/jaxb-xjc.jar:~/jars/relaxng-datatype.jar:~/jars/rngom.jar:~/jars/stax-ex.jar:~/jars/txw2.jar:~/jars/xsom.jar
  1. next edit the file: cd ~/Library/Android/sdk/tools/bin/sdkmanager change the CLASSPATH to the below

CLASSPATH=$CLASSPATH:$APP...

save the file and run the command again.

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

Use all the jackson dependencies(databind,core, annotations, scala(if you are using spark and scala)) with the same version.. and upgrade the versions to the latest releases..

<dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-scala_2.11</artifactId>
            <version>2.9.4</version>
        </dependency>

        <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.4</version>
        <exclusions>
            <exclusion>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-annotations</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.4</version>
    </dependency>

        <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.9.4</version>

        </dependency>

Note: Use Scala dependency only if you are working with scala. Otherwise it is not needed.

Didn't find class "com.google.firebase.provider.FirebaseInitProvider"?

1: Go to the gradle enable multiDexEnabled and add the multidex library in the dependencies.

android {
   ...
   defaultConfig {
      multiDexEnabled true
      ...
   }
}

dependencies {
  // add dependency 
  implementation 'com.android.support:multidex:1.0.1'
}

2: Go to the Manifest file and write android:name=".MyApplication" (Class name(MyApplication) is optional you can write whatever you want ).

    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        .
        .
        .
        .
        .
    </application>

3: As you wrote android:name=".MyApplication" Inside Application at Manifest file. it will give you an error because you didn't create MyApplication class. Create MyApplication Class extend it by "application" class or Simply click on.MyApplication, a small red balloon appear on the left side of a syntax click on it, you will see (create MyApplication class) in the menu, click on it and Include below Method Inside that class.

    public class MyApplication extends Application {

    @Override 
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    } 

If you want to get more information then Click on this Link:[https://developer.android.com/studio/build/multidex.html]

Hopefully, It works for you.

Apache POI error loading XSSFWorkbook class

Please note that 4.0 is not sufficient since ListValuedMap, was introduced in version 4.1.

You need to use this maven repository link for version 4.1. Replicated below for convenience

 <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
 <dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-collections4</artifactId>
   <version>4.1</version>
</dependency>

Error: Module not specified (IntelliJ IDEA)

this is how I fix this issue
1.open my project structure

2.click module enter image description here 3.click plus button enter image description here 4.click import module,and find the module's pom enter image description here
5.make sure you select the module you want to import,then next next finish:) enter image description here

java.lang.ClassNotFoundException: com.fasterxml.jackson.annotation.JsonInclude$Value

Use Jackson-annotations.jar will solve the problem, as it worked for me.

Warning about SSL connection when connecting to MySQL database

I use this property for hibernate in config xml

<property name="hibernate.connection.url">
jdbc:mysql://localhost:3306/bookshop?serverTimezone=UTC&amp;useSSL=false
</property>

without - serverTimezone=UTC - it doesn't work

WARNING: Exception encountered during context initialization - cancelling refresh attempt

This was my stupidity, but a stupidity that was not easy to identify :).

Problem:

  1. My code is compiled on Jdk 1.8.
  2. My eclipse, had JDK 1.8 as the compiler.
  3. My tomcat in eclipse was using Java 1.7 for its container, hence it was not able to understand the .class files which were compiled using 1.8.
  4. To avoid the problem, ensure in your eclipse, double click on your server -> Open Launch configuration -> Classpath -> JRE System Library -> Give the JDK/JRE of the compiled version of java class, in my case, it had to be JDK 1.8
    1. Post this, clean the server, build and redeploy, start the tomcat.

If you are deploying manually into your server, ensure your JAVA_HOME, JDK_HOME points to the correct JDK which you used to compile the project and build the war.

If you do not like to change JAVA_HOME, JDK_HOME, you can always change the JAVA_HOME and JDK_HOME in catalina.bat(for tomcat server) and that'll enable your life to be easy!

Spring Boot java.lang.NoClassDefFoundError: javax/servlet/Filter

That looks like you tried to add the libraries servlet.jar or servlet-api.jar into your project /lib/ folder, but Tomcat already should provide you with those libraries. Remove them from your project and classpath. Search for that anywhere in your project or classpath and remove it.

java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonFactory

Add the following dependency to your pom.xml

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.5.2</version>
</dependency>

UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory'

Well, you're getting a java.lang.NoClassDefFoundError. In your pom.xml, hibernate-core version is 3.3.2.GA and declared after hibernate-entitymanager, so it prevails. You can remove that dependency, since will be inherited version 3.6.7.Final from hibernate-entitymanager.

You're using spring-boot as parent, so no need to declare version of some dependencies, since they are managed by spring-boot.

Also, hibernate-commons-annotations is inherited from hibernate-entitymanager and hibernate-annotations is an old version of hibernate-commons-annotations, you can remove both.

Finally, your pom.xml can look like this:

<?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>org.elsys.internetprogramming.trafficspy.server</groupId>
    <artifactId>TrafficSpyService</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.3.RELEASE</version>
    </parent>

    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cloud-connectors</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.0.0</version>
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
        </dependency>

        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

    <properties>
        <java.version>1.7</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>

        <repository>
            <id>codehaus</id>
            <url>http://repository.codehaus.org/org/codehaus</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>

</project>

Let me know if you have a problem.

How to resolve this JNI error when trying to run LWJGL "Hello World"?

A CLASSPATH entry is either a directory at the head of a package hierarchy of .class files, or a .jar file. If you're expecting ./lib to include all the .jar files in that directory, it won't. You have to name them explicitly.

A child container failed during start java.util.concurrent.ExecutionException

I faced similar issue with similar logs. I was using JDK 1.6 with apache tomcat 7. Setting java_home to 1.7 resolved the issue.

How can I throw CHECKED exceptions from inside Java 8 streams?

The only built-in way of handling checked exceptions that can be thrown by a map operation is to encapsulate them within a CompletableFuture. (An Optional is a simpler alternative if you don't need to preserve the exception.) These classes are intended to allow you to represent contingent operations in a functional way.

A couple of non-trivial helper methods are required, but you can arrive at code that's relatively concise, while still making it apparent that your stream's result is contingent on the map operation having completed successfully. Here's what it looks like:

    CompletableFuture<List<Class<?>>> classes =
            Stream.of("java.lang.String", "java.lang.Integer", "java.lang.Double")
                  .map(MonadUtils.applyOrDie(Class::forName))
                  .map(cfc -> cfc.thenApply(Class::getSuperclass))
                  .collect(MonadUtils.cfCollector(ArrayList::new,
                                                  List::add,
                                                  (List<Class<?>> l1, List<Class<?>> l2) -> { l1.addAll(l2); return l1; },
                                                  x -> x));
    classes.thenAccept(System.out::println)
           .exceptionally(t -> { System.out.println("unable to get class: " + t); return null; });

This produces the following output:

[class java.lang.Object, class java.lang.Number, class java.lang.Number]

The applyOrDie method takes a Function that throws an exception, and converts it into a Function that returns an already-completed CompletableFuture -- either completed normally with the original function's result, or completed exceptionally with the thrown exception.

The second map operation illustrates that you've now got a Stream<CompletableFuture<T>> instead of just a Stream<T>. CompletableFuture takes care of only executing this operation if the upstream operation succeeded. The API makes this explict, but relatively painless.

Until you get to the collect phase, that is. This is where we require a pretty significant helper method. We want to "lift" a normal collection operation (in this case, toList()) "inside" the CompletableFuture -- cfCollector() lets us do that using a supplier, accumulator, combiner, and finisher that don't need to know anything at all about CompletableFuture.

The helper methods can be found on GitHub in my MonadUtils class, which is very much still a work in progress.

java.lang.NoClassDefFoundError: org/json/JSONObject

No.. It is not proper way. Refer the steps,

For Classpath reference: Right click on project in Eclipse -> Buildpath -> Configure Build path -> Java Build Path (left Pane) -> Libraries(Tab) -> Add External Jars -> Select your jar and select OK.

For Deployment Assembly: Right click on WAR in eclipse-> Buildpath -> Configure Build path -> Deployment Assembly (left Pane) -> Add -> External file system -> Add -> Select your jar -> Add -> Finish.

This is the proper way! Don't forget to remove environment variable. It is not required now.

Try this. Surely it will work. Try to use Maven, it will simplify you task.

Problems with local variable scope. How to solve it?

You have a scope problem indeed, because statement is a local method variable defined here:

protected void createContents() {
    ...
    Statement statement = null; // local variable
    ...
     btnInsert.addMouseListener(new MouseAdapter() { // anonymous inner class
        @Override
        public void mouseDown(MouseEvent e) {
            ...
            try {
                statement.executeUpdate(query); // local variable out of scope here
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            ...
    });
}

When you try to access this variable inside mouseDown() method you are trying to access a local variable from within an anonymous inner class and the scope is not enough. So it definitely must be final (which given your code is not possible) or declared as a class member so the inner class can access this statement variable.

Sources:


How to solve it?

You could...

Make statement a class member instead of a local variable:

public class A1 { // Note Java Code Convention, also class name should be meaningful   
    private Statement statement;
    ...
}

You could...

Define another final variable and use this one instead, as suggested by @HotLicks:

protected void createContents() {
    ...
    Statement statement = null;
    try {
        statement = connect.createStatement();
        final Statement innerStatement = statement;
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    ...
}

But you should...

Reconsider your approach. If statement variable won't be used until btnInsert button is pressed then it doesn't make sense to create a connection before this actually happens. You could use all local variables like this:

btnInsert.addMouseListener(new MouseAdapter() {
   @Override
   public void mouseDown(MouseEvent e) {
       try {
           Class.forName("com.mysql.jdbc.Driver");
           try (Connection connect = DriverManager.getConnection(...);
                Statement statement = connect.createStatement()) {

                // execute the statement here

           } catch (SQLException ex) {
               ex.printStackTrace();
           }

       } catch (ClassNotFoundException ex) {
           e.printStackTrace();
       }
});

Where can I download mysql jdbc jar from?

If you have WL server installed, pick it up from under
\Oracle\Middleware\wlserver_10.3\server\lib\mysql-connector-java-commercial-5.1.17-bin.jar

Otherwise, download it from:
http://www.java2s.com/Code/JarDownload/mysql/mysql-connector-java-5.1.17-bin.jar.zip

How to create an alert message in jsp page after submit process is complete

in your servlet

 request.setAttribute("submitDone","done");
 return mapping.findForward("success");

In your jsp

<c:if test="${not empty submitDone}">
  <script>alert("Form submitted");
</script></c:if>

java.lang.ClassNotFoundException: org.springframework.core.io.Resource

Make sure, following jar file included in your class path and lib folder.

spring-core-3.0.5.RELEASE.jar

enter image description here

if you are using maven, make sure you have included dependency for spring-core-3xxxxx.jar file

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-core</artifactId>
 <version>${org.springframework.version}</version>
</dependency>

Note : Replace ${org.springframework.version} with version number.

Checking Maven Version

Type the command mvn -version directly in your maven directory, you probably haven't added it to your PATH. Here are explained details of how to add maven to your PATH variable (I guess you use Windows because you are talking about CMD).

java.io.StreamCorruptedException: invalid stream header: 54657374

You can't expect ObjectInputStream to automagically convert text into objects. The hexadecimal 54657374 is "Test" as text. You must be sending it directly as bytes.

java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why?

For Java 7 you can simply omit the Class.forName() statement as it is not really required.

For Java 8 you cannot use the JDBC-ODBC Bridge because it has been removed. You will need to use something like UCanAccess instead. For more information, see

Manipulating an Access database from Java without ODBC

java.lang.ClassNotFoundException: Didn't find class on path: dexpathlist

Ashik abbas answer (disable Instant Run) work for me, but i need Instant Run, finally i found solution which is helpful for me. just disable minifyEnabled. go to build.gradle(Module: app) in debug block and disable minifyEnabled:

debug {
            minifyEnabled false

        }

org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

It's an eclipse setup issue, not a Jersey issue.

From this thread ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer

Right click your eclipse project Properties -> Deployment Assembly -> Add -> Java Build Path Entries -> Gradle Dependencies -> Finish.

So Eclipse wasn't using the Gradle dependencies when Apache was starting .

SEVERE: ContainerBase.addChild: start:org.apache.catalina.LifecycleException: Failed to start error

I'm not sure what happened in your case that fixed the issue, but your issue was on this line:

Caused by: java.lang.NoClassDefFoundError: javax/xml/rpc/handler/soap/SOAPMessageContext

You need to add jaxrpc-api.jar to your /libs or add

<dependency>
    <groupId>javax.xml</groupId>
    <artifactId>jaxrpc-api</artifactId>
    <version>x.x.x</version>
</dependency>

to your maven dependencies.

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

I had the same issue, for me this fixed the issue:
right click on the project ->maven -> update project

maven -> update project

java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication Maven

Mine was caused by a corrupt Maven repository.

I deleted everything under C:\Users\<me>\.m2\repository.

Then did an Eclipse Maven Update, and it worked first time.

So it was simply spring-boot.jar got corrupted.

java.lang.ClassNotFoundException: org.apache.jsp.index_jsp

An addition to the other answers that didn't work for me: In my case the error occurred due to permission errors. The project got deployed while the tomcat was running as root, later when started as tomcat user I got the error from the question title.

Solution in my case was to set the right permissions, e.x. on a unix system:

cd <tomcat-dir>
chown -R <tomcat-user> *

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject Error

You need to include xmlbeans-xxx.jar and if you have downloaded the POI binary zip, you will get the xmlbeans-xxx.jar in ooxml-lib folder (eg: \poi-3.11\ooxml-lib)

This jar is used for XML binding which is applicable for .xlsx files.

JDBC ODBC Driver Connection

Didn't work with ODBC-Bridge for me too. I got the way around to initialize ODBC connection using ODBC driver.

 import java.sql.*;  
 public class UserLogin
 {
     public static void main(String[] args)
     {
        try
        {    
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            // C:\\databaseFileName.accdb" - location of your database 
           String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";

            // specify url, username, pasword - make sure these are valid 
            Connection conn = DriverManager.getConnection(url, "username", "password");

            System.out.println("Connection Succesfull");
         } 
         catch (Exception e) 
         {
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());

          }
      }
  }

How to change the background color of Action Bar's Option Menu in Android 4.2?

Following are the changes required in your theme for changing action bar & overflow menu background color. You need to configure "android:background" of actionBarStyle & popupMenuStyle

<application
            android:name="...."
            android:theme="@style/AppLightTheme">

<style name="AppLightTheme" parent="android:Theme.Holo.Light">      
        <item name="android:actionBarStyle">@style/ActionBarLight</item>
        <item name="android:popupMenuStyle">@style/ListPopupWindowLight</item>
</style>

<style name="ActionBarLight" parent="android:style/Widget.Holo.Light.ActionBar">
        <item name="android:background">@color/white</item>
</style>


<style name="ListPopupWindowLight"parent="@android:style/Widget.Holo.Light.ListPopupWindow">
        <item name="android:background">@color/white</item>
</style>

Android ClassNotFoundException: Didn't find class on path

This following method worked for me

  • Right click on your project and select properties
  • The "Properties for " panel will open. From the menu on the left go to Java Build Path -> Order and Export
  • From the list below uncheck the box next to "Android Dependencies"
  • Finally clean your project and run

Java program to connect to Sql Server and running the sample query From Eclipse

Add sqlserver.jar Here is link

As the name suggests ClassNotFoundException in Java is a subclass of java.lang.Exception and Comes when Java Virtual Machine tries to load a particular class and doesn't found the requested class in classpath.

Another important point about this Exception is that, It is a checked Exception and you need to provide explicitly Exception handling while using methods which can possibly throw ClassNotFoundException in java either by using try-catch block or by using throws clause.

Oracle docs

public class ClassNotFoundException
 extends ReflectiveOperationException

Thrown when an application tries to load in a class through its string name using:

  • The forName method in class Class.
  • The findSystemClass method in class ClassLoader .
  • The loadClass method in class ClassLoader.

but no definition for the class with the specified name could be found.

Integrate ZXing in Android Studio

this tutorial help me to integrate to android studio: http://wahidgazzah.olympe.in/integrating-zxing-in-your-android-app-as-standalone-scanner/ if down try THIS

just add to AndroidManifest.xml

<activity
         android:name="com.google.zxing.client.android.CaptureActivity"
         android:configChanges="orientation|keyboardHidden"
         android:screenOrientation="landscape"
         android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
         android:windowSoftInputMode="stateAlwaysHidden" >
         <intent-filter>
             <action android:name="com.google.zxing.client.android.SCAN" />
             <category android:name="android.intent.category.DEFAULT" />
         </intent-filter>
     </activity>

Hope this help!.

A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war

Does the class org.apache.maven.shared.filtering.MavenFilteringException exist in file:/C:/Users/utopcu/.m2/repository/org/apache/maven/shared/maven-filtering/1.0-beta-2/maven-filtering-1.0-beta-2.jar?

The error message suggests that it doesn't. Maybe the JAR was corrupted somehow.

I'm also wondering where the version 1.0-beta-2 comes from; I have 1.0 on my disk. Try version 2.3 of the WAR plugin.

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]

Just go to the project Properties->Project Facets

  1. Uncheck the dynamic module, click apply.

  2. Maven->update the project.

java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer

Add this in pom

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-server</artifactId>
    <version>1.17.1</version>
</dependency>
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-core</artifactId>
    <version>1.17.1</version>
</dependency>
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-servlet</artifactId>
    <version>1.17.1</version>
</dependency>

How to solve java.lang.NoClassDefFoundError?

I use the FileSync plugin for Eclipse so I can live debug on Tomcat & I received NoClassFoundError because I had added a sync entry for the bin directory in the Eclipse workspace => classes in the metadata for Tomcat but hadn't also added a folder sync for the extlib directory in Eclipse =>

C:\Users\Stuart\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\webapps\myApp\WEB-INF\lib

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

The driver connector is not in your build path. Configure the build path and point it to the 'mysql-connector-java-5.1.25-bin.jar' (check the version which you are using). Alternatively you can use maven :D

How do I resolve ClassNotFoundException?

I deleted some unused imports and it fixed the problem for me. You can't not find a Class if you never look for it in the first place.

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)

Either remove the below code from the pom.xml or correct your java version to make it work.

  <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.0</version>
    <configuration>
      <source>1.6</source>
      <target>1.6</target>
    </configuration>
  </plugin>

java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger for JUnit test case for Java mail

com.sun.mail.util.MailLogger is part of JavaMail API. It is already included in EE environment (that's why you can use it on your live server), but it is not included in SE environment.

Oracle docs:

The JavaMail API is available as an optional package for use with Java SE platform and is also included in the Java EE platform.

99% that you run your tests in SE environment which means what you have to bother about adding it manually to your classpath when running tests.

If you're using maven add the following dependency (you might want to change version):

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.0</version>
</dependency>

Android Studio - Importing external Library/Jar

I had the problem not able to load jar file in libs folder in Android Studio. If you have added JAR file in libs folder, then just open build.gradle file and save it without editing anything else. If you have added this line

compile fileTree(dir: 'libs', include: ['*.jar'])

save it and clean the project .. In next build time Android Studio will load the JAR file.

Hope this helps.

Junit test case for database insert method with DAO and web service

@Test
public void testSearchManagementStaff() throws SQLException
{
    boolean res=true;
    ManagementDaoImp mdi=new ManagementDaoImp();
    boolean b=mdi.searchManagementStaff("[email protected]"," 123456");
    assertEquals(res,b);
}

How to run a maven created jar file using just the command line

1st Step: Add this content in pom.xml

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>2.1</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <transformers>
                            <transformer
                                implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                            </transformer>
                        </transformers>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

2nd Step : Execute this command line by line.

cd /go/to/myApp
mvn clean
mvn compile 
mvn package
java -cp target/myApp-0.0.1-SNAPSHOT.jar go.to.myApp.select.file.to.execute

java.lang.ClassNotFoundException:com.mysql.jdbc.Driver

The Problem is related to MySql Driver

Class.forName("com.mysql.jdbc.Driver");

Add the MySQL jdbc driver jar file in to your classpath.

Also i have this error on JDK. I build the ClassPath Properly then I put the "mysql-connector-java-5.1.25-bin" in dir "C:\Program Files\Java\jre7\lib\ext" in this dir i have my JDK. then compile and Run again then it's working fine.

How to add the JDBC mysql driver to an Eclipse project?

You can paste the .jar file of the driver in the Java setup instead of adding it to each project that you create. Paste it in C:\Program Files\Java\jre7\lib\ext or wherever you have installed java.

After this you will find that the .jar driver is enlisted in the library folder of your created project(JRE system library) in the IDE. No need to add it repetitively.

oracle.jdbc.driver.OracleDriver ClassNotFoundException

You can add a JAR which having above specified class exist e.g.ojdbc jar which supported by installed java version, also make sure that you have added it into classpath.

com.microsoft.sqlserver.jdbc.SQLServerDriver not found error

For me, it worked once I changed

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

to:

in POM

<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
    <version>6.1.0.jre8</version>
</dependency>

and then:

import com.microsoft.sqlserver.jdbc.SQLServerDriver;

...

DriverManager.registerDriver(SQLServerDriver());    
Connection connection = DriverManager.getConnection(connectionUrl); 

Eclipse JUnit - possible causes of seeing "initializationError" in Eclipse window

If you're using the xtend language (or some other JVM lang with type inference) and haven't explicitly defined the return type then it may be set to a non-void type because of the last expression, which will make JUnit fail.

java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

Just a quick comment: sometimes Maven does not copy the jstl-.jar to the WEB-INF folder even if the pom.xml has the entry for it.

I had to manually copy the JSTL jar to /WEB-INF/lib on the file system. That resolved the problem. The issue may be related to Maven war packaging plugin.

How to change already compiled .class file without decompile?

when you decompile and change the code you have to go on the root folder of your eclipse project and check your class in bin folder wich is on the same level as src. then open you original jar with zip tool ( 7zip is good for that ) and put the modified class in tha same package inside the jar.

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

I was getting same kinda error but after copying the ojdbc14.jar into lib folder, no more exception.(copy ojdbc14.jar from somewhere and paste it into lib folder inside WebContent.)

Unable instantiate android.gms.maps.MapFragment

try this

http://developer.android.com/tools/projects/projects-eclipse.html#ReferencingLibraryProject

I just added the project of google services and added a reference in my project property->Android

Execute jar file with multiple classpath libraries from command prompt

Regardless of the OS the below command should work:

java -cp "MyJar.jar;lib/*" com.mainClass

Always use quotes and please take attention that lib/*.jar will not work.

java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory

use maven it will download all the required jar files for you.

in this case you need the below jar files:

slf4j-log4j12-1.6.1.jar slf4j-api-1.6.1.jar

These jars will also depend on the cassandra version which you are running. There are dependencies with cassandra version , jar version and jdk version you use.

You can use : jdk1.6 with : cassandra 1.1.12 and the above jars.

Reference jars inside a jar

Add the jar files to your library(if using netbeans) and modify your manifest's file classpath as follows:

Class-Path: lib/derby.jar lib/derbyclient.jar lib/derbynet.jar lib/derbytools.jar

a similar answer exists here

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/JDBC_DBO]]

Posting since this solution may help somebody:

I faced a similar issue with the Tomcat 8.0. Seems the tomcat jar files might have corrupted. So I just downloaded the new Tomcat 8.0, unzipped it and configured it with my eclipse IDE. Also check the Project Facet under the preference menu.

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

I had to change my SQL setup (in my host, Dreamhost in my case) to allow the username to access the database from other hosts, not just Dreamhost since I'm running a program from the IDE on my computer. I did that for now by adding % to the list of Allowable Hosts. It now works!

How to run TestNG from command line

You will need to use semicolon as delimiter while specifying the jar and class file path in windows. This solved the issue.
Assuming the class file is under C:.

java -cp ".;C:\testng.jar" org.testng.TestNG testing.xml

How do I put all required JAR files in a library folder inside the final JAR file with Maven?

I found this answer to the question:

http://padcom13.blogspot.co.uk/2011/10/creating-standalone-applications-with.html

Not only do you get the dependent lib files in a lib folder, you also get a bin director with both a unix and a dos executable.

The executable ultimately calls java with a -cp argument that lists all of your dependent libs too.

The whole lot sits in an appasembly folder inside the target folder. Epic.

============= Yes I know this is an old thread, but it's still coming high on search results so I thought it might help someone like me.

Pentaho Data Integration SQL connection

In addition to the other answers here, here's how you can do it on Ubuntu (14.04):

sudo apt-get install libmysql-java

this will download mysql-connector-java-5.x.x.jar to /usr/share/java/, which i believe also automatically creates a symlink named mysql-connector-java.jar.

Then, create a symlink in /your/path/to/data-integration/lib/:

ln -s /usr/share/java/mysql-connector-java.jar /your/path/to/data-integration/lib/mysql-connector-java.jar

Class Not Found Exception when running JUnit test

I fixed my issue by running maven update. Right click project your project > Maven > Update Project

java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

It may be useful for someone, so I'll post it here. I was missing this dependency on my pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Maven error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher

Besides what @khmarbaise has pointed out, I think you have mistyped your JAVA_HOME. If you have installed in the default location, then there should be no "-" (hyphen) between jdk and 1.7.0_04. So it would be

JAVA_HOME C:\Program Files\Java\jdk1.7.0_04 

Eclipse Build Path Nesting Errors

I had the same issue and correct answer above did not work for me. What I did to resolve it was to go to Build Path->Configure Build Path and under the source tab I removed all the sources (which only had one source) and reconfigured them from there. I ended up removing the project from eclipse and import the maven project again in order to clear up the error.

java.lang.ClassNotFoundException: org.apache.log4j.Level

In my environment, I just added the two files to class path. And is work fine.

slf4j-jdk14-1.7.25.jar
slf4j-api-1.7.25.jar

NoClassDefFoundError on Maven dependency

Choosing to Project -> Clean should resolve this

java.lang.ClassNotFoundException: HttpServletRequest

So the problem is connected with the metadata errors of elcipse. Go to the metadata folder where this configuration is saved. For me one of the erorrs was that:

SEVERE: Error starting static Resources java.lang.IllegalArgumentException: Document base C:\Users\Cannibal\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\FoodQuantityService does not exist or is not a readable directory

So go there is in the workspace of your eclipse it is different for all and delete all its content . My services was named FoodQuantityService so I deleted all files in org.eclipse.wst.server.core but before that delete your server configuration from Eclipse

Delete current server configuration

Then create new configuration File->New->Other->Server select Tomcat and then projects which you want to be published. Start the server and everything will be ok.

java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient

I solved this issue for myself, I found there's was two files of http-client with different version of other dependent jar files. So there may version were collapsing between libraries files so remove all old/previous libraries files and re-add are jar files from lib folder of this zip file:

Donwload Zip file from here

The specified DSN contains an architecture mismatch between the Driver and Application. JAVA

I did encounter this problem. This is due to you computer architecture and the database architecture you are using.

If you're using 32 bits operating system then everything works well because you can only install 32 bits software. Problem comes when you're using the 64 bits operating system.

In order to solve this problem is simple - I took long time to discover this issue.

  1. Knowing your Operating System is 64 bits but your Microsoft Office is 32 bits.
  2. So in order for you to access your database using NetBean IDE (assuming you're using this), you need to install 32 bits JDK. If you have installed 64 bits, you have to uninstall it and install the 32 bits.

You're unable to access your database because your 64 bits JVM is not the same as 32 bit JVM.

To add your database into your system 1. Control Panel 2. Administrator Tools 3. Data Source (ODBC) right click on it change the target to \sysWOW64\odbcad32.exe change the start in to r%\SysWOW64

Then you should be able to run. Inform me if you have any problem with this.

Thank you!

Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

I had the same problem and resolved it adding this dependency.

<dependency>
    <groupId>javassist</groupId>
    <artifactId>javassist</artifactId>
    <version>3.12.1.GA</version>
</dependency>   

I am using hibernate 3.6 version.

NoClassDefFoundError for code in an Java library on Android

I have just figured out something with this error.

Just make sure that the library jar file contains the compiled R class under android.support.v7.appcompat package and copy all the res in the v7 appcompat support "project" in your ANDROID_SDK_HOME/extras/android/support/v7/appcompat folder.

I use Netbeans with the Android plugin and this solved my issue.

No suitable driver found for 'jdbc:mysql://localhost:3306/mysql

Just telling my resolution: in my case, the libraries and projects weren't being added automatically to the classpath (i don't know why), even clicking at the "add to build path" option. So I went on run -> run configurations -> classpath and added everything I needed through there.

java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory

This happened to me because I was using a Tomcat 5.5 catalina.sh file with a Tomcat 7 installation. Using the catalina.sh that came with the Tomcat 7 install fixed the problem.

The Network Adapter could not establish the connection when connecting with Oracle DB

If it is on a Linux box, I would suggest you add the database IP name and IP resolution to the /etc/hosts.

I have the same error and when we do the above, it works fine.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name

According to the stack trace, your issue is that your app cannot find org.apache.commons.dbcp.BasicDataSource, as per this line:

java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource

I see that you have commons-dbcp in your list of jars, but for whatever reason, your app is not finding the BasicDataSource class in it.

Listen to port via a Java socket

What do you actually want to achieve? What your code does is it tries to connect to a server located at 192.168.1.104:4000. Is this the address of a server that sends the messages (because this looks like a client-side code)? If I run fake server locally:

$ nc -l 4000

...and change socket address to localhost:4000, it will work and try to read something from nc-created server.

What you probably want is to create a ServerSocket and listen on it:

ServerSocket serverSocket = new ServerSocket(4000);
Socket socket = serverSocket.accept();

The second line will block until some other piece of software connects to your machine on port 4000. Then you can read from the returned socket. Look at this tutorial, this is actually a very broad topic (threading, protocols...)

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

I also had the same error. I had not added the below dependency in my POM file.

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.1.7.RELEASE</version>
  </dependency>

But My porject used to run even before I had added this dependency. But at one point it stopped and started giving the same above error.

If any one couldn't solve this error they can also solve by this link

How to initialize an array of objects in Java

Instead of

Player[PlayerCount] thePlayers;

you want

Player[] thePlayers = new Player[PlayerCount];

and

for(int i = 0; i < PlayerCount ; i++)
{
    thePlayers[i] = new Player(i);
}
return thePlayers;

should return the array initialized with Player instances.

EDIT:

Do check out this table on wikipedia on naming conventions for java that is widely used.

How do I run Java .class files?

To run Java class file from the command line, the syntax is:

java -classpath /path/to/jars <packageName>.<MainClassName>

where packageName (usually starts with either com or org) is the folder name where your class file is present.

For example if your main class name is App and Java package name of your app is com.foo.app, then your class file needs to be in com/foo/app folder (separate folder for each dot), so you run your app as:

$ java com.foo.app.App

Note: $ is indicating shell prompt, ignore it when typing

If your class doesn't have any package name defined, simply run as: java App.

If you've any other jar dependencies, make sure you specified your classpath parameter either with -cp/-classpath or using CLASSPATH variable which points to the folder with your jar/war/ear/zip/class files. So on Linux you can prefix the command with: CLASSPATH=/path/to/jars, on Windows you need to add the folder into system variable. If not set, the user class path consists of the current directory (.).


Practical example

Given we've created sample project using Maven as:

$ mvn archetype:generate -DgroupId=com.foo.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false 

and we've compiled our project by mvn compile in our my-app/ dir, it'll generate our class file is in target/classes/com/foo/app/App.class.

To run it, we can either specify class path via -cp or going to it directly, check examples below:

$ find . -name "*.class"
./target/classes/com/foo/app/App.class
$ CLASSPATH=target/classes/ java com.foo.app.App
Hello World!
$ java -cp target/classes com.foo.app.App
Hello World!
$ java -classpath .:/path/to/other-jars:target/classes com.foo.app.App
Hello World!
$ cd target/classes && java com.foo.app.App
Hello World!

To double check your class and package name, you can use Java class file disassembler tool, e.g.:

$ javap target/classes/com/foo/app/App.class
Compiled from "App.java"
public class com.foo.app.App {
  public com.foo.app.App();
  public static void main(java.lang.String[]);
}

Note: javap won't work if the compiled file has been obfuscated.

JUNIT Test class in Eclipse - java.lang.ClassNotFoundException

If you have a maven project try to run:

mvn clean compile

and then in eclipse clean & build your project.

setting system property

System.setProperty("gate.home", "/some/directory");

For more information, see:

I am getting "java.lang.ClassNotFoundException: com.google.gson.Gson" error even though it is defined in my classpath

I ran into the above error when building and running inside Eclipse, where everything seemed to be fine, with the exception of this error. However, I discovered that a Maven build failed and that I needed to include Gson in my pom.xml. After fixing the pom.xml, everything fell into place.

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo

This error also occurs when you use of ActionBarActivity but assigned a non AppCompat style.

To fix this just set your apps style parent to an Theme.AppCompat one like this.:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light">
    <!-- Customize your theme here. -->
</style>

java.lang.NoClassDefFoundError in junit

  1. Make sure Environment variable JUNIT_HOME is set to c:\JUNIT.
  2. then In run configuration > select classpath > add external jars junit-4.11.jar

java.lang.ClassNotFoundException on working app

I used a supertype method that was declared 'final' in one of my Activities (specifically the 'isResumed()' method). The actual error showed in LogCat only after restarting my development device.

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

Cheesle is right. There's no way for the classloader to find the embedded jars. If you put enough debug commands on the command line you should be able to see the 'java' command failing to add the jars to a classpath

What you want to make is sometimes called an 'uberjar'. I found one-jar as a tool to help make them, but I haven't tried it. Sure there's many other approaches.

Adding a library/JAR to an Eclipse Android project

Setting up a Library Project

A library project is a standard Android project, so you can create a new one in the same way as you would a new application project.

When you are creating the library project, you can select any application name, package, and set other fields as needed, as shown in figure 1.

Next, set the project's properties to indicate that it is a library project:

In the Package Explorer, right-click the library project and select Properties. In the Properties window, select the "Android" properties group at left and locate the Library properties at right. Select the "is Library" checkbox and click Apply. Click OK to close the Properties window. The new project is now marked as a library project. You can begin moving source code and resources into it, as described in the sections below.

How to convert Integer to int?

Perhaps you have the compiler settings for your IDE set to Java 1.4 mode even if you are using a Java 5 JDK? Otherwise I agree with the other people who already mentioned autoboxing/unboxing.

java.lang.ClassNotFoundException: org.eclipse.core.runtime.adaptor.EclipseStarter

my case seems to be invalid JRE version.

1.7+ required while I launched with 1.6

plus: I filtered some plugin jars which might be required. so changed to select all

Could not find main class HelloWorld

Java is not finding where your compiled class file (HelloWorld.class) is. It uses the directories and JAR-files in the CLASSPATH environment variable for searching if no -cp or -classpath option is given when running java.exe.

You don't need the rt.jar in the CLASSPATH, these was only needed for older versions of Java. You can leave it undefined and the current working directory will be used, or just add . (a single point), separated by ';', to the CLASSPATH variable to indicate the current directory:

CLASSPATH: .;C:\...\some.jar

Alternatively you can use the -cp or -classpath option:

java -cp . HelloWorld

And, as Andreas wrote, JAVA_HOME is not needed by Java, just for some third-party tools like ant (but should point to the correct location).

java.io.StreamCorruptedException: invalid stream header: 7371007E

when I send only one object from the client to server all works well.

when I attempt to send several objects one after another on the same stream I get StreamCorruptedException.

Actually, your client code is writing one object to the server and reading multiple objects from the server. And there is nothing on the server side that is writing the objects that the client is trying to read.

Connect Java to a MySQL database

Initialize database constants

Create constant properties database username, password, URL and drivers, polling limit etc.

// init database constants
// com.mysql.jdbc.Driver
private static final String DATABASE_DRIVER = "com.mysql.cj.jdbc.Driver";
private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database_name";
private static final String USERNAME = "root";
private static final String PASSWORD = "";
private static final String MAX_POOL = "250"; // set your own limit

Initialize Connection and Properties

Once the connection is established, it is better to store for reuse purpose.

// init connection object
private Connection connection;
// init properties object
private Properties properties;

Create Properties

The properties object hold the connection information, check if it is already set.

// create properties
private Properties getProperties() {
    if (properties == null) {
        properties = new Properties();
        properties.setProperty("user", USERNAME);
        properties.setProperty("password", PASSWORD);
        properties.setProperty("MaxPooledStatements", MAX_POOL);
    }
    return properties;
}

Connect the Database

Now connect to database using the constants and properties initialized.

// connect database
public Connection connect() {
    if (connection == null) {
        try {
            Class.forName(DATABASE_DRIVER);
            connection = DriverManager.getConnection(DATABASE_URL, getProperties());
        } catch (ClassNotFoundException | SQLException e) {
            // Java 7+
            e.printStackTrace();
        }
    }
    return connection;
}

Disconnect the database

Once you are done with database operations, just close the connection.

// disconnect database
public void disconnect() {
    if (connection != null) {
        try {
            connection.close();
            connection = null;
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Everything together

Use this class MysqlConnect directly after changing database_name, username and password etc.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class MysqlConnect {
    // init database constants
    private static final String DATABASE_DRIVER = "com.mysql.cj.jdbc.Driver";
    private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database_name";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "";
    private static final String MAX_POOL = "250";

    // init connection object
    private Connection connection;
    // init properties object
    private Properties properties;

    // create properties
    private Properties getProperties() {
        if (properties == null) {
            properties = new Properties();
            properties.setProperty("user", USERNAME);
            properties.setProperty("password", PASSWORD);
            properties.setProperty("MaxPooledStatements", MAX_POOL);
        }
        return properties;
    }

    // connect database
    public Connection connect() {
        if (connection == null) {
            try {
                Class.forName(DATABASE_DRIVER);
                connection = DriverManager.getConnection(DATABASE_URL, getProperties());
            } catch (ClassNotFoundException | SQLException e) {
                e.printStackTrace();
            }
        }
        return connection;
    }

    // disconnect database
    public void disconnect() {
        if (connection != null) {
            try {
                connection.close();
                connection = null;
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

How to Use?

Initialize the database class.

// !_ note _! this is just init
// it will not create a connection
MysqlConnect mysqlConnect = new MysqlConnect();

Somewhere else in your code ...

String sql = "SELECT * FROM `stackoverflow`";
try {
    PreparedStatement statement = mysqlConnect.connect().prepareStatement(sql);
    ... go on ...
    ... go on ...
    ... DONE ....
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    mysqlConnect.disconnect();
}

This is all :) If anything to improve edit it! Hope this is helpful.

How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception

My issue was a little different. Instead of jdbc:oracle:thin:@server:port/service i had it as server:port/service.

Missing was jdbc:oracle:thin:@ in url attribute in GlobalNamingResources.Resource. But I overlooked tomcat exception's

java.sql.SQLException: Cannot create JDBC driver of class 'oracle.jdbc.driver.OracleDriver' for connect URL 'server:port/service'

How to read input with multiple lines in Java

The problem you're having running from the command line is that you don't put ".class" after your class file.

java Practice 10 12

should work - as long as you're somewhere java can find the .class file.

Classpath issues are a whole 'nother story. If java still complains that it can't find your class, go to the same directory as your .class file (and it doesn't appear you're using packages...) and try -

java -cp . Practice 10 12

org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class

The problem is that there is no class called com.service.SempediaSearchManager on your webapp's classpath. The most likely root causes are:

  • the fully qualified classname is incorrect in /WEB-INF/Sempedia-service.xml; i.e. the class name is something else,

  • the class is not in your webapp's /WEB-INF/classes directory tree or a JAR file in the /WEB-INF/lib directory.

EDIT : The only other thing that I can think of is that the ClassDefNotFoundException may actually be a result of an earlier class loading / static initialization problem. Check your log files for the first stack trace, and look the nested exceptions, i.e. the "caused by" chain. [If a class load fails one time and you or Spring call Class.forName() again for some reason, then Java won't actually try to load a second time. Instead you will get a ClassDefNotFoundException stack trace that does not explain the real cause of the original failure.]

If you are still stumped, you should take Eclipse out of the picture. Create the WAR file in the form that you are eventually going to deploy it, then from the command line:

  1. manually shutdown Tomcat

  2. clean out your Tomcat webapp directory,

  3. copy the WAR file into the webapp directory,

  4. start Tomcat.

If that doesn't solve the problem directly, look at the deployed webapp directory on Tomcat to verify that the "missing" class is in the right place.

Strange "java.lang.NoClassDefFoundError" in Eclipse

I see that people have already talked about class path. Since there is no accepted answer, I assume it is not related to class path. So I would like to add that, not having package directive can also lead to class not found errors.

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

If you knew the Class of ImplementationType you could create an instance of it. So what you are trying to do is not possible.

ClassNotFoundException com.mysql.jdbc.Driver

I too struggled with the same problem and finally got the solution for it. Just copy the MySql-Connector.jar into Tomcat's lib folder, and then remove the jar from the webapp's lib folder, and then, run the project.

Getting java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory exception

Setting the scope to compile did it for me

<dependency>
  <groupId>commons-logging</groupId>
  <artifactId>commons-logging</artifactId>
  <version>1.2</version>
  <scope>compile</scope>
</dependency>

How to connect SQLite with Java?

You have to download and add the SQLite JDBC driver to your classpath.
You can download from here https://bitbucket.org/xerial/sqlite-jdbc/downloads

If you use Gradle, you will only have to add the SQLite dependency:

dependencies {
    compile 'org.xerial:sqlite-jdbc:3.8.11.2'
} 

Next thing you have to do is to initialize the driver:

try {
    Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException eString) {
    System.err.println("Could not init JDBC driver - driver not found");
}

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

A NoClassDefFoundError (NCDFE) happens when your code runs "new Y()" and it can't find the Y class.

It may simply be that Y is missing from your class loader like the other comments suggest, but it could be that the Y class isn't signed or has an invalid signature, or that Y is loaded by a different classloader not visible to your code, or even that Y depends on Z which couldn't be loaded for any of the above reasons.

If this happens, then the JVM will remember the result of loading X (NCDFE) and it will simply throw a new NCDFE every time you ask for Y without telling you why:

class a {
  static class b {}
  public static void main(String args[]) {
    System.out.println("First attempt new b():");
    try {new b(); } catch(Throwable t) {t.printStackTrace();}
    System.out.println("\nSecond attempt new b():");
    try {new b(); } catch(Throwable t) {t.printStackTrace();}
  }
}

save this as a.java somewhere

The code simply tries to instantiate a new "b" class twice, other than that, it doesn't have any bugs, and it doesn't do anything.

Compile the code with javac a.java, Then run a by invoking java -cp . a -- it should just print out two lines of text, and it should run fine without errors.

Then delete the "a$b.class" file (or fill it with garbage, or copy a.class over it) to simulate the missing or corrupted class. Here's what happens:

First attempt new b():
java.lang.NoClassDefFoundError: a$b
    at a.main(a.java:5)
Caused by: java.lang.ClassNotFoundException: a$b
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
    ... 1 more

Second attempt new b():
java.lang.NoClassDefFoundError: a$b
    at a.main(a.java:7)

The first invocation results in a ClassNotFoundException (thrown by the class loader when it can't find the class), which must be wrapped in an unchecked NoClassDefFoundError, since the code in question (new b()) should just work.

The second attempt will of course fail too, but as you can see the wrapped exception is no more, because the ClassLoader seems to remember failed class loaders. You see only the NCDFE with absolutely no clue as to what really happened.

So if you ever see a NCDFE with no root cause, you need to see if you can track back to the very first time the class was loaded to find the cause of the error.

How to execute a java .class from the command line

If you have in your java source

package mypackage;

and your class is hello.java with

public class hello {

and in that hello.java you have

 public static void main(String[] args) {

Then (after compilation) changeDir (cd) to the directory where your hello.class is. Then

java -cp . mypackage.hello

Mind the current directory and the package name before the class name. It works for my on linux mint and i hope on the other os's also

Thanks Stack overflow for a wealth of info.

Java: Unresolved compilation problem

The major part is correctly answered by Thorbjørn Ravn Andersen.

This answer tries to shed light on the remaining question: how could the class file with errors end up in the jar?

Each build (mvn&javac or eclipse) signals in its specific way when it hits a compile error, and will refuse to create a Jar file from it (or at least prominently alert you). The most likely cause for silently getting class files with errors into a jar is by concurrent operation of Maven and Eclipse.

If you have Eclipse open while running a mvn build, you should disable Project > Build Automatically until mvn completes.

EDIT: Let's try to split the riddle into three parts:

(1) What is the meaning of "java.lang.Error: Unresolved compilation problem"

This has been explained by Thorbjørn Ravn Andersen. There is no doubt that Eclipse found an error at compile time.

(2) How can an eclipse-compiled class file end up in jar file created by maven (assuming maven is not configured to used ecj for compilation)?

This could happen either by invoking maven with no or incomplete cleaning. Or, an automatic Eclipse build could react to changes in the filesystem (done by maven) and re-compile a class, before maven proceeds to collect class files into the jar (this is what I meant by "concurrent operation" in my original answer).

(3) How come there is a compile error, but mvn clean succeeds?

Again several possibilities: (a) compilers don't agree whether or not the source code is legal, or (b) Eclipse compiles with broken settings like incomplete classpath, wrong Java compliance etc. Either way a sequence of refresh and clean build in Eclipse should surface the problem.

Eclipse - java.lang.ClassNotFoundException

Make sure if your test class working before , but you facing issue all of sudden. then clean your project and build it again. Make sure project has been configured in build path as read above article.

NoClassDefFoundError while trying to run my jar with java.exe -jar...what's wrong?

The -jar option is mutually exclusive of -classpath. See an old description here

-jar

Execute a program encapsulated in a JAR file. The first argument is the name of a JAR file instead of a startup class name. In order for this option to work, the manifest of the JAR file must contain a line of the form Main-Class: classname. Here, classname identifies the class having the public static void main(String[] args) method that serves as your application's starting point.

See the Jar tool reference page and the Jar trail of the Java Tutorial for information about working with Jar files and Jar-file manifests.

When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.

A quick and dirty hack is to append your classpath to the bootstrap classpath:

-Xbootclasspath/a:path

Specify a colon-separated path of directires, JAR archives, and ZIP archives to append to the default bootstrap class path.

However, as @Dan rightly says, the correct solution is to ensure your JARs Manifest contains the classpath for all JARs it will need.

Creating pdf files at runtime in c#

There is a new project, RazorPDF which can be used from ASP.NET MVC. It is available as nuget package (search for RazorPDF).

Here is more info: http://nyveldt.com/blog/post/Introducing-RazorPDF

IMPORTANT UPDATE as @DenNukem pointed out, it depends on iTextsharp, I forgot to edit answer when I found that out (when I tried to use it), so if your project is not open source and eligible for their AGPL licence, it will probably be too expensive to use.

Error "can't load package: package my_prog: found packages my_prog and main"

Yes, each package must be defined in its own directory.

The source structure is defined in How to Write Go Code.

A package is a component that you can use in more than one program, that you can publish, import, get from an URL, etc. So it makes sense for it to have its own directory as much as a program can have a directory.

Wait until page is loaded with Selenium WebDriver for Python

From selenium/webdriver/support/wait.py

driver = ...
from selenium.webdriver.support.wait import WebDriverWait
element = WebDriverWait(driver, 10).until(
    lambda x: x.find_element_by_id("someId"))

Which data type for latitude and longitude?

In PostGIS, for points with latitude and longitude there is geography datatype.

To add a column:

alter table your_table add column geog geography;

To insert data:

insert into your_table (geog) values ('SRID=4326;POINT(longitude latitude)');

4326 is Spatial Reference ID that says it's data in degrees longitude and latitude, same as in GPS. More about it: http://epsg.io/4326

Order is Longitude, Latitude - so if you plot it as the map, it is (x, y).

To find closest point you need first to create spatial index:

create index on your_table using gist (geog);

and then request, say, 5 closest to a given point:

select * 
from your_table 
order by geog <-> 'SRID=4326;POINT(lon lat)' 
limit 5;

How do I escape a string inside JavaScript code inside an onClick handler?

Use hidden spans, one each for each of the parameters <%itemid%> and <%itemname%> and write their values inside them.

For example, the span for <%itemid%> would look like <span id='itemid' style='display:none'><%itemid%></span> and in the javascript function SelectSurveyItem to pick the arguments from these spans' innerHTML.

Find closest previous element jQuery

see http://api.jquery.com/prev/

var link = $("#me").parent("div").prev("h3").find("b");
alert(link.text());

see http://jsfiddle.net/gBwLq/

For Restful API, can GET method use json data?

To answer your question, yes you may pass JSON in the URI as part of a GET request (provided you URL-encode). However, considering your reason for doing this is due to the length of the URI, using JSON will be self-defeating (introducing more characters than required).

I suggest you send your parameters in body of a POST request, either in regular CGI style (param1=val1&param2=val2) or JSON (parsed by your API upon receipt)

Send and receive messages through NSNotificationCenter in Objective-C?

There is also the possibility of using blocks:

NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
[[NSNotificationCenter defaultCenter] 
     addObserverForName:@"notificationName" 
     object:nil
     queue:mainQueue
     usingBlock:^(NSNotification *notification)
     {
          NSLog(@"Notification received!");
          NSDictionary *userInfo = notification.userInfo;

          // ...
     }];

Apple's documentation

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

Probably the most elegant way of doing this is to do it in one step. See val().

$("#text").val(function(i, val) {
  return val.replace('.', ':');
});

compared to:

var val = $("#text").val();
$("#text").val(val.replace('.', ':'));

From the docs:

.val( function(index, value) )

function(index, value)A function returning the value to set.

This method is typically used to set the values of form fields. For <select multiple="multiple"> elements, multiple s can be selected by passing in an array.

The .val() method allows us to set the value by passing in a function. As of jQuery 1.4, the function is passed two arguments, the current element's index and its current value:

$('input:text.items').val(function(index, value) {
  return value + ' ' + this.className;
});

This example appends the string " items" to the text inputs' values.

This requires jQuery 1.4+.

Which Architecture patterns are used on Android?

There are various patterns used in Android framework like:

  • Broadcast receiver uses Observer pattern
  • Remoter service invocation uses Proxy pattern
  • View and view group uses Composite pattern
  • Media framework uses Facade pattern

Class 'ViewController' has no initializers in swift

The Swift Programming Language states:

Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created. Stored properties cannot be left in an indeterminate state.

You can set an initial value for a stored property within an initializer, or by assigning a default property value as part of the property’s definition.

Therefore, you can write:

class myClass {

    var delegate: AppDelegate //non-optional variable

    init() {
        delegate = UIApplication.sharedApplication().delegate as AppDelegate
    }

}

Or:

class myClass {

    var delegate = UIApplication.sharedApplication().delegate as AppDelegate //non-optional variable

    init() {
        println("Hello")
    }

}

Or:

class myClass {

    var delegate : AppDelegate! //implicitly unwrapped optional variable set to nil when class is initialized

    init() {
        println("Hello")
    }

    func myMethod() {
        delegate = UIApplication.sharedApplication().delegate as AppDelegate
    }

}

But you can't write the following:

class myClass {

    var delegate : AppDelegate //non-optional variable

    init() {
        println("Hello")
    }

    func myMethod() {
        //too late to assign delegate as an non-optional variable
        delegate = UIApplication.sharedApplication().delegate as AppDelegate
    }

}

Disable/enable an input with jQuery?

Disable:

$('input').attr('readonly', true); // Disable it.
$('input').addClass('text-muted'); // Gray it out with bootstrap.

Enable:

$('input').attr('readonly', false); // Enable it.
$('input').removeClass('text-muted'); // Back to normal color with bootstrap.

How to pass a file path which is in assets folder to File(String path)?

AFAIK, you can't create a File from an assets file because these are stored in the apk, that means there is no path to an assets folder.

But, you can try to create that File using a buffer and the AssetManager (it provides access to an application's raw asset files).

Try to do something like:

AssetManager am = getAssets();
InputStream inputStream = am.open("myfoldername/myfilename");
File file = createFileFromInputStream(inputStream);

private File createFileFromInputStream(InputStream inputStream) {

   try{
      File f = new File(my_file_name);
      OutputStream outputStream = new FileOutputStream(f);
      byte buffer[] = new byte[1024];
      int length = 0;

      while((length=inputStream.read(buffer)) > 0) {
        outputStream.write(buffer,0,length);
      }

      outputStream.close();
      inputStream.close();

      return f;
   }catch (IOException e) {
         //Logging exception
   }

   return null;
}

Let me know about your progress.

Excel: the Incredible Shrinking and Expanding Controls

Grouping the controls appears to work for me. I would upvote or comment but SO won't let me. Note that this issue comes up often if you use W8 display scaling and have a high resolution laptop and older monitor.

Clang vs GCC - which produces faster binaries?

The fact that Clang compiles code faster may not be as important as the speed of the resulting binary. However, here is a series of benchmarks.

What is float in Java?

In Java, when you type a decimal number as 3.6, its interpreted as a double. double is a 64-bit precision IEEE 754 floating point, while floatis a 32-bit precision IEEE 754 floating point. As a float is less precise than a double, the conversion cannot be performed implicitly.

If you want to create a float, you should end your number with f (i.e.: 3.6f).

For more explanation, see the primitive data types definition of the Java tutorial.

How to enable Logger.debug() in Log4j

Put a file named log4j.xml into your classpath. Contents are e.g.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <appender name="stdout" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ABSOLUTE} %5p %t %c{1}:%L - %m%n"/>
        </layout>
    </appender>

    <root>
        <level value="debug"/>
        <appender-ref ref="stdout"/>
    </root>

</log4j:configuration>

Get the Highlighted/Selected text

Getting the text the user has selected is relatively simple. There's no benefit to be gained by involving jQuery since you need nothing other than the window and document objects.

function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    return text;
}

If you're interested in an implementation that will also deal with selections in <textarea> and texty <input> elements, you could use the following. Since it's now 2016 I'm omitting the code required for IE <= 8 support but I've posted stuff for that in many places on SO.

_x000D_
_x000D_
function getSelectionText() {_x000D_
    var text = "";_x000D_
    var activeEl = document.activeElement;_x000D_
    var activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null;_x000D_
    if (_x000D_
      (activeElTagName == "textarea") || (activeElTagName == "input" &&_x000D_
      /^(?:text|search|password|tel|url)$/i.test(activeEl.type)) &&_x000D_
      (typeof activeEl.selectionStart == "number")_x000D_
    ) {_x000D_
        text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd);_x000D_
    } else if (window.getSelection) {_x000D_
        text = window.getSelection().toString();_x000D_
    }_x000D_
    return text;_x000D_
}_x000D_
_x000D_
document.onmouseup = document.onkeyup = document.onselectionchange = function() {_x000D_
  document.getElementById("sel").value = getSelectionText();_x000D_
};
_x000D_
Selection:_x000D_
<br>_x000D_
<textarea id="sel" rows="3" cols="50"></textarea>_x000D_
<p>Please select some text.</p>_x000D_
<input value="Some text in a text input">_x000D_
<br>_x000D_
<input type="search" value="Some text in a search input">_x000D_
<br>_x000D_
<input type="tel" value="4872349749823">_x000D_
<br>_x000D_
<textarea>Some text in a textarea</textarea>
_x000D_
_x000D_
_x000D_

Setting values of input fields with Angular 6

As an alternate you can use reactive forms. Here is an example: https://stackblitz.com/edit/angular-pqb2xx

Template

<form [formGroup]="mainForm" ng-submit="submitForm()">
  Global Price: <input type="number" formControlName="globalPrice">
  <button type="button" [disabled]="mainForm.get('globalPrice').value === null" (click)="applyPriceToAll()">Apply to all</button>
  <table border formArrayName="orderLines">
  <ng-container *ngFor="let orderLine of orderLines let i=index" [formGroupName]="i">
    <tr>
       <td>{{orderLine.time | date}}</td>
       <td>{{orderLine.quantity}}</td>
       <td><input formControlName="price" type="number"></td>
    </tr>
</ng-container>
  </table>
</form>

Component

import { Component } from '@angular/core';
import { FormGroup, FormControl, FormArray } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 6';
  mainForm: FormGroup;
  orderLines = [
    {price: 10, time: new Date(), quantity: 2},
    {price: 20, time: new Date(), quantity: 3},
    {price: 30, time: new Date(), quantity: 3},
    {price: 40, time: new Date(), quantity: 5}
    ]
  constructor() {
    this.mainForm = this.getForm();
  }

  getForm(): FormGroup {
    return new FormGroup({
      globalPrice: new FormControl(),
      orderLines: new FormArray(this.orderLines.map(this.getFormGroupForLine))
    })
  }

  getFormGroupForLine(orderLine: any): FormGroup {
    return new FormGroup({
      price: new FormControl(orderLine.price)
    })
  }

  applyPriceToAll() {
    const formLines = this.mainForm.get('orderLines') as FormArray;
    const globalPrice = this.mainForm.get('globalPrice').value;
    formLines.controls.forEach(control => control.get('price').setValue(globalPrice));
    // optionally recheck value and validity without emit event.
  }

  submitForm() {

  }
}

Ruby: kind_of? vs. instance_of? vs. is_a?

kind_of? and is_a? are synonymous.

instance_of? is different from the other two in that it only returns true if the object is an instance of that exact class, not a subclass.

Example:

  • "hello".is_a? Object and "hello".kind_of? Object return true because "hello" is a String and String is a subclass of Object.
  • However "hello".instance_of? Object returns false.

hidden field in php

You absolutely can, I use this approach a lot w/ both JavaScript and PHP.

Field definition:

<input type="hidden" name="foo" value="<?php echo $var;?>" />

Access w/ PHP:

$_GET['foo'] or $_POST['foo']

Also: Don't forget to sanitize your inputs if they are going into a database. Feel free to use my routine: https://github.com/niczak/PHP-Sanitize-Post/blob/master/sanitize.php

Cheers!

How do I supply an initial value to a text field?

If you want to handle multiple TextInputs as asked by @MRT in the comment to the accepted answer, you can create a function that takes an initial value and returns a TextEditingController like this:

initialValue(val) {
  return TextEditingController(text: val);
}

Then, set this function as the controller for the TextInput and supply its initial value there like this:

controller: initialValue('Some initial value here....')

You can repeat this for the other TextInputs.

Centering elements in jQuery Mobile

The best option would be to put any element you want to be centered in a div like this:

        <div class="center">
            <img src="images/logo.png" />
        </div>

and css or inline style:

.center {  
      text-align:center  
 }

Open File in Another Directory (Python)

import os
import os.path
import shutil

You find your current directory:

d = os.getcwd() #Gets the current working directory

Then you change one directory up:

os.chdir("..") #Go up one directory from working directory

Then you can get a tupple/list of all the directories, for one directory up:

o = [os.path.join(d,o) for o in os.listdir(d) if os.path.isdir(os.path.join(d,o))] # Gets all directories in the folder as a tuple

Then you can search the tuple for the directory you want and open the file in that directory:

for item in o:
    if os.path.exists(item + '\\testfile.txt'):
    file = item + '\\testfile.txt'

Then you can do stuf with the full file path 'file'

Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()'

Reinstalling Microsoft.AspNet.WebHelpers works for me

Update-Package –reinstall Microsoft.AspNet.WebHelpers

Distinct in Linq based on only one field of the table

You can try this:table1.GroupBy(t => t.Text).Select(shape => shape.r)).Distinct();

Interactive shell using Docker Compose

If anyone from the future also wanders up here:

docker-compose exec container_name sh

or

docker-compose exec container_name bash

or you can run single lines like

docker-compose exec container_name php -v

That is after you already have your containers up and running

number several equations with only one number

First of all, you probably don't want the align environment if you have only one column of equations. In fact, your example is probably best with the cases environment. But to answer your question directly, used the aligned environment within equation - this way the outside environment gives the number:

\begin{equation}
  \begin{aligned}
  w^T x_i + b &\geq 1-\xi_i &\text{ if }& y_i=1,  \\
  w^T x_i + b &\leq -1+\xi_i & \text{ if } &y_i=-1,
  \end{aligned}
\end{equation}

The documentation of the amsmath package explains this and more.

Import Excel spreadsheet columns into SQL Server database

Microsoft suggest several methods:

  • SQL Server Data Transformation Services (DTS)
  • Microsoft SQL Server 2005 Integration Services (SSIS)
  • SQL Server linked servers
  • SQL Server distributed queries
  • ActiveX Data Objects (ADO) and the Microsoft OLE DB Provider for SQL Server
  • ADO and the Microsoft OLE DB Provider for Jet 4.0

If the wizard (DTS) isn't working (and I think it should) you could try something like this http://www.devasp.net/net/articles/display/771.html which basically suggests doing something like

INSERT INTO [tblTemp] ([Column1], [Column2], [Column3], [Column4])

SELECT A.[Column1], A.[Column2], A.[Column3], A.[Column4]
FROM OPENROWSET 
('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=D:\Excel.xls;HDR=YES', 'select * from [Sheet1$]') AS A;

Trying to fire the onload event on script tag

You should set the src attribute after the onload event, f.ex:

el.onload = function() { //...
el.src = script;

You should also append the script to the DOM before attaching the onload event:

$body.append(el);
el.onload = function() { //...
el.src = script;

Remember that you need to check readystate for IE support. If you are using jQuery, you can also try the getScript() method: http://api.jquery.com/jQuery.getScript/

"Submit is not a function" error in JavaScript

Possible solutions -
1.Make sure that you don't have any other element with name/id as submit.
2.Try to call the function as onClick = "return submitAction();"
3.document.getElementById("form-name").submit();

XAMPP permissions on Mac OS X?

Go to htdocs folder, right click, get info, click to unlock the padlock icon, type your password, under sharing permission change the priviledge for everyone to read & write, on the cog wheel button next to the + and - icons, click and select apply to all enclosed items, click to accept security request, close get info. Now xampp can write and read your root folder.

Note:

  1. If you copy a new folder into the htdocs after this, you need to repeat the process for that folder to have write permission.

  2. When you move your files to the live server, you need to also chmod the appropriate files & folders on the server as well.

enabling cross-origin resource sharing on IIS7

One thing that has not been mentioned in these answers is that if you are using IIS and have sub applications with their own separate web.config, you may need to have a web.config in the parent directory containing the following code.

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*"/>
    <add name="Access-Control-Allow-Headers" value="Content-Type"/>
    <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS"/>
  </customHeaders>
</httpProtocol>

adb devices command not working

HTC One m7 running fresh Cyanogenmod 11.

Phone is connected USB and tethering my data connection.

Then I get this surprise:

cinder@ultrabook:~/temp/htc_m7/2015-11-11$ adb shell
error: insufficient permissions for device

cinder@ultrabook:~/temp/htc_m7/2015-11-11$ adb devices
List of devices attached
????????????    no permissions

SOLUTION: Turn tethering OFF on phone.

cinder@ultrabook:~/temp/htc_m7/2015-11-11$ adb devices
List of devices attached
HT36AW908858    device

-didSelectRowAtIndexPath: not being called

None of these answers worked for me. After about an hour, I figured out something very insidious:

I have a table view inside a cell of another table view. I decided to make an enclosing view that contains the inner table view, among other things. I called this view contentView and hooked it up in the xib.

Turns out that UITableViewCell already has a contentView and does weird things with it. The issue resolved itself when I renamed the property to mainContentView and reconnected the view to this renamed property.

How to connect to remote Redis server?

In Case of password also we need to pass one more parameter

redis-cli -h host -p port -a password

Descending order by date filter in AngularJs

see w3schools samples: https://www.w3schools.com/angular/angular_filters.asp https://www.w3schools.com/angular/tryit.asp?filename=try_ng_filters_orderby_click

then add the "reverse" flag:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<p>Click the table headers to change the sorting order:</p>

<div ng-app="myApp" ng-controller="namesCtrl">

<table border="1" width="100%">
<tr>
<th ng-click="orderByMe('name')">Name</th>
<th ng-click="orderByMe('country')">Country</th>
</tr>
<tr ng-repeat="x in names | orderBy:myOrderBy:reverse">
<td>{{x.name}}</td>
<td>{{x.country}}</td>
</tr>
</table>

</div>

<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.names = [
        {name:'Jani',country:'Norway'},
        {name:'Carl',country:'Sweden'},
        {name:'Margareth',country:'England'},
        {name:'Hege',country:'Norway'},
        {name:'Joe',country:'Denmark'},
        {name:'Gustav',country:'Sweden'},
        {name:'Birgit',country:'Denmark'},
        {name:'Mary',country:'England'},
        {name:'Kai',country:'Norway'}
        ];

    $scope.reverse=false;
    $scope.orderByMe = function(x) {

        if($scope.myOrderBy == x) {
            $scope.reverse=!$scope.reverse;
        }
        $scope.myOrderBy = x;
    }
});
</script>

</body>
</html>

$(form).ajaxSubmit is not a function

I'm guessing you don't have a jquery form plugin included. ajaxSubmit isn't a core jquery function, I believe.

Something like this : http://jquery.malsup.com/form/

UPD

<script src="http://malsup.github.com/jquery.form.js"></script> 

Get item in the list in Scala?

Use parentheses:

data(2)

But you don't really want to do that with lists very often, since linked lists take time to traverse. If you want to index into a collection, use Vector (immutable) or ArrayBuffer (mutable) or possibly Array (which is just a Java array, except again you index into it with (i) instead of [i]).

What does the following Oracle error mean: invalid column index

If that's a SQLException thrown by Java, it's most likely because you are trying to get or set a value from a ResultSet, but the index you are using isn't within the range.

For example, you might be trying to get the column at index 3 from the result set, but you only have two columns being returned from the SQL query.

Angular 4 Pipe Filter

Here is a working plunkr with a filter and sortBy pipe. https://plnkr.co/edit/vRvnNUULmBpkbLUYk4uw?p=preview

As developer033 mentioned in a comment, you are passing in a single value to the filter pipe, when the filter pipe is expecting an array of values. I would tell the pipe to expect a single value instead of an array

export class FilterPipe implements PipeTransform {
    transform(items: any[], term: string): any {
        // I am unsure what id is here. did you mean title?
        return items.filter(item => item.id.indexOf(term) !== -1);
    }
}

I would agree with DeborahK that impure pipes should be avoided for performance reasons. The plunkr includes console logs where you can see how much the impure pipe is called.

Android: Align button to bottom-right of screen using FrameLayout?

You can't do it with FrameLayout.

From spec:

http://developer.android.com/reference/android/widget/FrameLayout.html

"FrameLayout is designed to block out an area on the screen to display a single item. You can add multiple children to a FrameLayout, but all children are pegged to the top left of the screen."

Why not to use RelativeLayout?

Windows XP or later Windows: How can I run a batch file in the background with no window displayed?

Run it under a different user name, using "runas" or by scheduling it under a different user in Windows Scheduled Tasks.

Intro to GPU programming

Check out CUDA by NVidia, IMO it's the easiest platform to do GPU programming. There are tons of cool materials to read. http://www.nvidia.com/object/cuda_home.html

Hello world would be to do any kind of calculation using GPU.

Hope that helps.

SQL INSERT INTO from multiple tables

I would suggest instead of creating a new table, you just use a view that combines the two tables, this way if any of the data in table 1 or table 2 changes, you don't need to update the third table:

CREATE VIEW dbo.YourView
AS
    SELECT  t1.Name, t1.Age, t1.Sex, t1.City, t1.ID, t2.Number
    FROM    Table1 t1
            INNER JOIN Table2 t2
                ON t1.ID = t2.ID;

If you could have records in one table, and not in the other, then you would need to use a full join:

CREATE VIEW dbo.YourView
AS
    SELECT  t1.Name, t1.Age, t1.Sex, t1.City, ID = ISNULL(t1.ID, t2.ID), t2.Number
    FROM    Table1 t1
            FULL JOIN Table2 t2
                ON t1.ID = t2.ID;

If you know all records will be in table 1 and only some in table 2, then you should use a LEFT JOIN:

CREATE VIEW dbo.YourView
AS
    SELECT  t1.Name, t1.Age, t1.Sex, t1.City, t1.ID, t2.Number
    FROM    Table1 t1
            LEFT JOIN Table2 t2
                ON t1.ID = t2.ID;

If you know all records will be in table 2 and only some in table 2 then you could use a RIGHT JOIN

CREATE VIEW dbo.YourView
AS
    SELECT  t1.Name, t1.Age, t1.Sex, t1.City, t2.ID, t2.Number
    FROM    Table1 t1
            RIGHT JOIN Table2 t2
                ON t1.ID = t2.ID;

Or just reverse the order of the tables and use a LEFT JOIN (I find this more logical than a right join but it is personal preference):

CREATE VIEW dbo.YourView
AS
    SELECT  t1.Name, t1.Age, t1.Sex, t1.City, t2.ID, t2.Number
    FROM    Table2 t2
            LEFT JOIN Table1 t1
                ON t1.ID = t2.ID;

Simple division in Java - is this a bug or a feature?

You're using integer division.

Try 7.0/10 instead.

Search for "does-not-contain" on a DataFrame in pandas

I had to get rid of the NULL values before using the command recommended by Andy above. An example:

df = pd.DataFrame(index = [0, 1, 2], columns=['first', 'second', 'third'])
df.ix[:, 'first'] = 'myword'
df.ix[0, 'second'] = 'myword'
df.ix[2, 'second'] = 'myword'
df.ix[1, 'third'] = 'myword'
df

    first   second  third
0   myword  myword   NaN
1   myword  NaN      myword 
2   myword  myword   NaN

Now running the command:

~df["second"].str.contains(word)

I get the following error:

TypeError: bad operand type for unary ~: 'float'

I got rid of the NULL values using dropna() or fillna() first and retried the command with no problem.

Changing Shell Text Color (Windows)

Been looking into this for a while and not got any satisfactory answers, however...

1) ANSI escape sequences do work in a terminal on Linux

2) if you can tolerate a limited set of colo(u)rs try this:

print("hello", end=''); print("error", end='', file=sys.stderr); print("goodbye")

In idle "hello" and "goodbye" are in blue and "error" is in red.

Not fantastic, but good enough for now, and easy!

Split Spark Dataframe string column into multiple columns

pyspark.sql.functions.split() is the right approach here - you simply need to flatten the nested ArrayType column into multiple top-level columns. In this case, where each array only contains 2 items, it's very easy. You simply use Column.getItem() to retrieve each part of the array as a column itself:

split_col = pyspark.sql.functions.split(df['my_str_col'], '-')
df = df.withColumn('NAME1', split_col.getItem(0))
df = df.withColumn('NAME2', split_col.getItem(1))

The result will be:

col1 | my_str_col | NAME1 | NAME2
-----+------------+-------+------
  18 |  856-yygrm |   856 | yygrm
 201 |  777-psgdg |   777 | psgdg

I am not sure how I would solve this in a general case where the nested arrays were not the same size from Row to Row.

How to extract custom header value in Web API message handler?

The line below throws exception if the key does not exists.

IEnumerable<string> headerValues = request.Headers.GetValues("MyCustomID");

Work around :

Include System.Linq;

IEnumerable<string> headerValues;
var userId = string.Empty;

     if (request.Headers.TryGetValues("MyCustomID", out headerValues))
     {
         userId = headerValues.FirstOrDefault();
     }           

How to refresh an access form

"Requery" is indeed what you what you want to run, but you could do that in Form A's "On Got Focus" event. If you have code in your Form_Load, perhaps you can move it to Form_Got_Focus.

"use database_name" command in PostgreSQL

In pgAdmin you can also use

SET search_path TO your_db_name;

How to edit a text file in my terminal

You can open the file again using vi helloworld.txt and then use cat /path/your_file to view it.

Is it possible to install both 32bit and 64bit Java on Windows 7?

As stated by pnt you can have multiple versions of both 32bit and 64bit Java installed at the same time on the same machine.

Taking it further from there: Here's how it might be possible to set any runtime parameters for each of those installations:

You can run javacpl.exe or javacpl.cpl of the respective Java-version itself (bin-folder). The specific control panel opens fine. Adding parameters there is possible.

How to sort an STL vector?

A pointer-to-member allows you to write a single comparator, which can work with any data member of your class:

#include <algorithm>
#include <vector>
#include <string>
#include <iostream>

template <typename T, typename U>
struct CompareByMember {
    // This is a pointer-to-member, it represents a member of class T
    // The data member has type U
    U T::*field;
    CompareByMember(U T::*f) : field(f) {}
    bool operator()(const T &lhs, const T &rhs) {
        return lhs.*field < rhs.*field;
    }
};

struct Test {
    int a;
    int b;
    std::string c;
    Test(int a, int b, std::string c) : a(a), b(b), c(c) {}
};

// for convenience, this just lets us print out a Test object
std::ostream &operator<<(std::ostream &o, const Test &t) {
    return o << t.c;
}

int main() {
    std::vector<Test> vec;
    vec.push_back(Test(1, 10, "y"));
    vec.push_back(Test(2, 9, "x"));

    // sort on the string field
    std::sort(vec.begin(), vec.end(), 
        CompareByMember<Test,std::string>(&Test::c));
    std::cout << "sorted by string field, c: ";
    std::cout << vec[0] << " " << vec[1] << "\n";

    // sort on the first integer field
    std::sort(vec.begin(), vec.end(), 
        CompareByMember<Test,int>(&Test::a));
    std::cout << "sorted by integer field, a: ";
    std::cout << vec[0] << " " << vec[1] << "\n";

    // sort on the second integer field
    std::sort(vec.begin(), vec.end(), 
        CompareByMember<Test,int>(&Test::b));
    std::cout << "sorted by integer field, b: ";
    std::cout << vec[0] << " " << vec[1] << "\n";
}

Output:

sorted by string field, c: x y
sorted by integer field, a: y x
sorted by integer field, b: x y

How can I select random files from a directory in bash?

I use this: it uses temporary file but goes deeply in a directory until it find a regular file and return it.

# find for a quasi-random file in a directory tree:

# directory to start search from:
ROOT="/";  

tmp=/tmp/mytempfile    
TARGET="$ROOT"
FILE=""; 
n=
r=
while [ -e "$TARGET" ]; do 
    TARGET="$(readlink -f "${TARGET}/$FILE")" ; 
    if [ -d "$TARGET" ]; then
      ls -1 "$TARGET" 2> /dev/null > $tmp || break;
      n=$(cat $tmp | wc -l); 
      if [ $n != 0 ]; then
        FILE=$(shuf -n 1 $tmp)
# or if you dont have/want to use shuf:
#       r=$(($RANDOM % $n)) ; 
#       FILE=$(tail -n +$(( $r + 1 ))  $tmp | head -n 1); 
      fi ; 
    else
      if [ -f "$TARGET"  ] ; then
        rm -f $tmp
        echo $TARGET
        break;
      else 
        # is not a regular file, restart:
        TARGET="$ROOT"
        FILE=""
      fi
    fi
done;

How to get number of rows inserted by a transaction

@@ROWCOUNT will give the number of rows affected by the last SQL statement, it is best to capture it into a local variable following the command in question, as its value will change the next time you look at it:

DECLARE @Rows int
DECLARE @TestTable table (col1 int, col2 int)
INSERT INTO @TestTable (col1, col2) select 1,2 union select 3,4
SELECT @Rows=@@ROWCOUNT
SELECT @Rows AS Rows,@@ROWCOUNT AS [ROWCOUNT]

OUTPUT:

(2 row(s) affected)
Rows        ROWCOUNT
----------- -----------
2           1

(1 row(s) affected)

you get Rows value of 2, the number of inserted rows, but ROWCOUNT is 1 because the SELECT @Rows=@@ROWCOUNT command affected 1 row

if you have multiple INSERTs or UPDATEs, etc. in your transaction, you need to determine how you would like to "count" what is going on. You could have a separate total for each table, a single grand total value, or something completely different. You'll need to DECLARE a variable for each total you want to track and add to it following each operation that applies to it:

--note there is no error handling here, as this is a simple example
DECLARE @AppleTotal  int
DECLARE @PeachTotal  int

SELECT @AppleTotal=0,@PeachTotal=0

BEGIN TRANSACTION

INSERT INTO Apple (col1, col2) Select col1,col2 from xyz where ...
SET @AppleTotal=@AppleTotal+@@ROWCOUNT

INSERT INTO Apple (col1, col2) Select col1,col2 from abc where ...
SET @AppleTotal=@AppleTotal+@@ROWCOUNT

INSERT INTO Peach (col1, col2) Select col1,col2 from xyz where ...
SET @PeachTotal=@PeachTotal+@@ROWCOUNT

INSERT INTO Peach (col1, col2) Select col1,col2 from abc where ...
SET @PeachTotal=@PeachTotal+@@ROWCOUNT

COMMIT

SELECT @AppleTotal AS AppleTotal, @PeachTotal AS PeachTotal

What is the best place for storing uploaded images, SQL database or disk file system?

We use A. I would put it on a shared drive (unless you don't plan on running more than one server).

If the time comes when this won't scale for you then you can investigate caching mechanisms.

MySQL joins and COUNT(*) from another table

Maybe I am off the mark here and not understanding the OP but why are you joining tables?

If you have a table with members and this table has a column named "group_id", you can just run a query on the members table to get a count of the members grouped by the group_id.

SELECT group_id, COUNT(*) as membercount 
FROM members 
GROUP BY group_id 
HAVING membercount > 4

This should have the least overhead simply because you are avoiding a join but should still give you what you wanted.

If you want the group details and description etc, then add a join from the members table back to the groups table to retrieve the name would give you the quickest result.

How to create a listbox in HTML without allowing multiple selection?

Remove the multiple="multiple" attribute and add SIZE=6 with the number of elements you want

you may want to check this site

http://www.htmlcodetutorial.com/forms/_SELECT.html

how can I enable PHP Extension intl?

Download the files and try to install them. One or two files may fail to install.

http://www.microsoft.com/en-sg/download/details.aspx?id=30679

Multiple separate IF conditions in SQL Server

To avoid syntax errors, be sure to always put BEGIN and END after an IF clause, eg:

IF (@A!= @SA)
   BEGIN
   --do stuff
   END
IF (@C!= @SC)
   BEGIN
   --do stuff
   END

... and so on. This should work as expected. Imagine BEGIN and END keyword as the opening and closing bracket, respectively.

PDO mysql: How to know if insert was successful

Use id as primary key with auto increment

$stmt->execute();
$insertid = $conn->lastInsertId();

incremental id is always bigger than zero even on first record so that means it will always return a true value for id coz bigger than zero means true in PHP

if ($insertid)
   echo "record inserted successfully";
else
   echo "record insertion failed";

saving a file (from stream) to disk using c#

I have to quote Jon (the master of c#) Skeet:

Well, the easiest way would be to open a file stream and then use:

byte[] data = memoryStream.ToArray(); fileStream.Write(data, 0, data.Length);

That's relatively inefficient though, as it involves copying the buffer. It's fine for small streams, but for huge amounts of data you should consider using:

fileStream.Write(memoryStream.GetBuffer(), 0, memoryStream.Position);

How to define optional methods in Swift protocol?

Slightly off topic from the original question, but it builds off Antoine’s idea and I thought it might help someone.

You can also make computed properties optional for structs with protocol extensions.

You can make a property on the protocol optional

protocol SomeProtocol {
    var required: String { get }
    var optional: String? { get }
}

Implement the dummy computed property in the protocol extension

extension SomeProtocol {
    var optional: String? { return nil }
}

And now you can use structs that do or don’t have the optional property implemented

struct ConformsWithoutOptional {
    let required: String
}

struct ConformsWithOptional {
    let required: String
    let optional: String?
}

I’ve also written up how to do optional properties in Swift protocols on my blog, which I’ll keep updated in case things change through the Swift 2 releases.

Representing EOF in C code?

I have been researching a lot about the EOF signal. In the book on Programming in C by Dennis Ritchie it is first encountered while introducing putchar() and getchar() commands. It basically marks the end of the character string input.

For eg. Let us write a program that seeks two numerical inputs and prints their sum. You'll notice after each numerical input you press Enter to mark the signal that you have completed the iput action. But while working with character strings Enter is read as just another character ['\n': newline character]. To mark the termination of input you enter ^Z(Ctrl + Z on keyboard) in a completely new line and then enter. That signals the next lines of command to get executed.

#include <stdio.h>

int main()
{
char c;
int i = 0;
printf("INPUT:\t");
c = getchar();

while (c != EOF)
{
   ++i;
   c = getchar();
   
};

printf("NUMBER OF CHARACTERS %d.", i);

return 0;}

The above is the code to count number of characters including '\n'(newline) and '\t'( space) characters. If you don't wanna count the newline characters do this :

#include <stdio.h>

int main()
{
char c;
int i = 0;
printf("INPUT:\t");
c = getchar();

while (c != EOF)
{
    if (c != '\n')
    {
        ++i;
    }

    c = getchar();
    };

printf("NUMBER OF CHARACTERS %d.", i);

return 0;}. 

NOW THE MAIN THINK HOOW TO GIVE INPUT. IT'S SIMPLE: Write all the story you want then go in a new line and enter ^Z and then enter again.

Java: how to initialize String[]?

I believe you just migrated from C++, Well in java you have to initialize a data type(other then primitive types and String is not a considered as a primitive type in java ) to use them as according to their specifications if you don't then its just like an empty reference variable (much like a pointer in the context of C++).

public class StringTest {
    public static void main(String[] args) {
        String[] errorSoon = new String[100];
        errorSoon[0] = "Error, why?";
        //another approach would be direct initialization
        String[] errorsoon = {"Error , why?"};   
    }
}

Display more Text in fullcalendar

Here's my code for popup using qTip2 and eventMouseover:

$(document).ready(function() {
    // Setup FullCalendar
    // Setup FullCalendar
    (function() {
        var date = new Date();
        var d = date.getDate();
        var m = date.getMonth();
        var y = date.getFullYear();
        var day=date.toLocaleDateString(); 

        var tooltip = $('<div/>').qtip({
            id: 'fullcalendar',
            prerender: true,
            content: {
                text: ' ',
                title: {
                    button: true
                }
            },
            position: {
                my: 'bottom center',
                at: 'top center',
                target: 'mouse',
                viewport: $('#fullcalendar'),
                adjust: {
                    mouse: false,
                    scroll: false
                }
            },
            show: false,
            hide: false,
            style: 'qtip-light'
        }).qtip('api');

        $('#fullcalendar').fullCalendar({
            editable: true,
             disableDragging: true,
            height: 600,
            header: {
                left: 'title',
                center: '',
                right: 'today prev,next'
            },

            dayClick: function() { tooltip.hide() },
            eventResizeStart: function() { tooltip.hide() },
            eventDragStart: function() { tooltip.hide() },
            viewDisplay: function() { tooltip.hide() },
            events: [
                {
                    title: 'All Day Event',
                    start: new Date(2014, 3, 1)
                },
                {
                    title: 'Long Event',
                    start: new Date(y, m, d-5),
                    end: new Date(y, m, d-2)
                },
                {
                    id: 999,
                    title: 'Repeating Event',
                    start: new Date(y, m, d+4, 16, 0),
                    allDay: false
                },
                {
                    title: 'Meeting',
                    start: new Date(y, m, d, 10, 30),
                    allDay: false
                },
                {
                    title: 'Spring Membership Conference',
                    start: new Date(y, m, d+6, 7,0),
                    end: new Date(y, m, d+6, 13,0),
                    allDay: false,
                    description:'save the date! Join us for our Annual Membership Conference. Breakfast will be served beginning at 7:30 a.m. Featuring The EFEC Belief System & Our Pledge lunch'
                },
                {
                    title: 'Birthday Party',
                    start: new Date(y, m, d+1, 19, 0),
                    end: new Date(y, m, d+1, 22, 30),
                    allDay: false
                }
            ],
            eventMouseover : function(data, event, view) {
                var content = 
                '<p>'+data.description +'<p>'+
                '<h3>'+data.title+'</h3>' + 
                    '<p><b>Start:</b> '+data.start+'<br />' + 
                    (data.end && '<p><b>End:</b> '+data.end+'</p>' || '');

                tooltip.set({
                    'content.text': content
                })
                .reposition(event).show(event);
            },
        });
    }());
});

How to cast/convert pointer to reference in C++

foo(*ob);

You don't need to cast it because it's the same Object type, you just need to dereference it.

How to enter ssh password using bash?

Double check if you are not able to use keys.

Otherwise use expect:

#!/usr/bin/expect -f
spawn ssh [email protected]
expect "assword:"
send "mypassword\r"
interact

HTML / CSS Popup div on text click

DEMO

In the content area you can provide whatever you want to display in it.

_x000D_
_x000D_
.black_overlay {_x000D_
  display: none;_x000D_
  position: absolute;_x000D_
  top: 0%;_x000D_
  left: 0%;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  background-color: black;_x000D_
  z-index: 1001;_x000D_
  -moz-opacity: 0.8;_x000D_
  opacity: .80;_x000D_
  filter: alpha(opacity=80);_x000D_
}_x000D_
.white_content {_x000D_
  display: none;_x000D_
  position: absolute;_x000D_
  top: 25%;_x000D_
  left: 25%;_x000D_
  width: 50%;_x000D_
  height: 50%;_x000D_
  padding: 16px;_x000D_
  border: 16px solid orange;_x000D_
  background-color: white;_x000D_
  z-index: 1002;_x000D_
  overflow: auto;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <title>LIGHTBOX EXAMPLE</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <p>This is the main content. To display a lightbox click <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">here</a>_x000D_
  </p>_x000D_
  <div id="light" class="white_content">This is the lightbox content. <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">Close</a>_x000D_
  </div>_x000D_
  <div id="fade" class="black_overlay"></div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

What is the difference between MySQL, MySQLi and PDO?

Those are different APIs to access a MySQL backend

  • The mysql is the historical API
  • The mysqli is a new version of the historical API. It should perform better and have a better set of function. Also, the API is object-oriented.
  • PDO_MySQL, is the MySQL for PDO. PDO has been introduced in PHP, and the project aims to make a common API for all the databases access, so in theory you should be able to migrate between RDMS without changing any code (if you don't use specific RDBM function in your queries), also object-oriented.

So it depends on what kind of code you want to produce. If you prefer object-oriented layers or plain functions...

My advice would be

  1. PDO
  2. MySQLi
  3. mysql

Also my feeling, the mysql API would probably being deleted in future releases of PHP.

MySQL - count total number of rows in php

use num_rows to get correct count for queries with conditions

$result = $connect->query("select * from table where id='$iid'");
$count=$result->num_rows;
echo "$count";

Meaning of "n:m" and "1:n" in database design

Imagine you have have a Book model and a Page model,

1:N means:
One book can have **many** pages. One page can only be in **one** book.


N:N means:
One book can have **many** pages. And one page can be in **many** books.

Python 2,3 Convert Integer to "bytes" Cleanly

You can use the struct's pack:

In [11]: struct.pack(">I", 1)
Out[11]: '\x00\x00\x00\x01'

The ">" is the byte-order (big-endian) and the "I" is the format character. So you can be specific if you want to do something else:

In [12]: struct.pack("<H", 1)
Out[12]: '\x01\x00'

In [13]: struct.pack("B", 1)
Out[13]: '\x01'

This works the same on both python 2 and python 3.

Note: the inverse operation (bytes to int) can be done with unpack.

How to align title at center of ActionBar in default theme(Theme.Holo.Light)

I had the same problem, and because of the "Home" button added automatically in the toolbar, my text was not exactly entered.

I fixed it the dirty way but it works well in my case. I simply added a margin to the right of my TextView to compensate for the home button on the left. Here's my toolbar layout :

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:elevation="1dp"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    app:layout_collapseMode="pin"
    android:gravity="center"
    android:background="@color/mainBackgroundColor"
    android:fitsSystemWindows="true" >

    <com.lunabee.common.utils.LunabeeShadowTextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginRight="?attr/actionBarSize"
        android:gravity="center"
        style="@style/navigation.toolbar.title" />

</android.support.v7.widget.Toolbar>

Gradle to execute Java class (without modifying build.gradle)

You just need to use the Gradle Application plugin:

apply plugin:'application'
mainClassName = "org.gradle.sample.Main"

And then simply gradle run.

As Teresa points out, you can also configure mainClassName as a system property and run with a command line argument.

How do I get the project basepath in CodeIgniter

Change your default controller which is in config file.

i.e : config/routes.php

$route['default_controller'] = "Your controller name";

Hope this will help.

How to restart Postgresql

You can also restart postgresql by using this command, should work on both the versions :

sudo service postgresql start

Cannot simply use PostgreSQL table name ("relation does not exist")

You must write schema name and table name in qutotation mark. As below:

select * from "schemaName"."tableName";

List of standard lengths for database fields

Just looking though my email archives, there are a number of pretty long "first" names (of course what is meant by first is variable by culture). One example is Krishnamurthy - which is 13 letters long. A good guess might be 20 to 25 letters based on this. Email should be much longer since you might have [email protected]. Also, gmail and some other mail programs allow you to use [email protected] where "sometag" is anything you want to put there so that you can use it to sort incoming emails. I frequently run into web forms that don't allow me to put in my full email address without considering any tags. So, if you need a fixed email field maybe something like [email protected] in characters for a total of 90 characters (if I did my math right!).

Mongodb find() query : return only unique values (no duplicates)

I think you can use db.collection.distinct(fields,query)

You will be able to get the distinct values in your case for NetworkID.

It should be something like this :

Db.collection.distinct('NetworkID')

How to reset the state of a Redux store?

My take to keep Redux from referencing to the same variable of the initial state:

// write the default state as a function
const defaultOptionsState = () => ({
  option1: '',
  option2: 42,
});

const initialState = {
  options: defaultOptionsState() // invoke it in your initial state
};

export default (state = initialState, action) => {

  switch (action.type) {

    case RESET_OPTIONS:
    return {
      ...state,
      options: defaultOptionsState() // invoke the default function to reset this part of the state
    };

    default:
    return state;
  }
};

How to Handle Button Click Events in jQuery?

You have to put the event handler in the $(document).ready() event:

$(document).ready(function() {
    $("#btnSubmit").click(function(){
        alert("button");
    }); 
});

Changing nav-bar color after scrolling?

_x000D_
_x000D_
$(window).on('activate.bs.scrollspy', function (e,obj) {_x000D_
_x000D_
  if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) {_x000D_
    return;_x000D_
  }_x000D_
  _x000D_
  var isBGLight = $(obj.relatedTarget).hasClass('nav_white');_x000D_
  var isBGDark = $(obj.relatedTarget).hasClass('nav_blue');_x000D_
  $('.menu').removeClass('nav_white');_x000D_
  $('.menu').removeClass('nav_blue');_x000D_
  if(isBGDark)_x000D_
  {_x000D_
    $('.menu').addClass('nav_white');_x000D_
  }else if(isBGLight)_x000D_
  {_x000D_
    $('.menu').addClass('nav_blue');_x000D_
  }_x000D_
  /*var isScrolled = $(document).scrollTop() > 1;_x000D_
    $('.menu').toggleClass('scrolled', isScrolled);_x000D_
    $(".demos").toggleClass("demo");_x000D_
    $(".demos").toggleClass("demo1");_x000D_
  var posicionActual = $(document).scrollTop();_x000D_
  $.each($('.nav_transparent'),function(){_x000D_
    if ($(this).position().top < posicionActual){_x000D_
      $("nav.menu").removeClass("nav_white");_x000D_
      $("nav.menu").removeClass("nav_blue");_x000D_
      $("nav.menu").addClass("nav_transparent");_x000D_
      $(".demos").removeClass("demo");_x000D_
      $(".demos").addClass("demo1");_x000D_
      $(".cls").removeClass("cls2");_x000D_
      $(".cls").addClass("cls1");_x000D_
      $(".cl").removeClass("cl2");_x000D_
      $(".cl").addClass("cl1");_x000D_
      $(".hamb-bottom").css({"background-color": "#fff"});_x000D_
      $(".hamb-middle").css({"background-color": "#fff"});_x000D_
      $(".hamb-top").css({"background-color": "#fff"});_x000D_
    }_x000D_
  });_x000D_
  $.each($('.nav_blue'),function(){_x000D_
    if ($(this).position().top <= posicionActual){_x000D_
      $("nav.menu").removeClass("nav_transparent");_x000D_
      $("nav.menu").removeClass("nav_white");_x000D_
      $("nav.menu").addClass("nav_blue");_x000D_
      $(".demos").removeClass("demo1");_x000D_
      $(".demos").addClass("demo");_x000D_
      $(".cls").removeClass("cls2");_x000D_
      $(".cls").addClass("cls1");_x000D_
      $(".cl").removeClass("cl2");_x000D_
      $(".cl").addClass("cl1");_x000D_
      $(".hamb-bottom").css({"background-color": "#fff"});_x000D_
      $(".hamb-middle").css({"background-color": "#fff"});_x000D_
      $(".hamb-top").css({"background-color": "#fff"});_x000D_
    }_x000D_
  });_x000D_
  $.each($('.nav_white'),function(){_x000D_
    if ($(this).position().top <= posicionActual){_x000D_
      $("nav.menu").removeClass("nav_blue");_x000D_
      $("nav.menu").removeClass("nav_transparent");_x000D_
      $("nav.menu").addClass("nav_white");_x000D_
      $(".demos").removeClass("demo");_x000D_
      $(".demos").addClass("demo1");_x000D_
      $(".cls").removeClass("cls1");_x000D_
      $(".cls").addClass("cls2");_x000D_
      $(".cl").removeClass("cl1");_x000D_
      $(".cl").addClass("cl2");_x000D_
      $(".hamb-bottom").css({"background-color": "#4285f4"});_x000D_
      $(".hamb-middle").css({"background-color": "#4285f4"});_x000D_
      $(".hamb-top").css({"background-color": "#4285f4"});_x000D_
    }_x000D_
  });*/_x000D_
});_x000D_
$(window).on("scroll", function(){_x000D_
  if($(document).scrollTop() < 10)_x000D_
    {_x000D_
      $('.nav').removeClass('nav_white');_x000D_
      $('.nav').removeClass('nav_blue');_x000D_
      $('.nav').removeClass('nav_transparent');_x000D_
      $('.nav').addClass('nav_transparent');_x000D_
  }_x000D_
});
_x000D_
_x000D_
_x000D_

the solutions, maybe

Why is HttpContext.Current null?

try to implement Application_AuthenticateRequest instead of Application_Start.

this method has an instance for HttpContext.Current, unlike Application_Start (which fires very soon in app lifecycle, soon enough to not hold a HttpContext.Current object yet).

hope that helps.

How to Implement Custom Table View Section Headers and Footers with Storyboard

Just use a prototype cell as your section header and / or footer.

  • add an extra cell and put your desired elements in it.
  • set the identifier to something specific (in my case SectionHeader)
  • implement the tableView:viewForHeaderInSection: method or the tableView:viewForFooterInSection: method
  • use [tableView dequeueReusableCellWithIdentifier:] to get the header
  • implement the tableView:heightForHeaderInSection: method.

(see screenhot)

-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    static NSString *CellIdentifier = @"SectionHeader"; 
    UITableViewCell *headerView = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (headerView == nil){
        [NSException raise:@"headerView == nil.." format:@"No cells with matching CellIdentifier loaded from your storyboard"];
    }
    return headerView;
}  

Edit: How to change the header title (commented question):

  1. Add a label to the header cell
  2. set the tag of the label to a specific number (e.g. 123)
  3. In your tableView:viewForHeaderInSection: method get the label by calling:
    UILabel *label = (UILabel *)[headerView viewWithTag:123]; 
  1. Now you can use the label to set a new title:
    [label setText:@"New Title"];

Scheduling Python Script to run every hour accurately

The Python standard library does provide sched and threading for this task. But this means your scheduler script will have be running all the time instead of leaving its execution to the OS, which may or may not be what you want.

How do I make a newline after a twitter bootstrap element?

May be the solution could be use a padding property.

<div class="well span6" style="padding-top: 50px">
    <h3>I wish this appeared on the next line without having to 
        gratuitously use BR!
    </h3>
</div>

Duplicate Symbols for Architecture arm64

From the errors, it would appear that the FacebookSDK.framework already includes the Bolts.framework classes. Try removing the additional Bolts.framework from the project.

Passing a varchar full of comma delimited values to a SQL Server IN function

I can suggest using WITH like this:

DECLARE @Delim char(1) = ',';
SET @Ids = @Ids + @Delim;

WITH CTE(i, ls, id) AS (
    SELECT 1, CHARINDEX(@Delim, @Ids, 1), SUBSTRING(@Ids, 1, CHARINDEX(@Delim, @Ids, 1) - 1)
    UNION ALL
    SELECT i + 1, CHARINDEX(@Delim, @Ids, ls + 1), SUBSTRING(@Ids, ls + 1, CHARINDEX(@Delim, @Ids, ls + 1) - CHARINDEX(@Delim, @Ids, ls) - 1)
    FROM CTE
    WHERE  CHARINDEX(@Delim, @Ids, ls + 1) > 1
)
SELECT t.*
FROM yourTable t
    INNER JOIN
    CTE c
    ON t.id = c.id;

Difference between parameter and argument

Generally, the parameters are what are used inside the function and the arguments are the values passed when the function is called. (Unless you take the opposite view — Wikipedia mentions alternative conventions when discussing parameters and arguments).

double sqrt(double x)
{
    ...
    return x;
}

void other(void)
{
     double two = sqrt(2.0);
}

Under my thesis, x is the parameter to sqrt() and 2.0 is the argument.

The terms are often used at least somewhat interchangeably.

Subset and ggplot2

With option 2 in @agstudy's answer now deprecated, defining data with a function can be handy.

library(plyr)
ggplot(data=dat) + 
  geom_line(aes(Value1, Value2, group=ID, colour=ID),
            data=function(x){x$ID %in% c("P1", "P3"))

This approach comes in handy if you wish to reuse a dataset in the same plot, e.g. you don't want to specify a new column in the data.frame, or you want to explicitly plot one dataset in a layer above the other.:

library(plyr)
ggplot(data=dat, aes(Value1, Value2, group=ID, colour=ID)) + 
  geom_line(data=function(x){x[!x$ID %in% c("P1", "P3"), ]}, alpha=0.5) +
  geom_line(data=function(x){x[x$ID %in% c("P1", "P3"), ]})

How to utilize date add function in Google spreadsheet?

=TO_DATE(TO_PURE_NUMBER(Insert Date cell, i.e. AM4)+[how many days to add in numbers, e.g. 3 days])

Looks like in practice:

=TO_DATE(TO_PURE_NUMBER(AM4)+3)

Essentially you are converting the date into a pure number and back into a date again.

Read url to string in few lines of java code

Or just use Apache Commons IOUtils.toString(URL url), or the variant that also accepts an encoding parameter.

How to sort an array of objects in Java?

Java 8


Using lambda expressions

Arrays.sort(myTypes, (a,b) -> a.name.compareTo(b.name));

Test.java

public class Test {

    public static void main(String[] args) {

        MyType[] myTypes = {
                new MyType("John", 2, "author1", "publisher1"),
                new MyType("Marry", 298, "author2", "publisher2"),
                new MyType("David", 3, "author3", "publisher3"),
        };

        System.out.println("--- before");
        System.out.println(Arrays.asList(myTypes));
        Arrays.sort(myTypes, (a, b) -> a.name.compareTo(b.name));
        System.out.println("--- after");
        System.out.println(Arrays.asList(myTypes));

    }

}

MyType.java

public class MyType {

    public String name;
    public int id;
    public String author;
    public String publisher;

    public MyType(String name, int id, String author, String publisher) {
        this.name = name;
        this.id = id;
        this.author = author;
        this.publisher = publisher;
    }

    @Override
    public String toString() {
        return "MyType{" +
                "name=" + name + '\'' +
                ", id=" + id +
                ", author='" + author + '\'' +
                ", publisher='" + publisher + '\'' +
                '}' + System.getProperty("line.separator");
    }
}

Output:

--- before
[MyType{name=John', id=2, author='author1', publisher='publisher1'}
, MyType{name=Marry', id=298, author='author2', publisher='publisher2'}
, MyType{name=David', id=3, author='author3', publisher='publisher3'}
]
--- after
[MyType{name=David', id=3, author='author3', publisher='publisher3'}
, MyType{name=John', id=2, author='author1', publisher='publisher1'}
, MyType{name=Marry', id=298, author='author2', publisher='publisher2'}
]

Using method references

Arrays.sort(myTypes, MyType::compareThem);

where compareThem has to be added in MyType.java:

public static int compareThem(MyType a, MyType b) {
    return a.name.compareTo(b.name);
}

Get array elements from index to end

The [:-1] removes the last element. Instead of

a[3:-1]

write

a[3:]

You can read up on Python slicing notation here: Explain Python's slice notation

NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.

What is "origin" in Git?

origin is the default alias to the URL of your remote repository.

How to create an alert message in jsp page after submit process is complete

in your servlet

 request.setAttribute("submitDone","done");
 return mapping.findForward("success");

In your jsp

<c:if test="${not empty submitDone}">
  <script>alert("Form submitted");
</script></c:if>

Howto: Clean a mysql InnoDB storage engine?

Here is a more complete answer with regard to InnoDB. It is a bit of a lengthy process, but can be worth the effort.

Keep in mind that /var/lib/mysql/ibdata1 is the busiest file in the InnoDB infrastructure. It normally houses six types of information:

InnoDB Architecture

InnoDB Architecture

Many people create multiple ibdata files hoping for better disk-space management and performance, however that belief is mistaken.

Can I run OPTIMIZE TABLE ?

Unfortunately, running OPTIMIZE TABLE against an InnoDB table stored in the shared table-space file ibdata1 does two things:

  • Makes the table’s data and indexes contiguous inside ibdata1
  • Makes ibdata1 grow because the contiguous data and index pages are appended to ibdata1

You can however, segregate Table Data and Table Indexes from ibdata1 and manage them independently.

Can I run OPTIMIZE TABLE with innodb_file_per_table ?

Suppose you were to add innodb_file_per_table to /etc/my.cnf (my.ini). Can you then just run OPTIMIZE TABLE on all the InnoDB Tables?

Good News : When you run OPTIMIZE TABLE with innodb_file_per_table enabled, this will produce a .ibd file for that table. For example, if you have table mydb.mytable witha datadir of /var/lib/mysql, it will produce the following:

  • /var/lib/mysql/mydb/mytable.frm
  • /var/lib/mysql/mydb/mytable.ibd

The .ibd will contain the Data Pages and Index Pages for that table. Great.

Bad News : All you have done is extract the Data Pages and Index Pages of mydb.mytable from living in ibdata. The data dictionary entry for every table, including mydb.mytable, still remains in the data dictionary (See the Pictorial Representation of ibdata1). YOU CANNOT JUST SIMPLY DELETE ibdata1 AT THIS POINT !!! Please note that ibdata1 has not shrunk at all.

InnoDB Infrastructure Cleanup

To shrink ibdata1 once and for all you must do the following:

  1. Dump (e.g., with mysqldump) all databases into a .sql text file (SQLData.sql is used below)

  2. Drop all databases (except for mysql and information_schema) CAVEAT : As a precaution, please run this script to make absolutely sure you have all user grants in place:

    mkdir /var/lib/mysql_grants
    cp /var/lib/mysql/mysql/* /var/lib/mysql_grants/.
    chown -R mysql:mysql /var/lib/mysql_grants
    
  3. Login to mysql and run SET GLOBAL innodb_fast_shutdown = 0; (This will completely flush all remaining transactional changes from ib_logfile0 and ib_logfile1)

  4. Shutdown MySQL

  5. Add the following lines to /etc/my.cnf (or my.ini on Windows)

    [mysqld]
    innodb_file_per_table
    innodb_flush_method=O_DIRECT
    innodb_log_file_size=1G
    innodb_buffer_pool_size=4G
    

    (Sidenote: Whatever your set for innodb_buffer_pool_size, make sure innodb_log_file_size is 25% of innodb_buffer_pool_size.

    Also: innodb_flush_method=O_DIRECT is not available on Windows)

  6. Delete ibdata* and ib_logfile*, Optionally, you can remove all folders in /var/lib/mysql, except /var/lib/mysql/mysql.

  7. Start MySQL (This will recreate ibdata1 [10MB by default] and ib_logfile0 and ib_logfile1 at 1G each).

  8. Import SQLData.sql

Now, ibdata1 will still grow but only contain table metadata because each InnoDB table will exist outside of ibdata1. ibdata1 will no longer contain InnoDB data and indexes for other tables.

For example, suppose you have an InnoDB table named mydb.mytable. If you look in /var/lib/mysql/mydb, you will see two files representing the table:

  • mytable.frm (Storage Engine Header)
  • mytable.ibd (Table Data and Indexes)

With the innodb_file_per_table option in /etc/my.cnf, you can run OPTIMIZE TABLE mydb.mytable and the file /var/lib/mysql/mydb/mytable.ibd will actually shrink.

I have done this many times in my career as a MySQL DBA. In fact, the first time I did this, I shrank a 50GB ibdata1 file down to only 500MB!

Give it a try. If you have further questions on this, just ask. Trust me; this will work in the short term as well as over the long haul.

CAVEAT

At Step 6, if mysql cannot restart because of the mysql schema begin dropped, look back at Step 2. You made the physical copy of the mysql schema. You can restore it as follows:

mkdir /var/lib/mysql/mysql
cp /var/lib/mysql_grants/* /var/lib/mysql/mysql
chown -R mysql:mysql /var/lib/mysql/mysql

Go back to Step 6 and continue

UPDATE 2013-06-04 11:13 EDT

With regard to setting innodb_log_file_size to 25% of innodb_buffer_pool_size in Step 5, that's blanket rule is rather old school.

Back on July 03, 2006, Percona had a nice article why to choose a proper innodb_log_file_size. Later, on Nov 21, 2008, Percona followed up with another article on how to calculate the proper size based on peak workload keeping one hour's worth of changes.

I have since written posts in the DBA StackExchange about calculating the log size and where I referenced those two Percona articles.

Personally, I would still go with the 25% rule for an initial setup. Then, as the workload can more accurate be determined over time in production, you could resize the logs during a maintenance cycle in just minutes.

Python list subtraction operation

The answer provided by @aaronasterling looks good, however, it is not compatible with the default interface of list: x = MyList(1, 2, 3, 4) vs x = MyList([1, 2, 3, 4]). Thus, the below code can be used as a more python-list friendly:

class MyList(list):
    def __init__(self, *args):
        super(MyList, self).__init__(*args)

    def __sub__(self, other):
        return self.__class__([item for item in self if item not in other])

Example:

x = MyList([1, 2, 3, 4])
y = MyList([2, 5, 2])
z = x - y

How to add a set path only for that batch file executing?

Just like any other environment variable, with SET:

SET PATH=%PATH%;c:\whatever\else

If you want to have a little safety check built in first, check to see if the new path exists first:

IF EXIST c:\whatever\else SET PATH=%PATH%;c:\whatever\else

If you want that to be local to that batch file, use setlocal:

setlocal
set PATH=...
set OTHERTHING=...

@REM Rest of your script

Read the docs carefully for setlocal/endlocal , and have a look at the other references on that site - Functions is pretty interesting too and the syntax is tricky.

The Syntax page should get you started with the basics.

Android: why is there no maxHeight for a View?

(I know this does not directly answer the question but might be helpful to others looking for maxHeight functionality)

ConstraintLayout offers maximum height for its children via

app:layout_constraintHeight_max="300dp"
app:layout_constrainedHeight="true" 

or

app:layout_constraintWidth_max="300dp"
app:layout_constrainedWidth="true" 

Sample usage here.

No 'Access-Control-Allow-Origin' header is present on the requested resource- AngularJS

In my case, I was trying to hit a WebAPI service on localhost from inside an MVC app that used a lot of Angular code. My WebAPI service worked fine with Fiddler via http://localhost/myservice. Once I took a moment to configure the MVC app to use IIS instead of IIS Express (a part of Visual Studio), it worked fine, without adding any CORS-related configuration to either area.

Read input numbers separated by spaces

I would recommend reading in the line into a string, then splitting it based on the spaces. For this, you can use the getline(...) function. The trick is having a dynamic sized data structure to hold the strings once it's split. Probably the easiest to use would be a vector.

#include <string>
#include <vector>
...
  string rawInput;
  vector<String> numbers;
  while( getline( cin, rawInput, ' ' ) )
  {
    numbers.push_back(rawInput);
  }

So say the input looks like this:

Enter a number, or numbers separated by a space, between 1 and 1000.
10 5 20 1 200 7

You will now have a vector, numbers, that contains the elements: {"10","5","20","1","200","7"}.

Note that these are still strings, so not useful in arithmetic. To convert them to integers, we use a combination of the STL function, atoi(...), and because atoi requires a c-string instead of a c++ style string, we use the string class' c_str() member function.

while(!numbers.empty())
{
  string temp = numbers.pop_back();//removes the last element from the string
  num = atoi( temp.c_str() ); //re-used your 'num' variable from your code

  ...//do stuff
}

Now there's some problems with this code. Yes, it runs, but it is kind of clunky, and it puts the numbers out in reverse order. Lets re-write it so that it is a little more compact:

#include <string>
...
string rawInput;
cout << "Enter a number, or numbers separated by a space, between 1 and 1000." << endl;
while( getline( cin, rawInput, ' ') )
{
  num = atoi( rawInput.c_str() );
  ...//do your stuff
}

There's still lots of room for improvement with error handling (right now if you enter a non-number the program will crash), and there's infinitely more ways to actually handle the input to get it in a usable number form (the joys of programming!), but that should give you a comprehensive start. :)

Note: I had the reference pages as links, but I cannot post more than two since I have less than 15 posts :/

Edit: I was a little bit wrong about the atoi behavior; I confused it with Java's string->Integer conversions which throw a Not-A-Number exception when given a string that isn't a number, and then crashes the program if the exception isn't handled. atoi(), on the other hand, returns 0, which is not as helpful because what if 0 is the number they entered? Let's make use of the isdigit(...) function. An important thing to note here is that c++ style strings can be accessed like an array, meaning rawInput[0] is the first character in the string all the way up to rawInput[length - 1].

#include <string>
#include <ctype.h>
...
string rawInput;
cout << "Enter a number, or numbers separated by a space, between 1 and 1000." << endl;
while( getline( cin, rawInput, ' ') )
{
  bool isNum = true;
  for(int i = 0; i < rawInput.length() && isNum; ++i)
  {
    isNum = isdigit( rawInput[i]);
  }

  if(isNum)
  {
    num = atoi( rawInput.c_str() );
    ...//do your stuff
  }
  else
    cout << rawInput << " is not a number!" << endl;
}

The boolean (true/false or 1/0 respectively) is used as a flag for the for-loop, which steps through each character in the string and checks to see if it is a 0-9 digit. If any character in the string is not a digit, the loop will break during it's next execution when it gets to the condition "&& isNum" (assuming you've covered loops already). Then after the loop, isNum is used to determine whether to do your stuff, or to print the error message.

Android check internet connection

I had issues with the IsInternetAvailable answer not testing for cellular networks, rather only if wifi was connected. This answer works for both wifi and mobile data:

How to check network connection enable or disable in WIFI and 3G(data plan) in mobile?

Python TypeError must be str not int

print("the furnace is now " + str(temperature) + "degrees!")

cast it to str

How to make a class JSON serializable

I see no mention here of serial versioning or backcompat, so I will post my solution which I've been using for a bit. I probably have a lot more to learn from, specifically Java and Javascript are probably more mature than me here but here goes

https://gist.github.com/andy-d/b7878d0044a4242c0498ed6d67fd50fe

Python constructors and __init__

There is no notion of method overloading in Python. But you can achieve a similar effect by specifying optional and keyword arguments

Automatic login script for a website on windows machine?

Well, its true that we can use Vb Script for what you intended to do. We can open an application through the code like Internet Explorer. We can navigate to site you intend for. Later we can check the element names of Text Boxes which require username and password; can set then and then Login. It works fine all of using code.

No manual interaction with the website. And eventually you will end up signing in by just double clicking the file.

To get you started :

Set objIE = CreateObject("InternetExplorer.Application")

Call objIE.Navigate("https://gmail.com")

This will open an instance of internet explore and navigate to gmail. Rest you can learn and apply.

Failed to find target with hash string 'android-25'

I got similar problem

1: I tried to resolve with the answer which is marked correct above But I was not able to get the system setting which was quit amazing (On MacBook).

Most of the time such errors & issues comes because of replacing your grade file with other grade file ,due which gradel does not sync properly and while building the project issue comes . The issue is bascially related to non syncing for platform tools

Solution a: Go to File and then to Your project strucutre -modules -app-Properties -build tool version -click on options which is required for your project (if required build tool version not there chose any other). This will sync the grade file and now you can go to gradel and change target version and build tool version as per your requirement .you will prompted to download the required platform tool to sync it , now click on install tool version and let project to build

Solution b: Try Anuja Ans if you can get option of system setting and install platform tool.

How to delete items from a dictionary while iterating over it?

Iterate over a copy instead, such as the one returned by items():

for k, v in list(mydict.items()):

How to make a movie out of images in python

I use the ffmpeg-python binding. You can find more information here.

import ffmpeg
(
    ffmpeg
    .input('/path/to/jpegs/*.jpg', pattern_type='glob', framerate=25)
    .output('movie.mp4')
    .run()
)

Detect Click into Iframe using JavaScript

This definitely works if the iframe is from the same domain as your parent site. I have not tested it for cross-domain sites.

$(window.frames['YouriFrameId']).click(function(event){  /* do something here  */ });
$(window.frames['YouriFrameId']).mousedown(function(event){ /* do something here */ });
$(window.frames['YouriFrameId']).mouseup(function(event){ /* do something here */ });

Without jQuery you could try something like this, but again I have not tried this.

window.frames['YouriFrameId'].onmousedown = function() { do something here }

You can even filter your results:

$(window.frames['YouriFrameId']).mousedown(function(event){   
  var eventId = $(event.target).attr('id');      
  if (eventId == 'the-id-you-want') {
   //  do something
  }
});

How to send a “multipart/form-data” POST in Android with Volley

Here is Simple Solution And Complete Example for Uploading File Using Volley Android

1) Gradle Import

compile 'dev.dworks.libs:volleyplus:+'

2)Now Create a Class RequestManager

public class RequestManager {
    private static RequestManager mRequestManager;
    /**
     * Queue which Manages the Network Requests :-)
     */
    private static RequestQueue mRequestQueue;
    // ImageLoader Instance

    private RequestManager() {

    }

    public static RequestManager get(Context context) {

        if (mRequestManager == null)
            mRequestManager = new RequestManager();

        return mRequestManager;
    }

    /**
     * @param context application context
     */
    public static RequestQueue getnstance(Context context) {

        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(context);
        }

        return mRequestQueue;

    }


}

3)Now Create a Class to handle Request for uploading File WebService

public class WebService {
    private RequestQueue mRequestQueue;
    private static WebService apiRequests = null;

    public static WebService getInstance() {
        if (apiRequests == null) {
            apiRequests = new WebService();
            return apiRequests;
        }
        return apiRequests;
    }
    public void updateProfile(Context context, String doc_name, String doc_type, String appliance_id, File file, Response.Listener<String> listener, Response.ErrorListener errorListener) {
        SimpleMultiPartRequest request = new SimpleMultiPartRequest(Request.Method.POST, "YOUR URL HERE", listener, errorListener);
//        request.setParams(data);
        mRequestQueue = RequestManager.getnstance(context);
        request.addMultipartParam("token", "text", "tdfysghfhsdfh");
        request.addMultipartParam("parameter_1", "text", doc_name);
        request.addMultipartParam("dparameter_2", "text", doc_type);
        request.addMultipartParam("parameter_3", "text", appliance_id);
            request.addFile("document_file", file.getPath());

        request.setFixedStreamingMode(true);
        mRequestQueue.add(request);
    }
}

4) And Now Call The method Like This to Hit the service

public class Main2Activity extends AppCompatActivity implements Response.ErrorListener, Response.Listener<String>{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Button button=(Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadData();
            }
        });
    }

    private void uploadData() {
        WebService.getInstance().updateProfile(getActivity(), "appl_doc", "appliance", "1", mChoosenFile, this, this);
    }

    @Override
    public void onErrorResponse(VolleyError error) {

    }

    @Override
    public void onResponse(String response) {
     //Your response here 
    }
}

A TypeScript GUID class?

I found this https://typescriptbcl.codeplex.com/SourceControl/latest

here is the Guid version they have in case the link does not work later.

module System {
    export class Guid {
        constructor (public guid: string) {
            this._guid = guid;
        }

        private _guid: string;

        public ToString(): string {
            return this.guid;
        }

        // Static member
        static MakeNew(): Guid {
            var result: string;
            var i: string;
            var j: number;

            result = "";
            for (j = 0; j < 32; j++) {
                if (j == 8 || j == 12 || j == 16 || j == 20)
                    result = result + '-';
                i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
                result = result + i;
            }
            return new Guid(result);
        }
    }
}

Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax

I have adapted the solution of Biju:

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;


public class JsonPathArgumentResolver implements HandlerMethodArgumentResolver{

    private static final String JSONBODYATTRIBUTE = "JSON_REQUEST_BODY";

    private ObjectMapper om = new ObjectMapper();

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(JsonArg.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String jsonBody = getRequestBody(webRequest);

        JsonNode rootNode = om.readTree(jsonBody);
        JsonNode node = rootNode.path(parameter.getParameterName());    

        return om.readValue(node.toString(), parameter.getParameterType());
    }


    private String getRequestBody(NativeWebRequest webRequest){
        HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);

        String jsonBody = (String) webRequest.getAttribute(JSONBODYATTRIBUTE, NativeWebRequest.SCOPE_REQUEST);
        if (jsonBody==null){
            try {
                jsonBody = IOUtils.toString(servletRequest.getInputStream());
                webRequest.setAttribute(JSONBODYATTRIBUTE, jsonBody, NativeWebRequest.SCOPE_REQUEST);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return jsonBody;

    }

}

What's the different:

  • I'm using Jackson to convert json
  • I don't need a value in the annotation, you can read the name of the parameter out of the MethodParameter
  • I also read the type of the parameter out of the Methodparameter => so the solution should be generic (i tested it with string and DTOs)

BR

How do I use the new computeIfAbsent function?

multi-map

This is really helpful if you want to create a multimap without resorting to the Google Guava library for its implementation of MultiMap.

For example, suppose you want to store a list of students who enrolled for a particular subject.

The normal solution for this using JDK library is:

Map<String,List<String>> studentListSubjectWise = new TreeMap<>();
List<String>lis = studentListSubjectWise.get("a");
if(lis == null) {
    lis = new ArrayList<>();
}
lis.add("John");

//continue....

Since it have some boilerplate code, people tend to use Guava Mutltimap.

Using Map.computeIfAbsent, we can write in a single line without guava Multimap as follows.

studentListSubjectWise.computeIfAbsent("a", (x -> new ArrayList<>())).add("John");

Stuart Marks & Brian Goetz did a good talk about this https://www.youtube.com/watch?v=9uTVXxJjuco

Most simple code to populate JTable from ResultSet

Well I'm sure that this is the simplest way to populate JTable from ResultSet, without any external library. I have included comments in this method.

public void resultSetToTableModel(ResultSet rs, JTable table) throws SQLException{
        //Create new table model
        DefaultTableModel tableModel = new DefaultTableModel();

        //Retrieve meta data from ResultSet
        ResultSetMetaData metaData = rs.getMetaData();

        //Get number of columns from meta data
        int columnCount = metaData.getColumnCount();

        //Get all column names from meta data and add columns to table model
        for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++){
            tableModel.addColumn(metaData.getColumnLabel(columnIndex));
        }

        //Create array of Objects with size of column count from meta data
        Object[] row = new Object[columnCount];

        //Scroll through result set
        while (rs.next()){
            //Get object from column with specific index of result set to array of objects
            for (int i = 0; i < columnCount; i++){
                row[i] = rs.getObject(i+1);
            }
            //Now add row to table model with that array of objects as an argument
            tableModel.addRow(row);
        }

        //Now add that table model to your table and you are done :D
        table.setModel(tableModel);
    }

Generate a unique id

We can do something like this

string TransactionID = "BTRF"+DateTime.Now.Ticks.ToString().Substring(0, 10);

Declare global variables in Visual Studio 2010 and VB.NET

Pretty much the same way that you always have, with "Modules" instead of classes and just use "Public" instead of the old "Global" keyword:

Public Module Module1
    Public Foo As Integer
End Module

Twitter - How to embed native video from someone else's tweet into a New Tweet or a DM

I found a faster way of embedding:

  • Just copy the link.
  • Paste the link and remove the "?s=19" part and add "/video/1"
  • That's it.

Swift 3: Display Image from URL

Use this extension and download image faster.

extension UIImageView {
    public func imageFromURL(urlString: String) {

        let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        activityIndicator.frame = CGRect.init(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
        activityIndicator.startAnimating()
        if self.image == nil{
            self.addSubview(activityIndicator)
        }

        URLSession.shared.dataTask(with: NSURL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in

            if error != nil {
                print(error ?? "No Error")
                return
            }
            DispatchQueue.main.async(execute: { () -> Void in
                let image = UIImage(data: data!)
                activityIndicator.removeFromSuperview()
                self.image = image
            })

        }).resume()
    }
}

AngularJS : Factory and Service?

  • If you use a service you will get the instance of a function ("this" keyword).
  • If you use a factory you will get the value that is returned by invoking the function reference (the return statement in factory)

Factory and Service are the most commonly used recipes. The only difference between them is that Service recipe works better for objects of custom type, while Factory can produce JavaScript primitives and functions.

Reference

Change the Blank Cells to "NA"

I recently ran into similar issues, and this is what worked for me.

If the variable is numeric, then a simple df$Var[df$Var == ""] <- NA should suffice. But if the variable is a factor, then you need to convert it to the character first, then replace "" cells with the value you want, and convert it back to factor. So case in point, your Sex variable, I assume it would be a factor and if you want to replace the empty cell, I would do the following:

df$Var <- as.character(df$Var)
df$Var[df$Var==""] <- NA
df$Var <- as.factor(df$Var)

Functions that return a function

Returning b is returning a function object. In Javascript, functions are just objects, like any other object. If you find that not helpful, just replace the word "object" with "thing". You can return any object from a function. You can return a true/false value. An integer (1,2,3,4...). You can return a string. You can return a complex object with multiple properties. And you can return a function. a function is just a thing.

In your case, returning b returns the thing, the thing is a callable function. Returning b() returns the value returned by the callable function.

Consider this code:

function b() {
   return 42;
}

Using the above definition, return b(); returns the value 42. On the other hand return b; returns a function, that itself returns the value of 42. They are two different things.

Selecting multiple items in ListView

and to get it :

public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

                Log.d(getLocalClassName(), "onItemClick(" + view + ","
                        + position + "," + id + ")");
        }
    });

How to solve munmap_chunk(): invalid pointer error in C++

The hint is, the output file is created even if you get this error. The automatic deconstruction of vector starts after your code executed. Elements in the vector are deconstructed as well. This is most probably where the error occurs. The way you access the vector is through vector::operator[] with an index read from stream. Try vector::at() instead of vector::operator[]. This won't solve your problem, but will show which assignment to the vector causes error.

How do I put my website's logo to be the icon image in browser tabs?

  1. ADD THIS
**<HEAD>**

  < link rel="icon" href="directory/image.png">

Then run and enjoy it

C# Convert List<string> to Dictionary<string, string>

EDIT

another way to deal with duplicate is you can do like this

var dic = slist.Select((element, index)=> new{element,index} )
            .ToDictionary(ele=>ele.index.ToString(), ele=>ele.element);

or


easy way to do is

var res = list.ToDictionary(str => str, str=> str); 

but make sure that there is no string is repeating...again otherewise above code will not work for you

if there is string is repeating than its better to do like this

Dictionary<string,string> dic= new Dictionary<string,string> ();

    foreach(string s in Stringlist)
    {
       if(!dic.ContainsKey(s))
       {
        //  dic.Add( value to dictionary
      }
    }

How to pass optional parameters while omitting some other optional parameters?

you can use optional variable by ? or if you have multiple optional variable by ..., example:

function details(name: string, country="CA", address?: string, ...hobbies: string) {
    // ...
}

In the above:

  • name is required
  • country is required and has a default value
  • address is optional
  • hobbies is an array of optional params

Can I perform a DNS lookup (hostname to IP address) using client-side Javascript?

There is a javascript library DNS-JS.com that does just this.

DNS.Query("dns-js.com",
    DNS.QueryType.A,
    function(data) {
        console.log(data);
});

How can I escape square brackets in a LIKE clause?

The ESCAPE keyword is used if you need to search for special characters like % and _, which are normally wild cards. If you specify ESCAPE, SQL will search literally for the characters % and _.

Here's a good article with some more examples

SELECT columns FROM table WHERE 
    column LIKE '%[[]SQL Server Driver]%' 

-- or 

SELECT columns FROM table WHERE 
    column LIKE '%\[SQL Server Driver]%' ESCAPE '\'

Countdown timer in React

You have to setState every second with the seconds remaining (every time the interval is called). Here's an example:

_x000D_
_x000D_
class Example extends React.Component {_x000D_
  constructor() {_x000D_
    super();_x000D_
    this.state = { time: {}, seconds: 5 };_x000D_
    this.timer = 0;_x000D_
    this.startTimer = this.startTimer.bind(this);_x000D_
    this.countDown = this.countDown.bind(this);_x000D_
  }_x000D_
_x000D_
  secondsToTime(secs){_x000D_
    let hours = Math.floor(secs / (60 * 60));_x000D_
_x000D_
    let divisor_for_minutes = secs % (60 * 60);_x000D_
    let minutes = Math.floor(divisor_for_minutes / 60);_x000D_
_x000D_
    let divisor_for_seconds = divisor_for_minutes % 60;_x000D_
    let seconds = Math.ceil(divisor_for_seconds);_x000D_
_x000D_
    let obj = {_x000D_
      "h": hours,_x000D_
      "m": minutes,_x000D_
      "s": seconds_x000D_
    };_x000D_
    return obj;_x000D_
  }_x000D_
_x000D_
  componentDidMount() {_x000D_
    let timeLeftVar = this.secondsToTime(this.state.seconds);_x000D_
    this.setState({ time: timeLeftVar });_x000D_
  }_x000D_
_x000D_
  startTimer() {_x000D_
    if (this.timer == 0 && this.state.seconds > 0) {_x000D_
      this.timer = setInterval(this.countDown, 1000);_x000D_
    }_x000D_
  }_x000D_
_x000D_
  countDown() {_x000D_
    // Remove one second, set state so a re-render happens._x000D_
    let seconds = this.state.seconds - 1;_x000D_
    this.setState({_x000D_
      time: this.secondsToTime(seconds),_x000D_
      seconds: seconds,_x000D_
    });_x000D_
    _x000D_
    // Check if we're at zero._x000D_
    if (seconds == 0) { _x000D_
      clearInterval(this.timer);_x000D_
    }_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return(_x000D_
      <div>_x000D_
        <button onClick={this.startTimer}>Start</button>_x000D_
        m: {this.state.time.m} s: {this.state.time.s}_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Example/>, document.getElementById('View'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="View"></div>
_x000D_
_x000D_
_x000D_

How to prevent rm from reporting that a file was not found?

I had same issue for cshell. The only solution I had was to create a dummy file that matched pattern before "rm" in my script.

Ruby String to Date Conversion

Date.strptime(updated,"%a, %d %m %Y %H:%M:%S %Z")

Should be:

Date.strptime(updated, '%a, %d %b %Y %H:%M:%S %Z')

Create a nonclustered non-unique index within the CREATE TABLE statement with SQL Server

As of SQL 2014, this can be accomplished via inline index creation:

CREATE TABLE MyTable(
    a int NOT NULL
    ,b smallint NOT NULL
    ,c smallint NOT NULL
    ,d smallint NOT NULL
    ,e smallint NOT NULL

    -- This creates a primary key
    ,CONSTRAINT PK_MyTable PRIMARY KEY CLUSTERED (a)

    -- This creates a unique nonclustered index on columns b and c
    ,CONSTRAINT IX_MyTable1 UNIQUE (b, c)

    -- This creates a standard non-clustered index on (d, e)
    ,INDEX IX_MyTable4 NONCLUSTERED (d, e)
);
GO

Prior to SQL 2014, CREATE/ALTER TABLE only accepted CONSTRAINTs to be added, not indexes. The fact that primary key and unique constraints are implemented in terms of an index is a side effect.

How can I stop python.exe from closing immediately after I get an output?

It looks like you are running something in Windows by double clicking on it. This will execute the program in a new window and close the window when it terminates. No wonder you cannot read the output.

A better way to do this would be to switch to the command prompt. Navigate (cd) to the directory where the program is located and then call it using python. Something like this:

C:\> cd C:\my_programs\
C:\my_programs\> python area.py

Replace my_programs with the actual location of your program and area.py with the name of your python file.

What's the environment variable for the path to the desktop?

EDIT: Use the accepted answer, this will not work if the default location isn't being used, for example: The user moved the desktop to another drive like D:\Desktop


At least on Windows XP, Vista and 7 you can use the "%UserProfile%\Desktop" safely.

Windows XP en-US it will expand to "C:\Documents and Settings\YourName\Desktop"
Windows XP pt-BR it will expand to "C:\Documents and Settings\YourName\Desktop"
Windows 7 en-US it will expand to "C:\Users\YourName\Desktop"
Windows 7 pt-BR it will expand to "C:\Usuarios\YourName\Desktop"

On XP you can't use this to others folders exept for Desktop My documents turning to Meus Documentos and Local Settings to Configuracoes locais Personaly I thinks this is a bad thing when projecting a OS.

Using GroupBy, Count and Sum in LINQ Lambda Expressions

        var q = from b in listOfBoxes
                group b by b.Owner into g
                select new
                           {
                               Owner = g.Key,
                               Boxes = g.Count(),
                               TotalWeight = g.Sum(item => item.Weight),
                               TotalVolume = g.Sum(item => item.Volume)
                           };

how to display variable value in alert box?

spans not have the value in html

one is the id for span tag

in javascript use

document.getElementById('one').innerText;

in jQuery use

$('#one').text()

function check() {
    var content = document.getElementById("one").innerText;
    alert(content);
}

or

function check() {
        var content = $('#one').text();
        alert(content);
    }

Fill formula down till last row in column

It's a one liner actually. No need to use .Autofill

Range("M3:M" & LastRow).Formula = "=G3&"",""&L3"

When is a C++ destructor called?

  1. Pointers -- Regular pointers don't support RAII. Without an explicit delete, there will be garbage. Fortunately C++ has auto pointers that handle this for you!

  2. Scope -- Think of when a variable becomes invisible to your program. Usually this is at the end of {block}, as you point out.

  3. Manual destruction -- Never attempt this. Just let scope and RAII do the magic for you.

auto run a bat script in windows 7 at login

To run the batch file when the VM user logs in:

Drag the shortcut--the one that's currently on your desktop--(or the batch file itself) to Start - All Programs - Startup. Now when you login as that user, it will launch the batch file.

Another way to do the same thing is to save the shortcut or the batch file in %AppData%\Microsoft\Windows\Start Menu\Programs\Startup\.

As far as getting it to run full screen, it depends a bit what you mean. You can have it launch maximized by editing your batch file like this:

start "" /max "C:\Program Files\Oracle\VirtualBox\VirtualBox.exe" --comment "VM" --startvm "12dada4d-9cfd-4aa7-8353-20b4e455b3fa"

But if VirtualBox has a truly full-screen mode (where it hides even the taskbar), you'll have to look for a command-line parameter on VirtualBox.exe. I'm not familiar with that product.

Unknown URL content://downloads/my_downloads

The exception is caused by disabled Download Manager. And there is no way to activate/deactivate Download Manager directly, since it's system application and we don't have access to it.

Only alternative way is redirect user to settings of Download Manager Application.

try {
     //Open the specific App Info page:
     Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
     intent.setData(Uri.parse("package:" + "com.android.providers.downloads"));
     startActivity(intent);

} catch ( ActivityNotFoundException e ) {
     e.printStackTrace();

     //Open the generic Apps page:
     Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
     startActivity(intent);
}

How to add text at the end of each line in Vim?

ex mode is easiest:

:%s/$/,

: - enter command mode
% - for every line
s/ - substitute
$ - the end of the line
/ - and change it to
, - a comma

How to get the next auto-increment id in mysql

Improvement of @ravi404, in case your autoincrement offset IS NOT 1 :

SELECT (`auto_increment`-1) + IFNULL(@@auto_increment_offset,1) 
FROM INFORMATION_SCHEMA.TABLES
WHERE table_name = your_table_name
AND table_schema = DATABASE( );

(auto_increment-1) : db engine seems to alwaus consider an offset of 1. So you need to ditch this assumption, then add the optional value of @@auto_increment_offset, or default to 1 : IFNULL(@@auto_increment_offset,1)

What is the Windows version of cron?

The At command is now deprecated

you can use the SCHTASKS

Configure hibernate (using JPA) to store Y/N for type Boolean instead of 0/1

To do it in a generic JPA way using getter annotations, the example below works for me with Hibernate 3.5.4 and Oracle 11g. Note that the mapped getter and setter (getOpenedYnString and setOpenedYnString) are private methods. Those methods provide the mapping but all programmatic access to the class is using the getOpenedYn and setOpenedYn methods.

private String openedYn;

@Transient
public Boolean getOpenedYn() {
  return toBoolean(openedYn);
}

public void setOpenedYn(Boolean openedYn) {
  setOpenedYnString(toYesNo(openedYn));
}

@Column(name = "OPENED_YN", length = 1)
private String getOpenedYnString() {
  return openedYn;
}

private void setOpenedYnString(String openedYn) {
  this.openedYn = openedYn;
}

Here's the util class with static methods toYesNo and toBoolean:

public class JpaUtil {

    private static final String NO = "N";
    private static final String YES = "Y";

    public static String toYesNo(Boolean value) {
        if (value == null)
            return null;
        else if (value)
            return YES;
        else
            return NO;
    }

    public static Boolean toBoolean(String yesNo) {
        if (yesNo == null)
            return null;
        else if (YES.equals(yesNo))
            return true;
        else if (NO.equals(yesNo))
            return false;
        else
            throw new RuntimeException("unexpected yes/no value:" + yesNo);
    }
}

Scheduling recurring task in Android

Quoting the Scheduling Repeating Alarms - Understand the Trade-offs docs:

A common scenario for triggering an operation outside the lifetime of your app is syncing data with a server. This is a case where you might be tempted to use a repeating alarm. But if you own the server that is hosting your app's data, using Google Cloud Messaging (GCM) in conjunction with sync adapter is a better solution than AlarmManager. A sync adapter gives you all the same scheduling options as AlarmManager, but it offers you significantly more flexibility.

So, based on this, the best way to schedule a server call is using Google Cloud Messaging (GCM) in conjunction with sync adapter.

Guid.NewGuid() vs. new Guid()

Guid.NewGuid(), as it creates GUIDs as intended.

Guid.NewGuid() creates an empty Guid object, initializes it by calling CoCreateGuid and returns the object.

new Guid() merely creates an empty GUID (all zeros, I think).

I guess they had to make the constructor public as Guid is a struct.

Using R to download zipped data file, extract, and import data

I used CRAN package "downloader" found at http://cran.r-project.org/web/packages/downloader/index.html . Much easier.

download(url, dest="dataset.zip", mode="wb") 
unzip ("dataset.zip", exdir = "./")

Access VBA | How to replace parts of a string with another string

Use Access's VBA function Replace(text, find, replacement):

Dim result As String

result = Replace("Some sentence containing Avenue in it.", "Avenue", "Ave")

How to get user's high resolution profile picture on Twitter?

use this URL : "https://twitter.com/(userName)/profile_image?size=original"

If you are using TWitter SDK you can get the user name when logged in, with TWTRAPIClient, using TWTRAuthSession.

This is the code snipe for iOS:

if let twitterId = session.userID{
   let twitterClient = TWTRAPIClient(userID: twitterId)
   twitterClient.loadUser(withID: twitterId) {(user, error) in
       if let userName = user?.screenName{
          let url = "https://twitter.com/\(userName)/profile_image?size=original")
       }
   }
}

Setting public class variables

Inside class Testclass:

public function __construct($new_value)
{
    $this->testvar = $new_value;
}

self referential struct definition?

I know this post is old, however, to get the effect you are looking for, you may want to try the following:

#define TAKE_ADVANTAGE

/* Forward declaration of "struct Cell" as type Cell. */
typedef struct Cell Cell;

#ifdef TAKE_ADVANTAGE
/*
   Define Cell structure taking advantage of forward declaration.
*/
struct Cell
{
   int isParent;
   Cell *child;
};

#else

/*
   Or...you could define it as other posters have mentioned without taking
   advantage of the forward declaration.
*/
struct Cell
{
   int isParent;
   struct Cell *child;
};

#endif

/*
    Some code here...
*/

/* Use the Cell type. */
Cell newCell;

In either of the two cases mentioned in the code fragment above, you MUST declare your child Cell structure as a pointer. If you do not, then you will get the "field 'child' has incomplete type" error. The reason is that "struct Cell" must be defined in order for the compiler to know how much space to allocate when it is used.

If you attempt to use "struct Cell" inside the definition of "struct Cell", then the compiler cannot yet know how much space "struct Cell" is supposed to take. However, the compiler already knows how much space a pointer takes, and (with the forward declaration) it knows that "Cell" is a type of "struct Cell" (although it doesn't yet know how big a "struct Cell" is). So, the compiler can define a "Cell *" within the struct that is being defined.

Writing string to a file on a new line every time

Ok, here is a safe way of doing it.

with open('example.txt', 'w') as f:
 for i in range(10):
  f.write(str(i+1))
  f.write('\n')


This writes 1 to 10 each number on a new line.

Formatting code snippets for blogging on Blogger

To post your html, javascript,c# and java you should convert special characters to HTML code. as '<' as &lt; and '>' to &gt; and e.t.c..

Add this link Code Converter to iGoogle. This will help you to convert the special characters.

Then add SyntaxHighlighter 3.0.83 new version to customize your code in blogger. But you should know How to configure the syntaxHighlighter in your blogger template.

How can I return the difference between two lists?

List<String> l1 = new ArrayList<String>();
l1.add("apple");
l1.add("orange");
l1.add("banana");
l1.add("strawberry");

List<String> l2 = new ArrayList<String>();
l2.add("apple");
l2.add("orange");

System.out.println(l1);
System.out.println(l2);

for (String A: l2) {
  if (l1.contains(A))
    l1.remove(A);
}

System.out.println("output");
System.out.println(l1);

Output:

[apple, orange, banana, strawberry]
[apple, orange]
output
[banana, strawberry]

How to unpackage and repackage a WAR file

Adapting from the above answers, this works for Tomcat, but can be adapted for JBoss as well or any container:

sudo -u tomcat /opt/tomcat/bin/shutdown.sh
cd /opt/tomcat/webapps
sudo mkdir tmp; cd tmp
sudo jar -xvf ../myapp.war
#make edits...
sudo vi WEB-INF/classes/templates/fragments/header.html
sudo vi WEB-INF/classes/application.properties
#end of making edits
sudo jar -cvf myapp0.0.1.war *
sudo cp myapp0.0.1.war ..
cd ..
sudo chown tomcat:tomcat myapp0.0.1.war
sudo rm -rf tmp
sudo -u tomcat /opt/tomcat/bin/startup.sh

Anaconda version with Python 3.5

According to the official docu it's recommended to downgrade the whole Python environment:

conda install python=3.5

ProcessStartInfo hanging on "WaitForExit"? Why?

I solved it this way:

            Process proc = new Process();
            proc.StartInfo.FileName = batchFile;
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.RedirectStandardError = true;
            proc.StartInfo.RedirectStandardInput = true;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;      
            proc.Start();
            StreamWriter streamWriter = proc.StandardInput;
            StreamReader outputReader = proc.StandardOutput;
            StreamReader errorReader = proc.StandardError;
            while (!outputReader.EndOfStream)
            {
                string text = outputReader.ReadLine();                    
                streamWriter.WriteLine(text);
            }

            while (!errorReader.EndOfStream)
            {                   
                string text = errorReader.ReadLine();
                streamWriter.WriteLine(text);
            }

            streamWriter.Close();
            proc.WaitForExit();

I redirected both input, output and error and handled reading from output and error streams. This solution works for SDK 7- 8.1, both for Windows 7 and Windows 8

Generate random integers between 0 and 9

from random import randint

x = [randint(0, 9) for p in range(0, 10)]

This generates 10 pseudorandom integers in range 0 to 9 inclusive.

Using ORDER BY and GROUP BY together

Here is the simplest solution

select m_id,v_id,max(timestamp) from table group by m_id;

Group by m_id but get max of timestamp for each m_id.

How to save local data in a Swift app?

Okey so thanks to @bploat and the link to http://www.codingexplorer.com/nsuserdefaults-a-swift-introduction/

I've found that the answer is quite simple for some basic string storage.

let defaults = NSUserDefaults.standardUserDefaults()

// Store
defaults.setObject("theGreatestName", forKey: "username")

// Receive
if let name = defaults.stringForKey("username")
{
    print(name)
    // Will output "theGreatestName"
}

I've summarized it here http://ridewing.se/blog/save-local-data-in-swift/

How do I install a module globally using npm?

In Ubuntu, set path of node_modules in .bashrc file

export PATH="/home/username/node_modules/.bin:$PATH"

Find the nth occurrence of substring in a string

Def:

def get_first_N_words(mytext, mylen = 3):
    mylist = list(mytext.split())
    if len(mylist)>=mylen: return ' '.join(mylist[:mylen])

To use:

get_first_N_words('  One Two Three Four ' , 3)

Output:

'One Two Three'

How to pad a string with leading zeros in Python 3

There are many ways to achieve this but the easiest way in Python 3.6+, in my opinion, is this:

print(f"{1:03}")

"application blocked by security settings" prevent applets running using oracle SE 7 update 51 on firefox on Linux mint

I had this issue. The security settings in the ControlPanel seem to be user specific. Try running it as the user you are actually running your browser as (you are not browsing as root!??) and setting the security level to Medium there. - For me, that did it.

In Python, how to display current time in readable format

All you need is in the documentation.

import time
time.strftime('%X %x %Z')
'16:08:12 05/08/03 AEST'

How to Kill A Session or Session ID (ASP.NET/C#)

From what I tested:

Session.Abandon(); // Does nothing
Session.Clear();   // Removes the data contained in the session

Example:
001: Session["test"] = "test";
002: Session.Abandon();
003: Print(Session["test"]); // Outputs: "test"

Session.Abandon does only set a boolean flag in the session-object to true. The calling web-server may react to that or not, but there is NO immediate action caused by ASP. (I checked that myself with the .net-Reflector)

In fact, you can continue working with the old session, by hitting the browser's back button once, and continue browsing across the website normally.

So, to conclude this: Use Session.Clear() and save frustration.

Remark: I've tested this behaviour on the ASP.net development server. The actual IIS may behave differently.

Add "Appendix" before "A" in thesis TOC

You can easily achieve what you want using the appendix package. Here's a sample file that shows you how. The key is the titletoc option when calling the package. It takes whatever value you've defined in \appendixname and the default value is Appendix.

\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents

\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
  \chapter{Consectetur adipiscing elit}
  \chapter{Mauris euismod}
\end{appendices}
\end{document}

The output looks like

enter image description here

Argparse optional positional arguments?

Use nargs='?' (or nargs='*' if you need more than one dir)

parser.add_argument('dir', nargs='?', default=os.getcwd())

extended example:

>>> import os, argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-v', action='store_true')
_StoreTrueAction(option_strings=['-v'], dest='v', nargs=0, const=True, default=False, type=None, choices=None, help=None, metavar=None)
>>> parser.add_argument('dir', nargs='?', default=os.getcwd())
_StoreAction(option_strings=[], dest='dir', nargs='?', const=None, default='/home/vinay', type=None, choices=None, help=None, metavar=None)
>>> parser.parse_args('somedir -v'.split())
Namespace(dir='somedir', v=True)
>>> parser.parse_args('-v'.split())
Namespace(dir='/home/vinay', v=True)
>>> parser.parse_args(''.split())
Namespace(dir='/home/vinay', v=False)
>>> parser.parse_args(['somedir'])
Namespace(dir='somedir', v=False)
>>> parser.parse_args('somedir -h -v'.split())
usage: [-h] [-v] [dir]

positional arguments:
  dir

optional arguments:
  -h, --help  show this help message and exit
  -v

How to enumerate an enum

I know it is a bit messy, but if you are fan of one-liners, here is one:

((Suit[])Enum.GetValues(typeof(Suit))).ToList().ForEach(i => DoSomething(i));

How can I use NSError in my iPhone App?

Well, what I usually do is have my methods that could error-out at runtime take a reference to a NSError pointer. If something does indeed go wrong in that method, I can populate the NSError reference with error data and return nil from the method.

Example:

- (id) endWorldHunger:(id)largeAmountsOfMonies error:(NSError**)error {
    // begin feeding the world's children...
    // it's all going well until....
    if (ohNoImOutOfMonies) {
        // sad, we can't solve world hunger, but we can let people know what went wrong!
        // init dictionary to be used to populate error object
        NSMutableDictionary* details = [NSMutableDictionary dictionary];
        [details setValue:@"ran out of money" forKey:NSLocalizedDescriptionKey];
        // populate the error object with the details
        *error = [NSError errorWithDomain:@"world" code:200 userInfo:details];
        // we couldn't feed the world's children...return nil..sniffle...sniffle
        return nil;
    }
    // wohoo! We fed the world's children. The world is now in lots of debt. But who cares? 
    return YES;
}

We can then use the method like this. Don't even bother to inspect the error object unless the method returns nil:

// initialize NSError object
NSError* error = nil;
// try to feed the world
id yayOrNay = [self endWorldHunger:smallAmountsOfMonies error:&error];
if (!yayOrNay) {
   // inspect error
   NSLog(@"%@", [error localizedDescription]);
}
// otherwise the world has been fed. Wow, your code must rock.

We were able to access the error's localizedDescription because we set a value for NSLocalizedDescriptionKey.

The best place for more information is Apple's documentation. It really is good.

There is also a nice, simple tutorial on Cocoa Is My Girlfriend.

How to make a .NET Windows Service start right after the installation?

Use the .NET ServiceController class to start it, or issue the commandline command to start it --- "net start servicename". Either way works.

How do I activate a Spring Boot profile when running from IntelliJ?

So for resuming...

If you have the IntelliJ Ultimate the correct answer is the one provided by Daniel Bubenheim

But if you don't, create in Run->Edit Configurations and in Configuration tab add the next Environment variable:

SPRING_PROFILES_ACTIVE=profilename

And to execute the jar do:

java -jar -Dspring.profiles.active=profilename XXX.jar

momentJS date string add 5 days

You can reduce what they said in a few lines of code:

var nowPlusOneDay = moment().add('days', 1);
var nowPlusOneDayStr = nowPlusOneDay.format('YYYY-MM-DD');

alert('nowPlusOneDay Without Format(Unix Date):'+nowPlusOneDay);
alert('nowPlusOneDay Formatted(String):'+nowPlusOneDayStr);

ReadFile in Base64 Nodejs

var fs = require('fs');

function base64Encode(file) {
    var body = fs.readFileSync(file);
    return body.toString('base64');
}


var base64String = base64Encode('test.jpg');
console.log(base64String);

Determine which MySQL configuration file is being used

Taken from the fantastic "High Performance MySQL" O'Reilly book:

$ which mysqld
/usr/sbin/mysqld

$ /usr/sbin/mysqld --verbose --help | grep -A 1 "Default options"
Default options are read from the following files in the given order:
/etc/mysql/my.cnf ~/.my.cnf /usr/etc/my.cnf

How to embed a video into GitHub README.md?

I combine Alexandre Jasmin and Gab Le Roux answers like this:

[![Demo CountPages alpha](https://share.gifyoutube.com/KzB6Gb.gif)](https://www.youtube.com/watch?v=ek1j272iAmc)

Demo:

Demo CountPages alpha

You can see this demo on github.

I used gifyoutube here, but I recommend using a local gif converter (like ffmpeg, see how) instead of an online one.

To record your screen to gif directly, you may want to check ScreenToGif.

What is a file with extension .a?

.a files are static libraries typically generated by the archive tool. You usually include the header files associated with that static library and then link to the library when you are compiling.

How do I solve this "Cannot read property 'appendChild' of null" error?

Your condition id !== 0 will always be different that zero because you are assigning a string value. On pages where the element with id views_slideshow_controls_text_next_slideshow-block is not found, you will still try to append the img element, which causes the Cannot read property 'appendChild' of null error.

Instead of assigning a string value, you can assign the DOM element and verify if it exists within the page.

window.onload = function loadContIcons() {
    var elem = document.createElement("img");
    elem.src = "http://arno.agnian.com/sites/all/themes/agnian/images/up.png";
    elem.setAttribute("class", "up_icon");

    var container = document.getElementById("views_slideshow_controls_text_next_slideshow-block");
    if (container !== null) {
        container.appendChild(elem);
    } else console.log("aaaaa");

    var elem1 = document.createElement("img");
    elem1.src = "http://arno.agnian.com/sites/all/themes/agnian/images/down.png";
    elem1.setAttribute("class", "down_icon");

    container = document.getElementById("views_slideshow_controls_text_previous_slideshow-block");
    if (container !== null) {
        container.appendChild(elem1);
    } else console.log("aaaaa");
}

TypeScript - Append HTML to container element in Angular 2

When working with Angular the recent update to Angular 8 introduced that a static property inside @ViewChild() is required as stated here and here. Then your code would require this small change:

@ViewChild('one') d1:ElementRef;

into

// query results available in ngOnInit
@ViewChild('one', {static: true}) foo: ElementRef;

OR

// query results available in ngAfterViewInit
@ViewChild('one', {static: false}) foo: ElementRef;

How can VBA connect to MySQL database in Excel?

Updating this topic with a more recent answer, solution that worked for me with version 8.0 of MySQL Connector/ODBC (downloaded at https://downloads.mysql.com/archives/c-odbc/):

Public oConn As ADODB.Connection
Sub MySqlInit()
    If oConn Is Nothing Then
        Dim str As String
        str = "Driver={MySQL ODBC 8.0 Unicode Driver};SERVER=xxxxx;DATABASE=xxxxx;PORT=3306;UID=xxxxx;PWD=xxxxx;"
        Set oConn = New ADODB.Connection
        oConn.Open str
    End If
End Sub

The most important thing on this matter is to check the proper name and version of the installed driver at: HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers\

Can I execute a function after setState is finished updating?

With hooks in React 16.8 onward, it's easy to do this with useEffect

I've created a CodeSandbox to demonstrate this.

useEffect(() => {
  // code to be run when state variables in
  // dependency array changes
}, [stateVariables, thatShould, triggerChange])

Basically, useEffect synchronises with state changes and this can be used to render the canvas

import React, { useState, useEffect, useRef } from "react";
import { Stage, Shape } from "@createjs/easeljs";
import "./styles.css";

export default function App() {
  const [rows, setRows] = useState(10);
  const [columns, setColumns] = useState(10);
  let stage = useRef()

  useEffect(() => {
    stage.current = new Stage("canvas");
    var rectangles = [];
    var rectangle;
    //Rows
    for (var x = 0; x < rows; x++) {
      // Columns
      for (var y = 0; y < columns; y++) {
        var color = "Green";
        rectangle = new Shape();
        rectangle.graphics.beginFill(color);
        rectangle.graphics.drawRect(0, 0, 32, 44);
        rectangle.x = y * 33;
        rectangle.y = x * 45;

        stage.current.addChild(rectangle);

        var id = rectangle.x + "_" + rectangle.y;
        rectangles[id] = rectangle;
      }
    }
    stage.current.update();
  }, [rows, columns]);

  return (
    <div>
      <div className="canvas-wrapper">
        <canvas id="canvas" width="400" height="300"></canvas>
        <p>Rows: {rows}</p>
        <p>Columns: {columns}</p>
      </div>
      <div className="array-form">
        <form>
          <label>Number of Rows</label>
          <select
            id="numRows"
            value={rows}
            onChange={(e) => setRows(e.target.value)}
          >
            {getOptions()}
          </select>
          <label>Number of Columns</label>
          <select
            id="numCols"
            value={columns}
            onChange={(e) => setColumns(e.target.value)}
          >
            {getOptions()}
          </select>
        </form>
      </div>
    </div>
  );
}

const getOptions = () => {
  const options = [1, 2, 5, 10, 12, 15, 20];
  return (
    <>
      {options.map((option) => (
        <option key={option} value={option}>
          {option}
        </option>
      ))}
    </>
  );
};

MySQL compare DATE string with string from DATETIME field

SELECT * FROM sample_table WHERE last_visit = DATE_FORMAT('2014-11-24 10:48:09','%Y-%m-%d %H:%i:%s')

this for datetime format in mysql using DATE_FORMAT(date,format).

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

You must link an event in your onClick. Additionally, the click function must receive the event. See the example

export default function Component(props) {

    function clickEvent (event, variable){
        console.log(variable);
    }

    return (
        <div>
            <IconButton
                key="close"
                aria-label="Close"
                color="inherit"
                onClick={e => clickEvent(e, 10)}
            >
        </div>
    )
}

How to disable Hyper-V in command line?

Open command prompt as admin and write :

bcdedit /set hypervisorlaunchtype off

Bootstrap 3 Horizontal Divider (not in a dropdown)

As I found the default Bootstrap <hr/> size unsightly, here's some simple HTML and CSS to balance out the element visually:

HTML:

<hr class="half-rule"/>

CSS:

.half-rule { 
    margin-left: 0;
    text-align: left;
    width: 50%;
 }

Validate that text field is numeric usiung jQuery

I know there isn't any need to add a plugin for this.

But this can be useful if you are doing so many things with numbers. So checkout this plugin at least for a knowledge point of view.

The rest of karim79's answer is super cool.

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
        <script type="text/javascript" src="jquery.numeric.js"></script>
    </head>

    <body>
        <form>
            Numbers only:
            <input class="numeric" type="text" />
            Integers only:
            <input class="integer" type="text" />
            No negative values:
            <input class="positive" type="text" />
            No negative values (integer only):
            <input class="positive-integer" type="text" />
            <a href="#" id="remove">Remove numeric</a>
        </form>

        <script type="text/javascript">
            $(".numeric").numeric();

            $(".integer").numeric(false, function() {
                alert("Integers only");
                this.value = "";
                this.focus();
            });

            $(".positive").numeric({ negative: false },
                function() {
                    alert("No negative values");
                    this.value = "";
                    this.focus();
                });

            $(".positive-integer").numeric({ decimal: false, negative: false },
                function() {
                    alert("Positive integers only");
                    this.value = "";
                    this.focus();
                });

            $("#remove").click(
                function(e)
                {
                    e.preventDefault();
                    $(".numeric,.integer,.positive").removeNumeric();
                }
            );
        </script>

    </body>
</html>

How to add a button to UINavigationBar?

In Swift 2, you would do:

let rightButton: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: nil, action: nil)
self.navigationItem.rightBarButtonItem = rightButton

(Not a major change) In Swift 4/5, it will be:

let rightButton: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.done, target: nil, action: nil)
self.navigationItem.rightBarButtonItem = rightButton

How to Avoid Response.End() "Thread was being aborted" Exception during the Excel file download

I researched online and saw that the Response.End() always throws an exception.

Replace this: HttpContext.Current.Response.End();

With this:

HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client.
HttpContext.Current.Response.SuppressContent = true;  // Gets or sets a value indicating whether to send HTTP content to the client.
HttpContext.Current.ApplicationInstance.CompleteRequest(); // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event.

Mongoose limit/offset and count query

Instead of using 2 separate queries, you can use aggregate() in a single query:

Aggregate "$facet" can be fetch more quickly, the Total Count and the Data with skip & limit

    db.collection.aggregate([

      //{$sort: {...}}

      //{$match:{...}}

      {$facet:{

        "stage1" : [ {"$group": {_id:null, count:{$sum:1}}} ],

        "stage2" : [ { "$skip": 0}, {"$limit": 2} ]
  
      }},
     
     {$unwind: "$stage1"},
  
      //output projection
     {$project:{
        count: "$stage1.count",
        data: "$stage2"
     }}

 ]);

output as follows:-

[{
     count: 50,
     data: [
        {...},
        {...}
      ]
 }]

Also, have a look at https://docs.mongodb.com/manual/reference/operator/aggregation/facet/