Programs & Examples On #Tomcat

Use this tag for questions about Apache Tomcat (or simply Tomcat, formerly also Jakarta Tomcat) which is an open source Servlet Container developed by the Apache Software Foundation (ASF). Most questions should also include a tag specifying the operating system.

How to set CATALINA_HOME variable in windows 7?

Assuming Java (JDK + JRE) is installed in your system, do the following:

  1. Install Tomcat7
  2. Copy 'tools.jar' from 'C:\Program Files (x86)\Java\jdk1.6.0_27\lib' and pasted it under 'C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\lib'.
  3. Setup paths in your Environment Variables as shown below:

C:/>javap javax.servlet.http.HttpServletRequest

It should show a bunch of classes

Using Apache httpclient for https

According to the documentation you need to specify the key store:

Protocol authhttps = new Protocol("https",  
      new AuthSSLProtocolSocketFactory(
          new URL("file:my.keystore"), "mypassword",
          new URL("file:my.truststore"), "mypassword"), 443); 

 HttpClient client = new HttpClient();
 client.getHostConfiguration().setHost("localhost", 443, authhttps);

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

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

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

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

Tomcat request timeout

Add tomcat in Eclipse

In Eclipse, as tomcat server, double click "Tomcat v7.0 Server at Localhost", Change the properties as shown in time out settings 45 to whatever sec you like

No Spring WebApplicationInitializer types detected on classpath

I got a silly error it took me an embarrassingly long to solve.... Check out my pom.xml ...

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

<groupId>com.outbottle</groupId>
<artifactId>PersonalDetailsMVC</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<name>PersonalDetailsMVC</name>

<properties>
    <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <spring.version>4.0.1.RELEASE</spring.version>
    <jstl.version>1.2</jstl.version>
    <javax.servlet.version>3.0.1</javax.servlet.version>
</properties>

<dependencies>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-web-api</artifactId>
        <version>7.0</version>
        <scope>provided</scope>
    </dependency>

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

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

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

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>${javax.servlet.version}</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>${jstl.version}</version>
    </dependency>

</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <compilerArguments>
                    <endorseddirs>${endorsed.dir}</endorseddirs>
                </compilerArguments>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.3</version>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.6</version>
            <executions>
                <execution>
                    <phase>validate</phase>
                    <goals>
                        <goal>copy</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${endorsed.dir}</outputDirectory>
                        <silent>true</silent>
                        <artifactItems>
                            <artifactItem>
                                <groupId>javax</groupId>
                                <artifactId>javaee-endorsed-api</artifactId>
                                <version>7.0</version>
                                <type>jar</type>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

Problem was my package name. It MUST be "com.outbottle" (then config/controllers/model/etc) for it to work. As you can see above, I used Maven (for the first time), Spring, 1.8 JDK and nearly had a stroke debugging this issue. All running on Glassfish (Tomcat is ok too for the above pom config). That said, I'm all happy with myself now and know Maven and Spring much better for the next step of my Spring learning curve. Hoping this helps you also!

Remote debugging Tomcat with Eclipse

See this answer for issues I had with Java 8 and Tomcat 9: Java remote debugging (JPDA) not working for me in Tomcat 9

This is similar to @DAB's warning, and his solution is likely more secure.

Tomcat in Intellij Idea Community Edition

I am using intellij CE to create the WAR, and deploying the war externally using tomcat deployment manager. This works for testing the application however I still couldnt find the way to debug it.

  1. open cmd and current dir to tomcat/bin.
  2. you can start and stop the server using the batch files start.bat and shutdown.bat.
  3. Now build your app using mvn goal in intellij.
  4. Open localhost:8080/ **Your port number may differ.
  5. Use this tomcat application to deploy the application, If you get the authentication error, you would need to set the credentials under conf/tomcat-users.xml.

How to change Java version used by TOMCAT?

There are several good answers on here but I wanted to add one since it may be helpful for users like me who have Tomcat installed as a service on a Windows machine.

Option 3 here: http://www.codejava.net/servers/tomcat/4-ways-to-change-jre-for-tomcat

Basically, open tomcatw.exe and point Tomcat to the version of the JVM you need to use then restart the service. Ensure your deployed applications still work as well.

How do I properly set the permgen size?

Don't put the environment configuration in catalina.bat/catalina.sh. Instead you should create a new file in CATALINA_BASE\bin\setenv.bat to keep your customizations separate of tomcat installation.

Spring Boot War deployed to Tomcat

If you are creating a new app instead of converting an existing one, the easiest way to create WAR based spring boot application is through Spring Initializr.

It auto-generates the application for you. By default it creates Jar, but in the advanced options, you can select to create WAR. This war can be also executed directly.

enter image description here

Even easier is to create the project from IntelliJ IDEA directly:

File ? New Project ? Spring Initializr

"Server Tomcat v7.0 Server at localhost failed to start" without stack trace while it works in terminal

I was facing similar problem this weekend. Tried all the above mentioned tricks, but none of them worked of me. (Working in Eclipse LUNA)

Then i analysed that just before creating a particular servlet, i was running Apache Tomcat v7.0 successfully. Which was "RefreshServlet" as shown below :

RefreshServlet.java

So that practicing servlets to understand the "AutoRefresh" functioning. When i remove this servlet from my application, it works fine, but when i try to add and run this servlet, it gives the same error "Apache Tomcat v7.0 failed to start"

Don't know why, but only removing this servlet works fine for me to run the rest of my application.

So, the bottom line suggestion from me would be that if not any other trick is working, then try removing any latest servlet or any class you just created before getting this error and it may work fine for you too for the rest of the application.

Any further explanation would be appreciated. Thanks

Tomcat starts but home page cannot open with url http://localhost:8080

Make sure no other application using port 8080 before starting tomcat. If that's not the problem please paste tomcat log.

If you want to change tomcat's default port, go to tomcat folder and open conf folder, in which you can see server.xml. In that file you can see something like <Connector port= . Change the port value and start tomcat.

Where can I view Tomcat log files in Eclipse?

Go to the "Server" view, then double-click the Tomcat server you're running. The access log files are stored relative to the path in the "Server path" field, which itself is relative to the workspace path.

Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Problem solved, I've not added the index.html. Which is point out in the web.xml

enter image description here

Note: a project may have more than one web.xml file.

if there are another web.xml in

src/main/webapp/WEB-INF

Then you might need to add another index (this time index.jsp) to

src/main/webapp/WEB-INF/pages/

how to start the tomcat server in linux?

Go to the appropriate subdirectory of the EDQP Tomcat installation directory. The default directories are:

On Linux: /opt/server/tomcat/bin

On Windows: c:\server\tomcat\bin

Run the startup command:

On Linux: ./startup.sh

On Windows: % startup.bat

Run the shutdown command:

On Linux: ./shutdown.sh

On Windows: % shutdown.bat

How do you know if Tomcat Server is installed on your PC

Open your windows search bar, and search for the keyword Tomcat. If a shortcut file is found instead, you can open the source file location of the shortcut by right-clicking the shortcut file and selecting the Properties.

Server http:/localhost:8080 requires a user name and a password. The server says: XDB

Just change the port number used e.g. 8000 then call the http://localhost:8080

How to clear PermGen space Error in tomcat

The PermGen space is what Tomcat uses to store class definitions (definitions only, no instantiations) and string pools that have been interned. From experience, the PermGen space issues tend to happen frequently in dev environments really since Tomcat has to load new classes every time it deploys a WAR or does a jspc (when you edit a jsp file). Personally, I tend to deploy and redeploy wars a lot when I’m in dev testing so I know I’m bound to run out sooner or later (primarily because Java’s GC cycles are still kinda crap so if you redeploy your wars quickly and frequently enough, the space fills up faster than they can manage).

This should theoretically be less of an issue in production environments since you (hopefully) don’t change the codebase on a 10 minute basis. If it still occurs, that just means your codebase (and corresponding library dependencies) are too large for the default memory allocation and you’ll just need to mess around with stack and heap allocation. I think the standards are stuff like:

-XX:MaxPermSize=SIZE

I’ve found however the best way to take care of that for good is to allow classes to be unloaded so your PermGen never runs out:

-XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled

Stuff like that worked magic for me in the past. One thing tho, there’s a significant performance tradeoff in using those, since permgen sweeps will make like an extra 2 requests for every request you make or something along those lines. You’ll need to balance your use with the tradeoffs.

Deployment error:Starting of Tomcat failed, the server port 8080 is already in use

If on Linux you can kill existing Tomcats with this script

#/bin/bash
if [ `whoami` != root ]; then
    echo "Please run this script as root or using sudo"
    exit
fi
echo
echo "finding proceses that have name java and established connections status"
echo
echo "Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name"
netstat --tcp  --programs  | grep "ESTABLISHED" | grep "java"
echo
echo "finding proceses that use port 8080 or http-alt"
echo
netstat --tcp --programs | grep ':8080\|:http-alt'
echo -n "Do you wish to kill a process listed above?[Y/n]"
read choose
if [ "$choose" = "Y" ] || [ "$choose" = "y" ] || [ -z "$choose" ]
then
echo "enter pid to kill"
read procesId
kill -9 $procesId
fi
echo "done exiting"
exit 0

Tomcat 8 is not able to handle get request with '|' in query parameters?

Since Tomcat 7.0.76, 8.0.42, 8.5.12 you can define property requestTargetAllow to allow forbiden characters.

Add this line in your catalina.properties

tomcat.util.http.parser.HttpParser.requestTargetAllow=|{}

How do I increase memory on Tomcat 7 when running as a Windows Service?

If you are running a custom named service, you should see two executables in your Tomcat/bin directory
In my case with Tomcat 8

08/14/2019  10:24 PM           116,648 Tomcat-Custom.exe
08/14/2019  10:24 PM           119,720 Tomcat-Customw.exe
               2 File(s)        236,368 bytes

Running the "w" terminated executable will let you configure Xmx in the Java tab
enter image description here

Error starting Tomcat from NetBeans - '127.0.0.1*' is not recognized as an internal or external command

Assuming you are on Windows (this bug is caused by the crappy bat files escaping), It is a bug introduced in the latest versions (7.0.56 and 8.0.14) to workaround another bug. Try to remove the " around the JAVA_OPTS declaration in catalina.bat. It fixed it for me with Tomcat 7.0.56 yesterday.

In 7.0.56 in bin/catalina.bat:179 and 184

:noJuliConfig
set "JAVA_OPTS=%JAVA_OPTS% %LOGGING_CONFIG%"

..

:noJuliManager
set "JAVA_OPTS=%JAVA_OPTS% %LOGGING_MANAGER%"

to

:noJuliConfig
set JAVA_OPTS=%JAVA_OPTS% %LOGGING_CONFIG%

.. 

:noJuliManager
set JAVA_OPTS=%JAVA_OPTS% %LOGGING_MANAGER%

For your asterisk, it might only be a configuration of yours somewhere that appends it to the host declaration.

I saw this on Tomcat's bugtracker yesterday but I can't find the link again. Edit Found it! https://issues.apache.org/bugzilla/show_bug.cgi?id=56895

I hope it fixes your problem.

Tomcat manager/html is not available?

In my case, the folder was _Manager. After I renamed it to Manager it worked.

Now, I see login popup and I enter credentials from conf/tomcat-users.xml, It all works fine.

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.

IntelliJ and Tomcat.. Howto..?

The problem I had was due to the fact that I was unknowingly editing the default values and not a new Tomcat instance at all. Click the plus sign at the top left part of the Run window and select Tomcat | Local from there.

Tomcat is web server or application server?

Application Server:

Application server maintains the application logic and
serves the web pages in response to user request.

That means application server can do both application logic maintanence and web page serving.

Web Server:

Web server just serves the web pages and it cannot enforce any application logic.

Final conclusion is: Application server also contains the web server.

For further Reference : http://www.javaworld.com/javaqa/2002-08/01-qa-0823-appvswebserver.html

HttpServlet cannot be resolved to a type .... is this a bug in eclipse?

You have to set the runtime for your web project to the Tomcat installation you are using; you can do it in the "Targeted runtimes" section of the project configuration.

In this way you will allow Eclipse to add Tomcat's Java EE Web Profile jars to the build path.

Remember that the HttpServlet class isn't in a JRE, but at least in an Enterprise Web Profile (e.g. a servlet container runtime /lib folder).

Recommended way to save uploaded files in a servlet application

Store it anywhere in an accessible location except of the IDE's project folder aka the server's deploy folder, for reasons mentioned in the answer to Uploaded image only available after refreshing the page:

  1. Changes in the IDE's project folder does not immediately get reflected in the server's work folder. There's kind of a background job in the IDE which takes care that the server's work folder get synced with last updates (this is in IDE terms called "publishing"). This is the main cause of the problem you're seeing.

  2. In real world code there are circumstances where storing uploaded files in the webapp's deploy folder will not work at all. Some servers do (either by default or by configuration) not expand the deployed WAR file into the local disk file system, but instead fully in the memory. You can't create new files in the memory without basically editing the deployed WAR file and redeploying it.

  3. Even when the server expands the deployed WAR file into the local disk file system, all newly created files will get lost on a redeploy or even a simple restart, simply because those new files are not part of the original WAR file.

It really doesn't matter to me or anyone else where exactly on the local disk file system it will be saved, as long as you do not ever use getRealPath() method. Using that method is in any case alarming.

The path to the storage location can in turn be definied in many ways. You have to do it all by yourself. Perhaps this is where your confusion is caused because you somehow expected that the server does that all automagically. Please note that @MultipartConfig(location) does not specify the final upload destination, but the temporary storage location for the case file size exceeds memory storage threshold.

So, the path to the final storage location can be definied in either of the following ways:

  • Hardcoded:

      File uploads = new File("/path/to/uploads");
    
  • Environment variable via SET UPLOAD_LOCATION=/path/to/uploads:

      File uploads = new File(System.getenv("UPLOAD_LOCATION"));
    
  • VM argument during server startup via -Dupload.location="/path/to/uploads":

      File uploads = new File(System.getProperty("upload.location"));
    
  • *.properties file entry as upload.location=/path/to/uploads:

      File uploads = new File(properties.getProperty("upload.location"));
    
  • web.xml <context-param> with name upload.location and value /path/to/uploads:

      File uploads = new File(getServletContext().getInitParameter("upload.location"));
    
  • If any, use the server-provided location, e.g. in JBoss AS/WildFly:

      File uploads = new File(System.getProperty("jboss.server.data.dir"), "uploads");
    

Either way, you can easily reference and save the file as follows:

File file = new File(uploads, "somefilename.ext");

try (InputStream input = part.getInputStream()) {
    Files.copy(input, file.toPath());
}

Or, when you want to autogenerate an unique file name to prevent users from overwriting existing files with coincidentally the same name:

File file = File.createTempFile("somefilename-", ".ext", uploads);

try (InputStream input = part.getInputStream()) {
    Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}

How to obtain part in JSP/Servlet is answered in How to upload files to server using JSP/Servlet? and how to obtain part in JSF is answered in How to upload file using JSF 2.2 <h:inputFile>? Where is the saved File?

Note: do not use Part#write() as it interprets the path relative to the temporary storage location defined in @MultipartConfig(location).

See also:

Access Tomcat Manager App from different host

Following two configuration is working for me.

1 .tomcat-users.xml details
--------------------------------
  <role rolename="manager-gui"/>
  <role rolename="manager-script"/>
  <role rolename="manager-jmx"/>
  <role rolename="manager-status"/>
  <role rolename="admin-gui"/>
  <role rolename="admin-script"/>
  <role rolename="tomcat"/>


  <user  username="tomcat"  password="tomcat" roles="tomcat"/>

  <user  username="admin"  password="admin" roles="admin-gui"/>

  <user  username="adminscript"  password="adminscrip" roles="admin-script"/>

  <user  username="tomcat"  password="s3cret" roles="manager-gui"/>
  <user  username="status"  password="status" roles="manager-status"/>

  <user  username="both"    password="both"   roles="manager-gui,manager-status"/>

  <user  username="script"  password="script" roles="manager-script"/>
  <user  username="jmx"     password="jmx"    roles="manager-jmx"/>

2. context.xml  of <tomcat>/webapps/manager/META-INF/context.xml and 
<tomcat>/webapps/host-manager/META-INF/context.xml
------------------------------------------------------------------------
<Context antiResourceLocking="false" privileged="true" >

  <Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow=".*" />
  <Manager sessionAttributeValueClassNameFilter="java\.lang\.(?:Boolean|Integer|Long|Number|String)|org\.apache\.catalina\.filters\.CsrfPreventionFilter\$LruCache(?:\$1)?|java\.util\.(?:Linked)?HashMap"/>

Tomcat 7 "SEVERE: A child container failed during start"

I have the same problem a few months ago. This solve my problem using Maven instead of a downloaded version of Spring and some changes in the web.xml.

pom.xml

<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>SpringWEB1</groupId>
  <artifactId>SpringWEB1</artifactId>
  <version>1</version>
  <packaging>war</packaging>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.4</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
          <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.1.7.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
    </dependency>
  </dependencies>
</project>

Controller.java

package com.jmtm.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@org.springframework.stereotype.Controller
public class Controller {

    @RequestMapping("/hi")
    public ModelAndView hi(){
        return new ModelAndView("Hello", "msg", "Hello user.");
    }

}

spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:c="http://www.springframework.org/schema/c"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">

    <context:component-scan base-package="com.jmtm.controller"></context:component-scan>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

</beans>

And the most important part of the solution, include the path of the servlet dispatcher (A.K.A. spring-servlet.xml) in the web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SpringWEB1</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

Something weird happen when I try to solve this. Any downloaded version of Spring from maven.springframework.org/release/org/springframework/spring gives me a lot of problems (Tomcat couldn't find servlet, Spring stops Tomcat, Eclipse couldn't start the server {weird}) so with many problems find many partial solutions. I hope this works for you.

As an extra help, in Eclipse, download from the Eclipse Marketplace the Spring STS Tool for Eclipse, this will help you to create configuration files (servlet.xml) and write code for the servlet in the web.xml file.

The infamous java.sql.SQLException: No suitable driver found

I had this exact issue when developing a Spring Boot application in STS, but ultimately deploying the packaged war to WebSphere(v.9). Based on previous answers my situation was unique. ojdbc8.jar was in my WEB-INF/lib folder with Parent Last class loading set, but always it says it failed to find the suitable driver.

My ultimate issue was that I was using the incorrect DataSource class because I was just following along with online tutorials/examples. Found the hint thanks to David Dai comment on his own question here: Spring JDBC Could not load JDBC driver class [oracle.jdbc.driver.OracleDriver]

Also later found spring guru example with Oracle specific driver: https://springframework.guru/configuring-spring-boot-for-oracle/

Example that throws error using org.springframework.jdbc.datasource.DriverManagerDataSource based on generic examples.

@Config
@EnableTransactionManagement
public class appDataConfig {
 \* Other Bean Defs *\
    @Bean
    public DataSource dataSource() {
        // configure and return the necessary JDBC DataSource
        DriverManagerDataSource dataSource = new DriverManagerDataSource("jdbc:oracle:thin:@//HOST:PORT/SID", "user", "password");
        dataSource.setSchema("MY_SCHEMA");
        return dataSource;
    }
}

And the corrected exapmle using a oracle.jdbc.pool.OracleDataSource:

@Config
@EnableTransactionManagement
public class appDataConfig {
/* Other Bean Defs */
@Bean
    public DataSource dataSource() {
        // configure and return the necessary JDBC DataSource
        OracleDataSource datasource = null;
        try {
            datasource = new OracleDataSource();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        datasource.setURL("jdbc:oracle:thin:@//HOST:PORT/SID");
        datasource.setUser("user");
        datasource.setPassword("password");

        return datasource;
    }
}

http://localhost:8080/ Access Error: 404 -- Not Found Cannot locate document: /

I think I figured out the questions after reading the log. Thanks to Will's reminder, I checked the log and found out the some program else is listening to that port. Before I can start to figure out which program, my computer was restarted and localhost:8080 works and showing tomcat page. Whooh

How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses?

Several connectors are configured, and each connector has an optional "address" attribute where you can set the IP address.

  1. Edit tomcat/conf/server.xml.
  2. Specify a bind address for that connector:
    <Connector 
        port="8080" 
        protocol="HTTP/1.1" 
        address="127.0.0.1"
        connectionTimeout="20000" 
        redirectPort="8443" 
      />
    

How to tune Tomcat 5.5 JVM Memory settings without using the configuration program

Serhii's suggestion works and here is some more detail.

If you look in your installation's bin directory you will see catalina.sh or .bat scripts. If you look in these you will see that they run a setenv.sh or setenv.bat script respectively, if it exists, to set environment variables. The relevant environment variables are described in the comments at the top of catalina.sh/bat. To use them create, for example, a file $CATALINA_HOME/bin/setenv.sh with contents

export JAVA_OPTS="-server -Xmx512m"

For Windows you will need, in setenv.bat, something like

set JAVA_OPTS=-server -Xmx768m

Hope this helps, Glenn

Can't start Tomcat as Windows Service

Go to Start > Configure Tomcat >

  • Startup > Mode = Java
  • Shutdown > Mode = Java

This worked for me!

Increasing Heap Size on Linux Machines

Changing Tomcat config wont effect all JVM instances to get theses settings. This is not how it works, the setting will be used only to launch JVMs used by Tomcat, not started in the shell.

Look here for permanently changing the heap size.

403 Access Denied on Tomcat 8 Manager App without prompting for user/password

In my case it was the security constraints defined in web.xml. Make sure they have the same roles you use in your tomcat-users.xml file.

For example, this is one of the out-of-the-box tags and will work with the standard tomcat-users.xml.

 <security-constraint>
    <web-resource-collection>
      <web-resource-name>HTML Manager interface (for humans)</web-resource-name>
      <url-pattern>/html/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
       <role-name>manager-gui</role-name>
    </auth-constraint>
  </security-constraint>

In my case an admin had used a different role-name which prevented me from accessing the manager.

How to purge tomcat's cache when deploying a new .war file? Is there a config setting?

Tomcat also creates a ROOT directory at the same level as work/. ROOT/ also caches the old stuff. delete ROOT along with Catalina directory in work.

Default username password for Tomcat Application Manager

The admin and manager apps are two separate things. Here's a snapshot of a tomcat-users.xml file that works, try this:

<?xml version='1.0' encoding='utf-8'?>  
<tomcat-users>  
    <role rolename="tomcat"/>  
    <role rolename="role1"/>  
    <role rolename="manager"/>  
    <user username="tomcat" password="tomcat" roles="tomcat"/>  
    <user username="both" password="tomcat" roles="tomcat,role1"/>  
    <user username="role1" password="tomcat" roles="role1"/>  
    <user username="USERNAME" password="PASSWORD" roles="manager,tomcat,role1"/>  
</tomcat-users>  

It works for me very well

How to deploy a Java Web Application (.war) on tomcat?

The tomcat manual says:

Copy the web application archive file into directory $CATALINA_HOME/webapps/. When Tomcat is started, it will automatically expand the web application archive file into its unpacked form, and execute the application that way.

How to see tomcat is running or not

open http://localhost:8080/ in browser, if you get tomcat home page. it means tomcat is running

Best way to increase heap size in catalina.bat file

increase heap size of tomcat for window add this file in apache-tomcat-7.0.42\bin

enter image description here

heap size can be changed based on Requirements.

  set JAVA_OPTS=-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256m

org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

I had the same problem with eclipse, the WA solution was to copy the libs to WEB-INF/lib

Netbeans 8.0.2 The module has not been deployed

the solution to this problem differs because each time you deploy the application will give you the same sentence or the problem is different, so you should see the tomcat server log for the exact problem.

How can I specify my .keystore file with Spring Boot and Tomcat?

For external keystores, prefix with "file:"

server.ssl.key-store=file:config/keystore 

Setting property 'source' to 'org.eclipse.jst.jee.server:JSFTut' did not find a matching property

I thought I'd add that for Tomcat 7.x, <Context> is not in the server.xml, but in the context.xml. Removing and re-adding the project did not seem to help my similar issue, which was a web.xml issue, which I found out by checking the context.xml which had this line in the <Context> section:

<WatchedResource>WEB-INF/web.xml</WatchedResource>

The solution in WARNING: Setting property 'source' to 'org.eclipse.jst.jee.server:appname' did not find a matching property brought me closer to my answer, as the change of publishing into a separate XML did resolve the error reported above for me, but unfortunately it generated a second error that I'm still investigating.

WARNING: [SetContextPropertiesRule]{Context} Setting property 'source' to 'org.eclipse.jst.jee.server:myproject' did not find a matching property.

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

aforementioned solutions did not help me, I could solve it by re-installing the Tomcat server which took few seconds.

Is this very likely to create a memory leak in Tomcat?

The key "Transactional Resources" looks like you are talking to the database without a proper transaction. Make sure transaction management is configured properly and no invocation path to the DAO exists that doesn't run under a @Transactional annotation. This can easily happen when you configured transaction management on the Controller level but are invoking DAOs in a timer or are using @PostConstruct annotations. I wrote it up here http://georgovassilis.blogspot.nl/2014/01/tomcat-spring-and-memory-leaks-when.html

Edit: It looks like this is (also?) a bug with spring-data-jpa which has been fixed with v1.4.3. I looked it up in the spring-data-jpa sources of LockModeRepositoryPostProcessor which sets the "Transactional Resources" key. In 1.4.3 it also clears the key again.

Change Tomcat Server's timeout in Eclipse

SOLVED: That's it!!!! For me was compiling with JDK6 but running Tomcat with JDK7, WST uses the system properties and not the eclipse settings. I also configure the same JDK Version in eclipse and in System (check it with java -version in cmd line)

Details: I try to configure eclipse like describe here, but it didn´t solve the problem, then I notice in eclipse´s error log that tomcat was started with jre 1.7. in spite of my configurations.

I also try, in cmd line, 'java -version' and obtained '1.7' instead of expected '1.6'.

I also decide to configure java 1.6 (like in eclipse) in system panel but it didn´t solve the problem. I also desinstall jre 1.7 restart eclipse AND IT SUCCESS!.. It was a very usefull clue, thank you.

IntelliJ, can't start simple web application: Unable to ping server at localhost:1099

I added my hostname to /etc/hosts on localhost. Added JAVA_HOME but still it showed the same error. In the console, there was output:

Unable to start as CATALINA_BASE contains a colon (:) character

I solved the problem by going to Edit configurations -> Startup/Connection -> changing CATALINA_BASE value to the tomcat installation folder. Before that, it was

CATALINA_BASE:   C:\Program Files\Apache Software Foundation\Tomcat 8.0

which can't be correct on a linux machine ;)

Redirecting a request using servlets and the "setHeader" method not working

Oh no no! That's not how you redirect. It's far more simpler:

public class ModHelloWorld extends HttpServlet{
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
        response.sendRedirect("http://www.google.com");
    }
}

Also, it's a bad practice to write HTML code within a servlet. You should consider putting all that markup into a JSP and invoking the JSP using:

response.sendRedirect("/path/to/mynewpage.jsp");

Official reasons for "Software caused connection abort: socket write error"

For anyone using simple Client Server programms and getting this error, it is a problem of unclosed (or closed to early) Input or Output Streams.

org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

For Intellij Idea sometime localhost.log file generated at different location. For e.g. you can find it at homedirectory\ .IntelliJIdea14\system\tomcat.

IF you are using spring then start ur server in debug mode and put debug point in catch block of org.springframework.context.support.AbstractApplicationContext's refresh() method. If bean creation fails you would be able to see the exception.

Apache Tomcat Not Showing in Eclipse Server Runtime Environments

nor does it appear in the list of environments that can be added when I click the "Add" button. All I see is the J2EE Runtime Library.

Go get "Eclipse for Java EE developers". Note the extra "EE". This includes among others the Web Tools Platform with among others a lot of server plugins with among others the one for Apache Tomcat 5.x. It's also logically; JSP/Servlet is part of the Java EE API.

Unknown version of Tomcat was specified in Eclipse

Having installed tomcat with brew the solution for me was:

sudo chmod -R 777 /usr/local/Cellar/tomcat/<your_version>

org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]A child container failed during start

If you are using the following stack: Server Version: Apache Tomcat/9.0.21 Servlet Version: 4.0 JSP Version: 2.3

Then try adding <absolute-ordering /> to your web.xml file. So your file looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>spring-mvc-crud-demo</display-name>

  <absolute-ordering />

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>

  ......

Tomcat Server Error - Port 8080 already in use

The Way I solved this problem is , Install TCPview go to TCP view and check what ports is Tomcat utilizing there will be few other ports other than 8005,8009,8080 now go to Servers tab in eclipse double click on Tomcatv9.0 server and change port numbers there. This will solve the problem.

Simplest way to serve static data from outside the application server in a Java web application

Add to server.xml :

 <Context docBase="c:/dirtoshare" path="/dir" />

Enable dir file listing parameter in web.xml :

    <init-param>
        <param-name>listings</param-name>
        <param-value>true</param-value>
    </init-param>

How to deploy a war file in Tomcat 7

For deploying the war file over tomcat, Follow the below steps :

  1. Stop the tomcat. powershell->services.msc->OK->Apache Tomcat 8.5->stop(on left hand side).

enter image description here

  1. Put the .war file inside E:\Tomcat_Installation\webapps i.e. webapps folder i.e. put.war (put.war is just an example)

enter image description here

  1. After starting the tomcat(to start tomcat powershell->services.msc->OK->Apache Tomcat 8.5->start )

you will get one folder inside E:\Tomcat_Installation\webapps**put**

enter image description here

In this way you can deploy your war file in Apache Tomcat.

Kill tomcat service running on any port, Windows

netstat -ano | findstr :3010

enter image description here

taskkill /F /PID

enter image description here

But it won't work for me

then I tried taskkill -PID <processorid> -F

Example:- taskkill -PID 33192 -F Here 33192 is the processorid and it works enter image description here

Eclipse Build Path Nesting Errors

Try this:

From the libraries tab:

Eclipse -> right click on project name in sidebar -> configure build path -> Libraries

Remove your web app libraries:

click on "Web App Libraries" -> click "remove"

Add them back in:

click "Add Library" -> click to highlight "Web App Libraries" -> click "next" -> confirm your desired project is the selected option -> click "Finish"

Highlighting "Web App Libraries":

Highlighting "Web App Libraries"

Where can I find the Tomcat 7 installation folder on Linux AMI in Elastic Beanstalk?

Following environment variables worked for me on Debian Wheezy 7 and Tomcat 7:

CATALINA_HOME=/usr/share/tomcat7
CATALINA_BASE=/var/lib/tomcat7
CATALINA_TMPDIR=/tmp/tomcat7

(I did create /tmp/tomcat7 manually)

Deploying just HTML, CSS webpage to Tomcat

Here's my step in Ubuntu 16.04 and Tomcat 8.

  1. Copy folder /var/lib/tomcat8/webapps/ROOT to your folder.

    cp -r /var/lib/tomcat8/webapps/ROOT /var/lib/tomcat8/webapps/{yourfolder}

  2. Add your html, css, js, to your folder.

  3. Open "http://localhost:8080/{yourfolder}" in browser

Notes:

  1. If you using chrome web browser and did wrong folder before, then clean web browser's cache(or change another name) otherwise (sometimes) it always 404.

  2. The folder META-INF with context.xml is needed.

Access-Control-Allow-Origin: * in tomcat

Change this:

<init-param>
    <param-name>cors.supportedHeaders</param-name>
    <param-value>Content-Type, Last-Modified</param-value>
</init-param>

To this

<init-param>
    <param-name>cors.supportedHeaders</param-name>
    <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified</param-value>
</init-param>

I had to do this to get anything to work.

Tomcat started in Eclipse but unable to connect to http://localhost:8085/

Right-click on your project's name in Eclipse's Project Explorer, then click Run As followed by Run on Server. Click the Next button. Make sure your project's name is listed in the Configured: column on the right. If it is, then you should be able to access it with this URL:

http://localhost:8085/projectname/

Additionally, whenever you make new additions (such as new JSPs, graphics or other resources) to your project, be sure to refresh the project by clicking on its name and then hitting F5. Otherwise Eclipse does not know that those new resources are available and will not make them available to Tomcat to serve.

port 8080 is already in use and no process using 8080 has been listed

PID is the process ID - not the port number. You need to look for an entry with ":8080" at the end of the address/port part (the second column). Then you can look at the PID and use Task Manager to work out which process is involved... or run netstat -abn which will show the process names (but must be run under an administrator account).

Having said that, I would expect the find "8080" to find it...

Another thing to do is just visit http://localhost:8080 - on that port, chances are it's a web server of some description.

Starting of Tomcat failed from Netbeans

I had the same problem but none of the answers above worked. The solution for me was to restore the Manager web application that is bundled with Tomcat.

How to set the context path of a web application in Tomcat 7.0

In Tomcat 8.X ,under tomcat home directory /conf/ folder in server.xml you can add <Context> tag under <Host> tag as shown below . But you have to restart the server in order to take effect

  <Host name="localhost"  appBase="webapps"
        unpackWARs="true" autoDeploy="true">

     <Context docBase="${catalina.base}\webapps\<Your App Directory Name>" path="<your app path you wish>" reloadable="true" />
  </Host>

OR if you are using Tomcat 7.X you can add context.xml file in WEB-INF folder in your project . The contents of the file i used is as shown . and it worked fine for me . you don't have to restart server in this case .

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

<Context docBase="${catalina.base}\webapps\<My App Directory Name>" path="<your app path you wish>" reloadable="true" />

What does "The APR based Apache Tomcat Native library was not found" mean?

I just went through this and configured it with the following:

Ubuntu 16.04

Tomcat 8.5.9

Apache2.4.25

APR 1.5.2

Tomcat-native 1.2.10

Java 8

These are the steps i used based on the older posts here:

Install package

sudo apt-get update
sudo apt-get install libtcnative-1

Verify these packages are installed

sudo apt-get install make 
sudo apt-get install gcc
sudo apt-get install openssl

Install package

sudo apt-get install libssl-dev

Install and compile Apache APR

cd /opt/tomcat/bin
sudo wget http://apache.mirror.anlx.net//apr/apr-1.5.2.tar.gz
sudo tar -xzvf apr-1.5.2.tar.gz
cd apr-1.5.2
sudo ./configure
sudo make
sudo make install

verify installation

cd /usr/local/apr/lib/
ls 

you should see the compiled file as

libapr-1.la

Download and install Tomcat Native source package

cd /opt/tomcat/bin
sudo wget https://archive.apache.org/dist/tomcat/tomcat-connectors/native/1.2.10/source/tomcat-native-1.2.10-src.tar.gz
sudo tar -xzvf tomcat-native-1.2.10-src.tar.gz
cd tomcat-native-1.2.10-src/native

verify JAVA_HOME

sudo pico ~/.bashrc
export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
source ~/.bashrc
sudo ./configure --with-apr=/usr/local/apr --with-java-home=$JAVA_HOME
sudo make
sudo make install

Edit the /opt/tomcat/bin/setenv.sh file with following line:

sudo pico /opt/tomcat/bin/setenv.sh
export LD_LIBRARY_PATH='$LD_LIBRARY_PATH:/usr/local/apr/lib'

restart tomcat

sudo service tomcat restart

build-impl.xml:1031: The module has not been deployed

if you still getting this error try this.

  1. Go to Netbeans services
  2. Remove Apache Tomcat.
  3. Add Apache Tomcat again.
  4. Build Project.
  5. Deploy Project

enter image description here

How to setup Tomcat server in Netbeans?

I had same issue. No need to re install.

In Netbeans 6.0 , Find RunTime -> Servers - > Add server -> select Tomcat install 'root' directory

In Netbeans 7.x -> Tools -> Servers-> Add server -> select Tomcat install 'root' directory

Here is in Netbeans Wiki.

http://wiki.netbeans.org/AddExternalTomcat

Is there a max size for POST parameter content?

There is no defined maximum size for HTTP POST requests. If you notice such a limit then it's an arbitrary limitation of your HTTP Server/Client.

You might get a better answer if you tell how big the XML is.

What is the difference between Tomcat, JBoss and Glassfish?

JBoss and Glassfish are basically full Java EE Application Server whereas Tomcat is only a Servlet container. The main difference between JBoss, Glassfish but also WebSphere, WebLogic and so on respect to Tomcat but also Jetty, was in the functionality that an full app server offer. When you had a full stack Java EE app server you can benefit of all the implementation of the vendor of your choice, and you can benefit of EJB, JTA, CDI(JAVA EE 6+), JPA, JSF, JSP/Servlet of course and so on. With Tomcat on the other hands you can benefit only of JSP/Servlet. However to day with advanced Framework such as Spring and Guice, many of the main advantage of using an a full stack application server can be mitigate, and with the assumption of a one of this framework manly with Spring Ecosystem, you can benefit of many sub project that in the my work experience let me to left the use of a full stack app server in favour of lightweight app server like tomcat.

How to enable CORS in apache tomcat

Just to add a bit of extra info over the right solution. Be aware that you'll need this class org.apache.catalina.filters.CorsFilter. So in order to have it, if your tomcat is not 7.0.41 or higher, download 'tomcat-catalina.7.0.41.jar' or higher ( you can do it from http://mvnrepository.com/artifact/org.apache.tomcat/tomcat-catalina ) and put it in the 'lib' folder inside Tomcat installation folders. I actually used 7.0.42 Hope it helps!

Deploying my application at the root in Tomcat

Adding on to @Rob Hruska's sol, this setting in server.xml inside section works:

<Context path="" docBase="gateway" reloadable="true" override="true"> </Context>

Note: override="true" might be required in some cases.

ClientAbortException: java.net.SocketException: Connection reset by peer: socket write error

Your HTTP client disconnected.

This could have a couple of reasons:

  • Responding to the request took too long, the client gave up
  • You responded with something the client did not understand
  • The end-user actually cancelled the request
  • A network error occurred
  • ... probably more

You can fairly easily emulate the behavior:

URL url = new URL("http://example.com/path/to/the/file");

int numberOfBytesToRead = 200;

byte[] buffer = new byte[numberOfBytesToRead];
int numberOfBytesRead = url.openStream().read(buffer);

How to set JAVA_HOME for multiple Tomcat instances?

If you are a Windows user, put the content below in a setenv.bat file that you must create in Tomcat bin directory.

set JAVA_HOME=C:\Program Files\Java\jdk1.6.x

If you are a Linux user, put the content below in a setenv.sh file that you must create in Tomcat bin directory.

JAVA_HOME=/usr/java/jdk1.6.x

java.net.SocketTimeoutException: Read timed out under Tomcat

Connection.Response resp = Jsoup.connect(url) //
                .timeout(20000) //
                .method(Connection.Method.GET) //
                .execute();

actually, the error occurs when you have slow internet so try to maximize the timeout time and then your code will definitely work as it works for me.

Is Tomcat running?

Basically you want to test

  1. Connectivity to your tomcat instance
  2. Gather some basic statistics
  3. Whether the unix process is running

I will evaluate first 2 options as the 3rd one has been sufficiently answered already.

easiest is just to develop a webpage on your WebApp that gathers some basic metrics, and have a client that can read the results or detect connectivity issues.

For doing so, you have several issues

Eclipse add Tomcat 7 blank server name

In Eclipse Neon.3 Release (4.6.3) on Ubuntu 17.04 with Tomcat 8.0 the problem persists. What helped me was the combination of deleting the prefs files:

rm ~/workspace/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.jst.server.tomcat.core.prefs    
rm ~/workspace/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.wst.server.core.prefs

and linking to catalina.policy (somewhat differently than how @michael-brooks suggested for his configuration):

sudo ln -s /var/lib/tomcat8/policy/catalina.policy conf/catalina.policy

Multiple contexts with the same path error running web service in Eclipse using Tomcat

This error occurs when you copy a project than past it, and then you change the name of that project.

in such a case, follow the following steps.

Step-1: you need to edit your web.xml file. remove servlet and servlet-mapping of the previous projects.

Step-2: got to SERVER--> server.xml--> find context

Example :- Context docBase="JSPandServletDemo" path="/JSPandServletDemo" reloadable="true" source="org.eclipse.jst.jee.server:JSPandServletDemo"/>

now you just need to change the pathname to your current project name.

Good Luck Happy Coding :)

FAIL - Application at context path /Hello could not be started

check web.xml file maybe servletContextlistener not doing well . in my case i added servletContextlistener and let him an empty and gave me the same error, i tried to delete it from project files but it still in web.xml file .finally i delete it from the web.xml and save the file . run the project and it stated successfully

Could not load the Tomcat server configuration

The application is trying to load /usr/share/tomcat7/conf/ which doesn't exist. Eclipse assumes conf is in the same directory as bin

In Ubuntu, conf is placed in /etc/tomcat7/ and there is a symbolic link in /var/lib/tomcat7/.

To solve this, you can either

  1. Download package from Apache Tomcat, and place them in a specific directory, say /opt/ or
  2. Create a symbolic link in /usr/share/tomcat7/ pointing to /etc/tomcat7/conf

How to create war files

Use ant build code I use this for my project SMS

<property name="WEB-INF" value="${basedir}/WebRoot/WEB-INF" />
<property name="OUT" value="${basedir}/out" />
<property name="WAR_FILE_NAME" value="mywebapplication.war" />
<property name="TEMP" value="${basedir}/temp" />

<target name="help">
    <echo>
        --------------------------------------------------
        compile - Compile
        archive - Generate WAR file
        --------------------------------------------------
    </echo>
</target>

<target name="init">
    <delete dir="${WEB-INF}/classes" />
    <mkdir dir="${WEB-INF}/classes" />
</target>

<target name="compile" depends="init">
    <javac srcdir="${basedir}/src" 
                destdir="${WEB-INF}/classes" 
                classpathref="libs">
    </javac>
</target>

<target name="archive" depends="compile">
    <delete dir="${OUT}" />
    <mkdir dir="${OUT}" />
    <delete dir="${TEMP}" />
    <mkdir dir="${TEMP}" />
    <copy todir="${TEMP}" >
        <fileset dir="${basedir}/WebRoot">
        </fileset>
    </copy>
    <move file="${TEMP}/log4j.properties" 
                    todir="${TEMP}/WEB-INF/classes" />
    <war destfile="${OUT}/${WAR_FILE_NAME}" 
                    basedir="${TEMP}" 
                    compress="true" 
                    webxml="${TEMP}/WEB-INF/web.xml" />
    <delete dir="${TEMP}" />
</target>

<path id="libs">
    <fileset includes="*.jar" dir="${WEB-INF}/lib" />
</path>

Tomcat 7.0.43 "INFO: Error parsing HTTP request header"

If you don't want to upgrade your tomcat, Add this line in your catalina.properties

tomcat.util.http.parser.HttpParser.requestTargetAllow=|{}

It works for me http://www.zhoulujun.cn/zhoulujun/html/java/tomcat/2018_0508_8109.html

What is "pom" packaging in maven?

Packaging of pom is used in projects that aggregate other projects, and in projects whose only useful output is an attached artifact from some plugin. In your case, I'd guess that your top-level pom includes <modules>...</modules> to aggregate other directories, and the actual output is the result of one of the other (probably sub-) directories. It will, if coded sensibly for this purpose, have a packaging of war.

UnsupportedClassVersionError unsupported major.minor version 51.0 unable to load class

Well presumably it's not using the same version of Java when running it externally. Look through the startup scripts carefully to find where it picks up the version of Java to run. You should also check the startup logs to see whether they indicate which version is running.

Alternatively, unless you need the Java 7 features, you could always change your compiler preferences in Eclipse to target 1.6 instead.

SSLHandshakeException: No subject alternative names present

Unlike some browsers, Java follows the HTTPS specification strictly when it comes to the server identity verification (RFC 2818, Section 3.1) and IP addresses.

When using a host name, it's possible to fall back to the Common Name in the Subject DN of the server certificate, instead of using the Subject Alternative Name.

When using an IP address, there must be a Subject Alternative Name entry (of type IP address, not DNS name) in the certificate.

You'll find more details about the specification and how to generate such a certificate in this answer.

Difference between Xms and Xmx and XX:MaxPermSize

Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.

The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.

-Xmssize Specifies the initial heap size.

-Xmxsize Specifies the maximum heap size.

-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.

Sizes are expressed in bytes. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, g or G to indicate gigabytes.

References:

How is the java memory pool divided?

What is perm space?

Java (JVM) Memory Model – Memory Management in Java

Java 7 SE Command Line Options

Java 7 HotSpot VM Options

Bad Gateway 502 error with Apache mod_proxy and Tomcat

If you want to handle your webapp's timeout with an apache load balancer, you first have to understand the different meaning of timeout. I try to condense the discussion I found here: http://apache-http-server.18135.x6.nabble.com/mod-proxy-When-does-a-backend-be-considered-as-failed-td5031316.html :

It appears that mod_proxy considers a backend as failed only when the transport layer connection to that backend fails. Unless failonstatus/failontimeout is used. ...

So, setting failontimeout is necessary for apache to consider a timeout of the webapp (e.g. served by tomcat) as a fail (and consecutively switch to the hot spare server). For the proper configuration, note the following misconfiguration:

ProxyPass / balancer://localbalance/ failontimeout=on timeout=10 failonstatus=50

This is a misconfiguration because:

You are defining a balancer here, so the timeout parameter relates to the balancer (like the two others). However for a balancer, the timeout parameter is not a connection timeout (like the one used with BalancerMember), but the maximum time to wait for a free worker/member (e.g. when all the workers are busy or in error state, the default being to not wait).

So, a proper configuration is done like this

  1. set timeout at the BalanceMember level:
 <Proxy balancer://mycluster>
     BalancerMember http://member1:8080/svc timeout=6 
 ... more BalanceMembers here
</Proxy>
  1. set the failontimeout on the balancer
ProxyPass /svc balancer://mycluster failontimeout=on

Restart apache.

Tomcat: How to find out running tomcat version

run the following

/usr/local/tomcat/bin/catalina.sh version

its response will be something like:

Using CATALINA_BASE:   /usr/local/tomcat
Using CATALINA_HOME:   /usr/local/tomcat
Using CATALINA_TMPDIR: /var/tmp/
Using JRE_HOME:        /usr
Using CLASSPATH:       /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
Using CATALINA_PID:    /var/catalina.pid
Server version: Apache Tomcat/7.0.30
Server built:   Sep 27 2012 05:13:37
Server number:  7.0.30.0
OS Name:        Linux
OS Version:     2.6.32-504.3.3.el6.x86_64
Architecture:   amd64
JVM Version:    1.7.0_60-b19
JVM Vendor:     Oracle Corporation

8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE

hi creating a simple line in application.properties as SERVER_PORT=8090 solved the issue.

Spring Boot application in eclipse, the Tomcat connector configured to listen on port XXXX failed to start

Another easy way of solving this error is right clicking in the console and click on Terminate/Disconnect All. Afterwards run the application it should work fine.

How to resolve Error listenerStart when deploying web-app in Tomcat 5.5?

/var/lib/tomcat5.5/webapps/spaghetti/WEB-INF/lib/jsp-api-6.0.16.jar
/var/lib/tomcat5.5/webapps/spaghetti/WEB-INF/lib/servlet-api-6.0.16.jar

You should not have any server-specific libraries in the /WEB-INF/lib. Leave them in the appserver's own library. It would only lead to collisions in the classpath. Get rid of all appserver-specific libraries in /WEB-INF/lib (and also in JRE/lib and JRE/lib/ext if you have placed any of them there).

A common cause that the appserver-specific libraries are included in the webapp's library is that starters think that it is the right way to fix compilation errors of among others the javax.servlet classes not being resolveable. Putting them in webapp's library is the wrong solution. You should reference them in the classpath during compilation, i.e. javac -cp /path/to/server/lib/servlet.jar and so on, or if you're using an IDE, you should integrate the server in the IDE and associate the web project with the server. The IDE will then automatically take server-specific libraries in the classpath (buildpath) of the webapp project.

At least one JAR was scanned for TLDs yet contained no TLDs

If one wants to have the conf\logging.properties read one must (see also here) dump this file into the Servers\Tomcat v7.0 Server at localhost-config\ folder and then add the lines :

-Djava.util.logging.config.file="${workspace_loc}\Servers\Tomcat v7.0 Server at localhost-config\logging.properties" -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager

to the VM arguments of the launch configuration one is using.

This may have taken a restart or two (or not) but finally I saw in the console in bright red :

FINE: No TLD files were found in [file:/C:/Dropbox/eclipse_workspaces/javaEE/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/ted2012/WEB-INF/lib/logback-classic-1.0.7.jar]. Consider adding the JAR to the tomcat.util.scan.DefaultJarScanner.jarsToSkip or org.apache.catalina.startup.TldConfig.jarsToSkip property in CATALINA_BASE/conf/catalina.properties file. //etc

I still don't know when exactly this FINE warning appears - does not appear immediately on tomcat launch EDIT: from the comment by @Stephan: "The FINE warning appears each time any change is done in the JSP file".


Bonus: To make the warning go away add in catalina.properties :

# Additional JARs (over and above the default JARs listed above) to skip when
# scanning for TLDs. The list must be a comma separated list of JAR file names.
org.apache.catalina.startup.TldConfig.jarsToSkip=logback-classic-1.0.7.jar,\
joda-time-2.1.jar,joda-time-2.1-javadoc.jar,mysql-connector-java-5.1.24-bin.jar,\
logback-core-1.0.7.jar,javax.servlet.jsp.jstl-api-1.2.1.jar

Cannot add a project to a Tomcat server in Eclipse

Steps I used to resolve it:

  1. Double click on Tomcat Server in the Servers tab.
  2. In a dropdown next to Runtime Environment:, select Apache Tomcat your version
  3. Click on save.

Now, you should be able to add to server on right click "Add and Remove".

Note: Additionally, when on clear/run, you get an error for multiple instances, open server.xml and ensure that it contains a single instance of each application and not multiple.

HTTP Status 500 - Error instantiating servlet class pkg.coreServlet

In my case missing private static final long serialVersionUID = 1L; line caused the same error. I added the line and it worked!

How does Tomcat locate the webapps directory?

Change appBase in server.xml

If you want to keep both previous webapps and a new one, you can use another Host instance with another port defined in tomcat.

Tomcat 7 is not running on browser(http://localhost:8080/ )

There could be a number of reasons, have it as a checklist and go through it

Is your server running on 8080?I mean that is the default port but it could be configured to run on other.

Also there is a possibility that the default application is removed/uninstalled that is why it is giving "the requested resource is not available"

Also it could be a proxy issue. make sure you are not using any proxy in your browser.

org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 15

I faced this issue with tomcat 7 + jdk 1.8

with java 1.7 and lower versions it's working fine.

window -> preferences -> java -> installed jre

in my case I changed jre1.8 to JDK 1.7

and accordingly modify project facet , select same java version as it's there in selected Installed JRE.

Python NameError: name is not defined

You must define the class before creating an instance of the class. Move the invocation of Something to the end of the script.

You can try to put the cart before the horse and invoke procedures before they are defined, but it will be an ugly hack and you will have to roll your own as defined here:

Make function definition in a python file order independent

Angularjs - simple form submit

I think the reason AngularJS does not say much about form submission because it depends more on 'two-way data binding'. In traditional html development you had one way data binding, i.e. once DOM rendered any changes you make to DOM element did not reflect in JS Object, however in AngularJS it works both way. Hence there's in fact no need to form submission. I have done a mid sized application using AngularJS without the need to form submission. If you are keen to submit form you can write a directive wrapping up your form which handles ENTER keydown and SUBMIT button click events and call form.submit().

If you want the sample source code of such a directive, please let me know by commenting on this. I figured out it would a simple directive that you can write yourself.

TypeError: 'builtin_function_or_method' object is not subscriptable

You are trying to access pop as if was a list or a tupple, but pop is not. It's a method.

VBA Count cells in column containing specified value

Not what you asked but may be useful nevertheless.

Of course you can do the same thing with matrix formulas. Just read the result of the cell that contains:

Cell A1="Text to search"
Cells A2:C20=Range to search for

=COUNT(SEARCH(A1;A2:C20;1))

Remember that entering matrix formulas needs CTRL+SHIFT+ENTER, not just ENTER. After, it should look like :

{=COUNT(SEARCH(A1;A2:C20;1))}

How to insert current_timestamp into Postgres via python

Sure, just pass a string value for that timestamp column in the format: '2011-05-16 15:36:38' (you can also append a timezone there, like 'PST'). PostgreSQL will automatically convert the string to a timestamp. See http://www.postgresql.org/docs/9.0/static/datatype-datetime.html#DATATYPE-DATETIME-INPUT

jQuery's .click - pass parameters to user function

Yes, this is an old post. Regardless, someone may find it useful. Here is another way to send parameters to event handlers.

//click handler
function add_event(event, paramA, paramB)
{
    //do something with your parameters
    alert(paramA ? 'paramA:' + paramA : '' + paramB ? '  paramB:' + paramB : '');
}

//bind handler to click event
$('.leadtoscore').click(add_event);
...
//once you've processed some data and know your parameters, trigger a click event.
//In this case, we will send 'myfirst' and 'mysecond' as parameters
$('.leadtoscore').trigger('click', {'myfirst', 'mysecond'});

//or use variables
var a = 'first',
    b = 'second';

$('.leadtoscore').trigger('click', {a, b});
$('.leadtoscore').trigger('click', {a});

What is the best way to search the Long datatype within an Oracle database?

Don't use LONGs, use CLOB instead. You can index and search CLOBs like VARCHAR2.

Additionally, querying with a leading wildcard(%) will ALWAYS result in a full-table-scan. Look into Oracle Text indexes instead.

Using ng-if as a switch inside ng-repeat?

This one is noteworthy as well

<div ng-repeat="post in posts" ng-if="post.type=='article'">
  <h1>{{post.title}}</h1>
</div>

Call Activity method from adapter

For Kotlin:

In your adapter, simply call

(context as Your_Activity_Name).yourMethod()

Can curl make a connection to any TCP ports, not just HTTP/HTTPS?

Of course:

curl http://example.com:11740
curl https://example.com:11740

Port 80 and 443 are just default port numbers.

Enabling the OpenSSL in XAMPP

Yes, you must open php.ini and remove the semicolon to:

;extension=php_openssl.dll

If you don't have that line, check that you have the file (In my PC is on D:\xampp\php\ext) and add this to php.ini in the "Dynamic Extensions" section:

extension=php_openssl.dll

Things have changed for PHP > 7. This is what i had to do for PHP 7.2.

Step: 1: Uncomment extension=openssl

Step: 2: Uncomment extension_dir = "ext"

Step: 3: Restart xampp.

Done.

Explanation: ( From php.ini )

If you wish to have an extension loaded automatically, use the following syntax:

extension=modulename

Note : The syntax used in previous PHP versions (extension=<ext>.so and extension='php_<ext>.dll) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>) syntax.

Special Note: Be sure to appropriately set the extension_dir directive.

Where do I find the definition of size_t?

Practically speaking size_t represents the number of bytes you can address. On most modern architectures for the last 10-15 years that has been 32 bits which has also been the size of a unsigned int. However we are moving to 64bit addressing while the uint will most likely stay at 32bits (it's size is not guaranteed in the c++ standard). To make your code that depends on the memory size portable across architectures you should use a size_t. For example things like array sizes should always use size_t's. If you look at the standard containers the ::size() always returns a size_t.

Also note, visual studio has a compile option that can check for these types of errors called "Detect 64-bit Portability Issues".

How can I enable Assembly binding logging?

For me the 'Bla' file was System.Net.http dll which was missing from my BIN folder. I just added it and it worked fine. Didn't change any registry key or anything of that sort.

Session only cookies with Javascript

For creating session only cookie with java script, you can use the following. This works for me.

document.cookie = "cookiename=value; expires=0; path=/";

then get cookie value as following

 //get cookie 
var cookiename = getCookie("cookiename");
if (cookiename == "value") {
    //write your script
}

//function getCookie        
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return "";
}

Okay to support IE we can leave "expires" completely and can use this

document.cookie = "mtracker=somevalue; path=/";

Call apply-like function on each row of dataframe with multiple arguments from each row

Others have correctly pointed out that mapply is made for this purpose, but (for the sake of completeness) a conceptually simpler method is just to use a for loop.

for (row in 1:nrow(df)) { 
    df$newvar[row] <- testFunc(df$x[row], df$z[row]) 
}

How to hide a column (GridView) but still access its value?

You can do it code behind.

Set visible= false for columns after data binding . After that you can again do visibility "true" in row_selection function from grid view .It will work!!

XML Schema How to Restrict Attribute by Enumeration

you need to create a type and make the attribute of that type:

<xs:simpleType name="curr">
  <xs:restriction base="xs:string">
    <xs:enumeration value="pounds" />
    <xs:enumeration value="euros" />
    <xs:enumeration value="dollars" />
  </xs:restriction>
</xs:simpleType>

then:

<xs:complexType>
    <xs:attribute name="currency" type="curr"/>
</xs:complexType>

Are one-line 'if'/'for'-statements good Python style?

Older versions of Python would only allow a single simple statement after for ...: if ...: or similar block introductory statements.

I see that one can have multiple simple statements on the same line as any of these. However, there are various combinations that don't work. For example we can:

for i in range(3): print "Here's i:"; print i

... but, on the other hand, we can't:

for i in range(3): if i % 2: print "That's odd!"

We can:

x=10
while x > 0: print x; x-=1

... but we can't:

x=10; while x > 0: print x; x-=1

... and so on.

In any event all of these are considered to be extremely NON-pythonic. If you write code like this then experience Pythonistas will probably take a dim view of your skills.

It's marginally acceptable to combine multiple statements on a line in some cases. For example:

x=0; y=1

... or even:

if some_condition(): break

... for simple break continue and even return statements or assigments.

In particular if one needs to use a series of elif one might use something like:

if     keystroke == 'q':   break
elif   keystroke == 'c':   action='continue'
elif   keystroke == 'd':   action='delete'
# ...
else:                      action='ask again'

... then you might not irk your colleagues too much. (However, chains of elif like that scream to be refactored into a dispatch table ... a dictionary that might look more like:

dispatch = {
    'q': foo.break,
    'c': foo.continue,
    'd': foo.delete
    }


# ...
while True:
    key = SomeGetKey()
    dispatch.get(key, foo.try_again)()

angular.element vs document.getElementById or jQuery selector with spin (busy) control

Improvement to kaiser's answer:

var myEl = $document.find('#some-id');

Don't forget to inject $document into your directive

How do I make UITableViewCell's ImageView a fixed size even when the image is smaller

I've created an extension using @GermanAttanasio 's answer. It provides a method to resize an image to a desired size, and another method to do the same while adding a transparent margin to the image (this can be useful for table views where you want the image to have a margin as well).

import UIKit

extension UIImage {

    /// Resizes an image to the specified size.
    ///
    /// - Parameters:
    ///     - size: the size we desire to resize the image to.
    ///
    /// - Returns: the resized image.
    ///
    func imageWithSize(size: CGSize) -> UIImage {

        UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.mainScreen().scale);
        let rect = CGRectMake(0.0, 0.0, size.width, size.height);
        drawInRect(rect)

        let resultingImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        return resultingImage
    }

    /// Resizes an image to the specified size and adds an extra transparent margin at all sides of
    /// the image.
    ///
    /// - Parameters:
    ///     - size: the size we desire to resize the image to.
    ///     - extraMargin: the extra transparent margin to add to all sides of the image.
    ///
    /// - Returns: the resized image.  The extra margin is added to the input image size.  So that
    ///         the final image's size will be equal to:
    ///         `CGSize(width: size.width + extraMargin * 2, height: size.height + extraMargin * 2)`
    ///
    func imageWithSize(size: CGSize, extraMargin: CGFloat) -> UIImage {

        let imageSize = CGSize(width: size.width + extraMargin * 2, height: size.height + extraMargin * 2)

        UIGraphicsBeginImageContextWithOptions(imageSize, false, UIScreen.mainScreen().scale);
        let drawingRect = CGRect(x: extraMargin, y: extraMargin, width: size.width, height: size.height)
        drawInRect(drawingRect)

        let resultingImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        return resultingImage
    }
}

Could not load file or assembly 'System.Data.SQLite'

System.Data.SQLite has a dependency on System.Data.SQLite.interop make sure both packages are the same version and are both x86.

This is an old question, but I tried all the above. I was working on a strictly x86 project, so there was not two folders /x86, /x64. But for some reason, the System.Data.SQLite was a different version to System.Data.SQLite.interop, once I pulled down matching dlls the problem was fixed.

PHP, display image with Header()

Browsers make their best guess with the data they receive. This works for markup (which Websites often get wrong) and other media content. A program that receives a file can often figure out what its received regardless of the MIME content type it's been told.

This isn't something you should rely on however. It's recommended you always use the correct MIME content.

What is LD_LIBRARY_PATH and how to use it?

Well, the error message tells you what to do: add the path where Jacob.dll resides to java.library.path. You can do that on the command line like this:

java -Djava.library.path="dlls" ...

(assuming Jacob.dll is in the "dlls" folder)

Also see java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

Which icon sizes should my Windows application's icon include?

After some testing with an icon with 8, 16, 20, 24, 32, 40, 48, 64, 96, 128 and 256 pixels (256 in PNG) in Windows 7:

  • At 100% resolution: Explorer uses 16, 40, 48, and 256. Windows Photo Viewer uses 96. Paint uses 256.
  • At 125% resolution: Explorer uses 20, 40, and 256. Windows Photo Viewer uses 96. Paint uses 256.
  • At 150% resolution: Explorer uses 24, 48, and 256. Windows Photo Viewer uses 96. Paint uses 256.
  • At 200% resolution: Explorer uses 40, 64, 96, and 256. Windows Photo Viewer uses 128. Paint uses 256.

So 8, 32 were never used (it's strange to me for 32) and 128 only by Windows Photo Viewer with a very high dpi screen, i.e. almot never used.

It means your icon should at least provide 16, 48 and 256 for Windows 7. For supporting newer screens with high resolutions, you should provide 16, 20, 24, 40, 48, 64, 96, and 256. For Windows 7, all pictures can be compressed using PNG but for backward compatibility with Windows XP, 16 to 48 should not be compressed.

http://localhost/ not working on Windows 7. What's the problem?

If you installed it on port 8080, you need to access it on port 8080:

http://localhost:8080 or http://127.0.0.1:8080

HTML embedded PDF iframe

If the browser has a pdf plugin installed it executes the object, if not it uses Google's PDF Viewer to display it as plain HTML:

<object data="your_url_to_pdf" type="application/pdf">
    <iframe src="https://docs.google.com/viewer?url=your_url_to_pdf&embedded=true"></iframe>
</object>

Check Whether a User Exists

There's no need to check the exit code explicitly. Try

if getent passwd $1 > /dev/null 2>&1; then
    echo "yes the user exists"
else
    echo "No, the user does not exist"
fi

If that doesn't work, there is something wrong with your getent, or you have more users defined than you think.

Getting "TypeError: failed to fetch" when the request hasn't actually failed

Note that there is an unrelated issue in your code but that could bite you later: you should return res.json() or you will not catch any error occurring in JSON parsing or your own function processing data.

Back to your error: You cannot have a TypeError: failed to fetch with a successful request. You probably have another request (check your "network" panel to see all of them) that breaks and causes this error to be logged. Also, maybe check "Preserve log" to be sure the panel is not cleared by any indelicate redirection. Sometimes I happen to have a persistent "console" panel, and a cleared "network" panel that leads me to have error in console which is actually unrelated to the visible requests. You should check that.

Or you (but that would be vicious) actually have a hardcoded console.log('TypeError: failed to fetch') in your final .catch ;) and the error is in reality in your .then() but it's hard to believe.

An efficient way to transpose a file in Bash

Assuming all your rows have the same number of fields, this awk program solves the problem:

{for (f=1;f<=NF;f++) col[f] = col[f]":"$f} END {for (f=1;f<=NF;f++) print col[f]}

In words, as you loop over the rows, for every field f grow a ':'-separated string col[f] containing the elements of that field. After you are done with all the rows, print each one of those strings in a separate line. You can then substitute ':' for the separator you want (say, a space) by piping the output through tr ':' ' '.

Example:

$ echo "1 2 3\n4 5 6"
1 2 3
4 5 6

$ echo "1 2 3\n4 5 6" | awk '{for (f=1;f<=NF;f++) col[f] = col[f]":"$f} END {for (f=1;f<=NF;f++) print col[f]}' | tr ':' ' '
 1 4
 2 5
 3 6

Get Cell Value from Excel Sheet with Apache Poi

May be by:-

    for(Row row : sheet) {          
        for(Cell cell : row) {              
            System.out.print(cell.getStringCellValue());

        }
    }       

For specific type of cell you can try:

switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
    cellValue = cell.getStringCellValue();
    break;

case Cell.CELL_TYPE_FORMULA:
    cellValue = cell.getCellFormula();
    break;

case Cell.CELL_TYPE_NUMERIC:
    if (DateUtil.isCellDateFormatted(cell)) {
        cellValue = cell.getDateCellValue().toString();
    } else {
        cellValue = Double.toString(cell.getNumericCellValue());
    }
    break;

case Cell.CELL_TYPE_BLANK:
    cellValue = "";
    break;

case Cell.CELL_TYPE_BOOLEAN:
    cellValue = Boolean.toString(cell.getBooleanCellValue());
    break;

}

How to "fadeOut" & "remove" a div in jQuery?

Try this:

<a onclick='$("#notification").fadeOut(300, function() { $(this).remove(); });' class="notificationClose "><img src="close.png"/></a>

I think your double quotes around the onclick were making it not work. :)

EDIT: As pointed out below, inline javascript is evil and you should probably take this out of the onclick and move it to jQuery's click() event handler. That is how the cool kids are doing it nowadays.

How to read numbers from file in Python?

Not sure why do you need w,h. If these values are actually required and mean that only specified number of rows and cols should be read than you can try the following:

output = []
with open(r'c:\file.txt', 'r') as f:
    w, h  = map(int, f.readline().split())
    tmp = []
    for i, line in enumerate(f):
        if i == h:
            break
        tmp.append(map(int, line.split()[:w]))
    output.append(tmp)

How to get all subsets of a set? (powerset)

Here it is my solutions, it is similar (conceptually) with the solution of lmiguelvargasf.

Let me say that -[math item] by defintion the powerset do contain the empty set -[personal taste] and also that I don't like using frozenset.

So the input is a list and the output will be a list of lists. The function could close earlier, but I like the element of the power set to be order lexicographically, that essentially means nicely.

def power_set(L):
    """
    L is a list.
    The function returns the power set, but as a list of lists.
    """
    cardinality=len(L)
    n=2 ** cardinality
    powerset = []
    
    for i in range(n):
        a=bin(i)[2:]
        subset=[]
        for j in range(len(a)):
            if a[-j-1]=='1':
                subset.append(L[j])
        powerset.append(subset)
        
    #the function could stop here closing with
    #return powerset

    powerset_orderred=[]
    for k in range(cardinality+1):
        for w in powerset:
            if len(w)==k:
                powerset_orderred.append(w)
        
    return powerset_orderred

Set the default value in dropdownlist using jQuery

jQuery("select#cboDays option[value='Wednesday']").attr("selected", "selected");

Creating Roles in Asp.net Identity MVC 5

    public static void createUserRole(string roleName)
    {
        if (!System.Web.Security.Roles.RoleExists(roleName))
        {
            System.Web.Security.Roles.CreateRole(roleName);
        }
    }

filter items in a python dictionary where keys contain a specific string

input = {"A":"a", "B":"b", "C":"c"}
output = {k:v for (k,v) in input.items() if key_satifies_condition(k)}

TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT maximum storage sizes

From the documentation (MySQL 8) :

      Type | Maximum length
-----------+-------------------------------------
  TINYTEXT |           255 (2 8−1) bytes
      TEXT |        65,535 (216−1) bytes = 64 KiB
MEDIUMTEXT |    16,777,215 (224−1) bytes = 16 MiB
  LONGTEXT | 4,294,967,295 (232−1) bytes =  4 GiB

Note that the number of characters that can be stored in your column will depend on the character encoding.

Disable all table constraints in Oracle

This is another way for disabling constraints (it came from https://asktom.oracle.com/pls/asktom/f?p=100:11:2402577774283132::::P11_QUESTION_ID:399218963817)

WITH qry0 AS
       (SELECT    'ALTER TABLE '
               || child_tname
               || ' DISABLE CONSTRAINT '
               || child_cons_name
                 disable_fk
              ,   'ALTER TABLE '
               || parent_tname
               || ' DISABLE CONSTRAINT '
               || parent.parent_cons_name
                 disable_pk
          FROM (SELECT a.table_name child_tname
                      ,a.constraint_name child_cons_name
                      ,b.r_constraint_name parent_cons_name
                      ,LISTAGG ( column_name, ',') WITHIN GROUP (ORDER BY position) child_columns
                  FROM user_cons_columns a
                      ,user_constraints b
                 WHERE a.constraint_name = b.constraint_name AND b.constraint_type = 'R'
                GROUP BY a.table_name, a.constraint_name
                        ,b.r_constraint_name) child
              ,(SELECT a.constraint_name parent_cons_name
                      ,a.table_name parent_tname
                      ,LISTAGG ( column_name, ',') WITHIN GROUP (ORDER BY position) parent_columns
                  FROM user_cons_columns a
                      ,user_constraints b
                 WHERE a.constraint_name = b.constraint_name AND b.constraint_type IN ('P', 'U')
                GROUP BY a.table_name, a.constraint_name) parent
         WHERE child.parent_cons_name = parent.parent_cons_name
           AND (parent.parent_tname LIKE 'V2_%' OR child.child_tname LIKE 'V2_%'))
SELECT DISTINCT disable_pk
  FROM qry0
UNION
SELECT DISTINCT disable_fk
  FROM qry0;

works like a charm

Setting Different Bar color in matplotlib Python

Update pandas 0.17.0

@7stud's answer for the newest pandas version would require to just call

s.plot( 
    kind='bar', 
    color=my_colors,
)

instead of

pd.Series.plot(
    s, 
    kind='bar', 
    color=my_colors,
)

The plotting functions have become members of the Series, DataFrame objects and in fact calling pd.Series.plot with a color argument gives an error

How to avoid Python/Pandas creating an index in a saved csv?

Use index=False.

df.to_csv('your.csv', index=False)

How to compare dates in datetime fields in Postgresql?

Use the range type. If the user enter a date:

select *
from table
where
    update_date
    <@
    tsrange('2013-05-03', '2013-05-03'::date + 1, '[)');

If the user enters timestamps then you don't need the ::date + 1 part

http://www.postgresql.org/docs/9.2/static/rangetypes.html

http://www.postgresql.org/docs/9.2/static/functions-range.html

Sorting object property by values

I made a plugin just for this, it accepts 1 arg which is an unsorted object, and returns an object which has been sorted by prop value. This will work on all 2 dimensional objects such as {"Nick": 28, "Bob": 52}...

var sloppyObj = {
    'C': 78,
    'A': 3,
    'B': 4
};

// Extend object to support sort method
function sortObj(obj) {
    "use strict";

    function Obj2Array(obj) {
        var newObj = [];
        for (var key in obj) {
            if (!obj.hasOwnProperty(key)) return;
            var value = [key, obj[key]];
            newObj.push(value);
        }
        return newObj;
    }

    var sortedArray = Obj2Array(obj).sort(function(a, b) {
        if (a[1] < b[1]) return -1;
        if (a[1] > b[1]) return 1;
        return 0;
    });

    function recreateSortedObject(targ) {
        var sortedObj = {};
        for (var i = 0; i < targ.length; i++) {
            sortedObj[targ[i][0]] = targ[i][1];
        }
        return sortedObj;
    }
    return recreateSortedObject(sortedArray);
}

var sortedObj = sortObj(sloppyObj);

alert(JSON.stringify(sortedObj));

Here is a demo of the function working as expected http://codepen.io/nicholasabrams/pen/RWRqve?editors=001

How to use opencv in using Gradle?

I've imported the Java project from OpenCV SDK into an Android Studio gradle project and made it available at https://github.com/ctodobom/OpenCV-3.1.0-Android

You can include it on your project only adding two lines into build.gradle file thanks to jitpack.io service.

Bootstrap 3 Multi-column within a single ul not floating properly

Thanks, Varun Rathore. It works perfectly!

For those who want graceful collapse from 4 items per row to 2 items per row depending on the screen width:

<ul class="list-group row">
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_1</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_2</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_3</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_4</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_5</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_6</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_7</li>
</ul>

Count indexes using "for" in Python

If you have some given list, and want to iterate over its items and indices, you can use enumerate():

for index, item in enumerate(my_list):
    print index, item

If you only need the indices, you can use range():

for i in range(len(my_list)):
    print i

How many bytes in a JavaScript string?

You can use the Blob to get the string size in bytes.

Examples:

_x000D_
_x000D_
console.info(_x000D_
  new Blob(['']).size,                             // 4_x000D_
  new Blob(['']).size,                             // 4_x000D_
  new Blob(['']).size,                           // 8_x000D_
  new Blob(['']).size,                           // 8_x000D_
  new Blob(['I\'m a string']).size,                  // 12_x000D_
_x000D_
  // from Premasagar correction of Lauri's answer for_x000D_
  // strings containing lone characters in the surrogate pair range:_x000D_
  // https://stackoverflow.com/a/39488643/6225838_x000D_
  new Blob([String.fromCharCode(55555)]).size,       // 3_x000D_
  new Blob([String.fromCharCode(55555, 57000)]).size // 4 (not 6)_x000D_
);
_x000D_
_x000D_
_x000D_

Sockets: Discover port availability using Java

The following solution is inspired by the SocketUtils implementation of Spring-core (Apache license).

Compared to other solutions using Socket(...) it is pretty fast (testing 1000 TCP ports in less than a second):

public static boolean isTcpPortAvailable(int port) {
    try (ServerSocket serverSocket = new ServerSocket()) {
        // setReuseAddress(false) is required only on OSX, 
        // otherwise the code will not work correctly on that platform          
        serverSocket.setReuseAddress(false);
        serverSocket.bind(new InetSocketAddress(InetAddress.getByName("localhost"), port), 1);
        return true;
    } catch (Exception ex) {
        return false;
    }
}       

How can the default node version be set using NVM?

Alert: This answer is for MacOS only

Let suppose you have 2 versions of nodeJS inside your nvm, namely v13.10.1 & v15.4.0

And, v15.4.0 is default

> nvm list
       v13.10.1
->      v15.4.0
         system
default -> 15.4.0 (-> v15.4.0)

And, you want to switch the default to v13.10.1

Follow these steps on your Mac terminal:

  1. Run the command:

    nvm alias default 13.10.1

This will make the default point to v13.10.1 as...

default -> 13.10.1 (-> v13.10.1)
  1. Open new instance of terminal. Now check the node version here as...

node -v

You will get...

v13.10.1
  1. nvm list will also show the new default version.

    nvm list

Just an info: The NodeJS versions taken as example above will have their different npm versions. You can cross-verify it in terminal by running npm -v

What does auto do in margin:0 auto?

It is a broken/very hard to use replacement for the "center" tag. It comes in handy when you need broken tables and non-working centering for blocks and text.

PHP + curl, HTTP POST sample code?

It's can be easily reached with:

<?php

$post = [
    'username' => 'user1',
    'password' => 'passuser1',
    'gender'   => 1,
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.domain.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$response = curl_exec($ch);
var_export($response);

javascript get x and y coordinates on mouse click

It sounds like your printMousePos function should:

  1. Get the X and Y coordinates of the mouse
  2. Add those values to the HTML

Currently, it does this:

  1. Creates (undefined) variables for the X and Y coordinates of the mouse
  2. Attaches a function to the "mousemove" event (which will set those variables to the mouse coordinates when triggered by a mouse move)
  3. Adds the current values of your variables to the HTML

See the problem? Your variables are never getting set, because as soon as you add your function to the "mousemove" event you print them.

It seems like you probably don't need that mousemove event at all; I would try something like this:

function printMousePos(e) {
    var cursorX = e.pageX;
    var cursorY = e.pageY;
    document.getElementById('test').innerHTML = "x: " + cursorX + ", y: " + cursorY;
}

Scrolling an iframe with JavaScript?

Or, you can set a margin-top on the iframe...a bit of a hack but works in FF so far.

#frame {
margin-top:200px;
}

Gradle - Could not find or load main class

I just ran into this problem and decided to debug it myself since i couldn't find a solution on the internet. All i did is change the mainClassName to it's whole path(with the correct subdirectories in the project ofc)

    mainClassName = 'main.java.hello.HelloWorld'

I know it's been almost one year since the post has been made, but i think someone will find this information useful.

Happy coding.

Watch multiple $scope attributes

Angular introduced $watchGroup in version 1.3 using which we can watch multiple variables, with a single $watchGroup block $watchGroup takes array as first parameter in which we can include all of our variables to watch.

$scope.$watchGroup(['var1','var2'],function(newVals,oldVals){
   console.log("new value of var1 = " newVals[0]);
   console.log("new value of var2 = " newVals[1]);
   console.log("old value of var1 = " oldVals[0]);
   console.log("old value of var2 = " oldVals[1]);
});

Send PHP variable to javascript function

You can do the following:

<script type='text/javascript'>
    document.body.onclick(function(){
        var myVariable = <?php echo(json_encode($myVariable)); ?>;
    };
</script>

How to disable Excel's automatic cell reference change after copy/paste?

Try this: Left-click the tab, making a copy of the whole sheet, then cut the cells you want to keep the same and paste them into your original worksheet.

Using variables in Nginx location rules

A modified python version of @danack's PHP generate script. It generates all files & folders that live inside of build/ to the parent directory, replacing all {{placeholder}} matches. You need to cd into build/ before running the script.

File structure

build/
-- (files/folders you want to generate)
-- build.py

sites-available/...
sites-enabled/...
nginx.conf
...

build.py

import os, re

# Configurations
target = os.path.join('.', '..')
variables = {
  'placeholder': 'your replacement here'
}


# Loop files
def loop(cb, subdir=''):
  dir = os.path.join('.', subdir);

  for name in os.listdir(dir):
    file = os.path.join(dir, name)
    newsubdir = os.path.join(subdir, name)

    if name == 'build.py': continue
    if os.path.isdir(file): loop(cb, newsubdir)
    else: cb(subdir, name)


# Update file
def replacer(subdir, name):
  dir  = os.path.join(target, subdir)
  file = os.path.join(dir, name)
  oldfile = os.path.join('.', subdir, name)

  with open(oldfile, "r") as fin:
    data = fin.read()

  for key, replacement in variables.iteritems():
    data = re.sub(r"{{\s*" + key + "\s*}}", replacement, data)

  if not os.path.exists(dir):
    os.makedirs(dir)

  with open(file, "w") as fout:
    fout.write(data)


# Start variable replacements.
loop(replacer)

Adding ASP.NET MVC5 Identity Authentication to an existing project

This is what I did to integrate Identity with an existing database.

  1. Create a sample MVC project with MVC template. This has all the code needed for Identity implementation - Startup.Auth.cs, IdentityConfig.cs, Account Controller code, Manage Controller, Models and related views.

  2. Install the necessary nuget packages for Identity and OWIN. You will get an idea by seeing the references in the sample Project and the answer by @Sam

  3. Copy all these code to your existing project. Please note don't forget to add the "DefaultConnection" connection string for Identity to map to your database. Please check the ApplicationDBContext class in IdentityModel.cs where you will find the reference to "DefaultConnection" connection string.

  4. This is the SQL script I ran on my existing database to create necessary tables:

    USE ["YourDatabse"]
    GO
    /****** Object:  Table [dbo].[AspNetRoles]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetRoles](
    [Id] [nvarchar](128) NOT NULL,
    [Name] [nvarchar](256) NOT NULL,
    CONSTRAINT [PK_dbo.AspNetRoles] PRIMARY KEY CLUSTERED 
    (
      [Id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO
    /****** Object:  Table [dbo].[AspNetUserClaims]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetUserClaims](
       [Id] [int] IDENTITY(1,1) NOT NULL,
       [UserId] [nvarchar](128) NOT NULL,
       [ClaimType] [nvarchar](max) NULL,
       [ClaimValue] [nvarchar](max) NULL,
    CONSTRAINT [PK_dbo.AspNetUserClaims] PRIMARY KEY CLUSTERED 
    (
       [Id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
    
    GO
    /****** Object:  Table [dbo].[AspNetUserLogins]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetUserLogins](
        [LoginProvider] [nvarchar](128) NOT NULL,
        [ProviderKey] [nvarchar](128) NOT NULL,
        [UserId] [nvarchar](128) NOT NULL,
    CONSTRAINT [PK_dbo.AspNetUserLogins] PRIMARY KEY CLUSTERED 
    (
        [LoginProvider] ASC,
        [ProviderKey] ASC,
        [UserId] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO
    /****** Object:  Table [dbo].[AspNetUserRoles]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetUserRoles](
       [UserId] [nvarchar](128) NOT NULL,
       [RoleId] [nvarchar](128) NOT NULL,
    CONSTRAINT [PK_dbo.AspNetUserRoles] PRIMARY KEY CLUSTERED 
    (
        [UserId] ASC,
        [RoleId] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO
    /****** Object:  Table [dbo].[AspNetUsers]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetUsers](
        [Id] [nvarchar](128) NOT NULL,
        [Email] [nvarchar](256) NULL,
        [EmailConfirmed] [bit] NOT NULL,
        [PasswordHash] [nvarchar](max) NULL,
        [SecurityStamp] [nvarchar](max) NULL,
        [PhoneNumber] [nvarchar](max) NULL,
        [PhoneNumberConfirmed] [bit] NOT NULL,
        [TwoFactorEnabled] [bit] NOT NULL,
        [LockoutEndDateUtc] [datetime] NULL,
        [LockoutEnabled] [bit] NOT NULL,
        [AccessFailedCount] [int] NOT NULL,
        [UserName] [nvarchar](256) NOT NULL,
    CONSTRAINT [PK_dbo.AspNetUsers] PRIMARY KEY CLUSTERED 
    (
        [Id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
    
     GO
     ALTER TABLE [dbo].[AspNetUserClaims]  WITH CHECK ADD  CONSTRAINT [FK_dbo.AspNetUserClaims_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
     REFERENCES [dbo].[AspNetUsers] ([Id])
     ON DELETE CASCADE
     GO
     ALTER TABLE [dbo].[AspNetUserClaims] CHECK CONSTRAINT [FK_dbo.AspNetUserClaims_dbo.AspNetUsers_UserId]
     GO
     ALTER TABLE [dbo].[AspNetUserLogins]  WITH CHECK ADD  CONSTRAINT [FK_dbo.AspNetUserLogins_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
     REFERENCES [dbo].[AspNetUsers] ([Id])
     ON DELETE CASCADE
     GO
     ALTER TABLE [dbo].[AspNetUserLogins] CHECK CONSTRAINT [FK_dbo.AspNetUserLogins_dbo.AspNetUsers_UserId]
     GO
     ALTER TABLE [dbo].[AspNetUserRoles]  WITH CHECK ADD  CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetRoles_RoleId] FOREIGN KEY([RoleId])
     REFERENCES [dbo].[AspNetRoles] ([Id])
     ON DELETE CASCADE
     GO
     ALTER TABLE [dbo].[AspNetUserRoles] CHECK CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetRoles_RoleId]
     GO
     ALTER TABLE [dbo].[AspNetUserRoles]  WITH CHECK ADD  CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
     REFERENCES [dbo].[AspNetUsers] ([Id])
     ON DELETE CASCADE
     GO
     ALTER TABLE [dbo].[AspNetUserRoles] CHECK CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetUsers_UserId]
     GO
    
  5. Check and solve any remaining errors and you are done. Identity will handle the rest :)

How can I format bytes a cell in Excel as KB, MB, GB etc?

Slight change to make it work on my region, Europe (. as thousands separator, comma as decimal separator):

[<1000000]#.##0,00" KB";[<1000000000]#.##0,00.." MB";#.##0,00..." GB"

Still same issue on data conversion (1000 != 1024) but it does the job for me.

Get filename and path from URI from mediastore

This works for me perfectly if your system version is above 19, Hope this can help you.

  @TargetApi(Build.VERSION_CODES.KITKAT)
    public static String getPath(final Context context, final Uri uri) {
        final boolean isOverKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        // DocumentProvider
        if (isOverKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/"
                            + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection,
                        selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

What's the best way to cancel event propagation between nested ng-click calls?

Sometimes, it may make most sense just to do this:

<widget ng-click="myClickHandler(); $event.stopPropagation()"/>

I chose to do it this way because I didn't want myClickHandler() to stop the event propagation in the many other places it was used.

Sure, I could've added a boolean parameter to the handler function, but stopPropagation() is much more meaningful than just true.

What does Visual Studio mean by normalize inconsistent line endings?

Some lines end with \n.

Some other lines end with \r\n.

Visual Studio suggests you to make all lines end the same.

How to auto-reload files in Node.js?

Use this:

function reload_config(file) {
  if (!(this instanceof reload_config))
    return new reload_config(file);
  var self = this;

  self.path = path.resolve(file);

  fs.watchFile(file, function(curr, prev) {
    delete require.cache[self.path];
    _.extend(self, require(file));
  });

  _.extend(self, require(file));
}

All you have to do now is:

var config = reload_config("./config");

And config will automatically get reloaded :)

Error in plot.window(...) : need finite 'xlim' values

This error appears when the column contains character, if you check the data type it would be of type 'chr' converting the column to 'Factor' would solve this issue.

For e.g. In case you plot 'City' against 'Sales', you have to convert column 'City' to type 'Factor'

How to decode jwt token in javascript without using a library?

I use this function to get payload , header , exp(Expiration Time), iat (Issued At) based on this answer

function parseJwt(token) {
  try {
    // Get Token Header
    const base64HeaderUrl = token.split('.')[0];
    const base64Header = base64HeaderUrl.replace('-', '+').replace('_', '/');
    const headerData = JSON.parse(window.atob(base64Header));

    // Get Token payload and date's
    const base64Url = token.split('.')[1];
    const base64 = base64Url.replace('-', '+').replace('_', '/');
    const dataJWT = JSON.parse(window.atob(base64));
    dataJWT.header = headerData;

// TODO: add expiration at check ...


    return dataJWT;
  } catch (err) {
    return false;
  }
}

const jwtDecoded = parseJwt('YOUR_TOKEN') ;
if(jwtDecoded)
{
    console.log(jwtDecoded)
}

Pygame mouse clicking detection

The pygame documentation for mouse events is here. You can either use the pygame.mouse.get_pressed method in collaboration with the pygame.mouse.get_pos (if needed). But please use the mouse click event via a main event loop. The reason why the event loop is better is due to "short clicks". You may not notice these on normal machines, but computers that use tap-clicks on trackpads have excessively small click periods. Using the mouse events will prevent this.

EDIT: To perform pixel perfect collisions use pygame.sprite.collide_rect() found on their docs for sprites.

Getting attributes of Enum's value

And if you want the full list of names you can do something like

typeof (PharmacyConfigurationKeys).GetFields()
        .Where(x => x.GetCustomAttributes(false).Any(y => typeof(DescriptionAttribute) == y.GetType()))
        .Select(x => ((DescriptionAttribute)x.GetCustomAttributes(false)[0]).Description);

What's a .sh file?

If you open your second link in a browser you'll see the source code:

#!/bin/bash
# Script to download individual .nc files from the ORNL
# Daymet server at: http://daymet.ornl.gov

[...]

# For ranges use {start..end}
# for individul vaules, use: 1 2 3 4 
for year in {2002..2003}
do
   for tile in {1159..1160}
        do wget --limit-rate=3m http://daymet.ornl.gov/thredds/fileServer/allcf/${year}/${tile}_${year}/vp.nc -O ${tile}_${year}_vp.nc
        # An example using curl instead of wget
    #do curl --limit-rate 3M -o ${tile}_${year}_vp.nc http://daymet.ornl.gov/thredds/fileServer/allcf/${year}/${tile}_${year}/vp.nc
     done
done

So it's a bash script. Got Linux?


In any case, the script is nothing but a series of HTTP retrievals. Both wget and curl are available for most operating systems and almost all language have HTTP libraries so it's fairly trivial to rewrite in any other technology. There're also some Windows ports of bash itself (git includes one). Last but not least, Windows 10 now has native support for Linux binaries.

use current date as default value for a column

CREATE TABLE Orders(
    O_Id int NOT NULL,
    OrderNo int NOT NULL,
    P_Id int,
    OrderDate date DEFAULT GETDATE() // you can set default constraints while creating the table
)

Karma: Running a single test file from command line

First you need to start karma server with

karma start

Then, you can use grep to filter a specific test or describe block:

karma run -- --grep=testDescriptionFilter

How to highlight a selected row in ngRepeat?

Each row has an ID. All you have to do is to send this ID to the function setSelected(), store it (in $scope.idSelectedVote for instance), and then check for each row if the selected ID is the same as the current one. Here is a solution (see the documentation for ngClass, if needed):

$scope.idSelectedVote = null;
$scope.setSelected = function (idSelectedVote) {
   $scope.idSelectedVote = idSelectedVote;
};
<ul ng-repeat="vote in votes" ng-click="setSelected(vote.id)" ng-class="{selected: vote.id === idSelectedVote}">
    ...
</ul>

Plunker

python: create list of tuples from lists

You're looking for the zip builtin function. From the docs:

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]

Use child_process.execSync but keep output in console

Simply:

 try {
    const cmd = 'git rev-parse --is-inside-work-tree';
    execSync(cmd).toString();
 } catch (error) {
    console.log(`Status Code: ${error.status} with '${error.message}'`;
 }

Ref: https://stackoverflow.com/a/43077917/104085

// nodejs
var execSync = require('child_process').execSync;

// typescript
const { execSync } = require("child_process");

 try {
    const cmd = 'git rev-parse --is-inside-work-tree';
    execSync(cmd).toString();
 } catch (error) {
    error.status;  // 0 : successful exit, but here in exception it has to be greater than 0
    error.message; // Holds the message you typically want.
    error.stderr;  // Holds the stderr output. Use `.toString()`.
    error.stdout;  // Holds the stdout output. Use `.toString()`.
 }

enter image description here

enter image description here

When command runs successful: enter image description here

Android, landscape only orientation?

One thing I've not found through the answers is that there are two possible landscape orientations, and I wanted to let both be available! So android:screenOrientation="landscape" will lock your app only to one of the 2 possibilities, but if you want your app to be limited to both landscape orientations (for them whom is not clear, having device on portrait, one is rotating left and the other one rotating right) this is what is needed:

android:screenOrientation="sensorLandscape"

sql primary key and index

Here the passage from the MSDN:

When you specify a PRIMARY KEY constraint for a table, the Database Engine enforces data uniqueness by creating a unique index for the primary key columns. This index also permits fast access to data when the primary key is used in queries. Therefore, the primary keys that are chosen must follow the rules for creating unique indexes.

Intercept page exit event

Instead of an annoying confirmation popup, it would be nice to delay leaving just a bit (matter of milliseconds) to manage successfully posting the unsaved data to the server, which I managed for my site using writing dummy text to the console like this:

window.onbeforeunload=function(e){
  // only take action (iterate) if my SCHEDULED_REQUEST object contains data        
  for (var key in SCHEDULED_REQUEST){   
    postRequest(SCHEDULED_REQUEST); // post and empty SCHEDULED_REQUEST object
    for (var i=0;i<1000;i++){
      // do something unnoticable but time consuming like writing a lot to console
      console.log('buying some time to finish saving data'); 
    };
    break;
  };
}; // no return string --> user will leave as normal but data is send to server

Edit: See also Synchronous_AJAX and how to do that with jquery

How to get domain URL and application name?

The application name come from getContextPath.

I find this graphic from Agile Software Craftsmanship HttpServletRequest Path Decoding sorts out all the different methods that are available:

enter image description here

Threading pool similar to the multiprocessing Pool?

Yes, and it seems to have (more or less) the same API.

import multiprocessing

def worker(lnk):
    ....    
def start_process():
    .....
....

if(PROCESS):
    pool = multiprocessing.Pool(processes=POOL_SIZE, initializer=start_process)
else:
    pool = multiprocessing.pool.ThreadPool(processes=POOL_SIZE, 
                                           initializer=start_process)

pool.map(worker, inputs)
....

NVIDIA NVML Driver/library version mismatch

sudo reboot

Rebooting solved it for me.

.NET Events - What are object sender & EventArgs e?

Manually cast the sender to the type of your custom control, and then use it to delete or disable etc. Eg, something like this:

private void myCustomControl_Click(object sender, EventArgs e)
{
  ((MyCustomControl)sender).DoWhatever();
}

The 'sender' is just the object that was actioned (eg clicked).

The event args is subclassed for more complex controls, eg a treeview, so that you can know more details about the event, eg exactly where they clicked.

Making interface implementations async

An abstract class can be used instead of an interface (in C# 7.3).

// Like interface
abstract class IIO
{
    public virtual async Task<string> DoOperation(string Name)
    {
        throw new NotImplementedException(); // throwing exception
        // return await Task.Run(() => { return ""; }); // or empty do
    }
}

// Implementation
class IOImplementation : IIO
{
    public override async Task<string> DoOperation(string Name)
    {
        return await await Task.Run(() =>
        {
            if(Name == "Spiderman")
                return "ok";
            return "cancel";
        }); 
    }
}

jquery AJAX and json format

Currently you are sending the data as typical POST values, which look like this:

first_name=somename&last_name=somesurname

If you want to send data as json you need to create an object with data and stringify it.

data: JSON.stringify(someobject)

How to test Spring Data repositories?

With Spring Boot + Spring Data it has become quite easy:

@RunWith(SpringRunner.class)
@DataJpaTest
public class MyRepositoryTest {

    @Autowired
    MyRepository subject;

    @Test
    public void myTest() throws Exception {
        subject.save(new MyEntity());
    }
}

The solution by @heez brings up the full context, this only bring up what is needed for JPA+Transaction to work. Note that the solution above will bring up a in memory test database given that one can be found on the classpath.

jquery $(window).width() and $(window).height() return different values when viewport has not been resized

Try to use a

  • $(window).load event

or

  • $(document).ready

    because the initial values may be inconstant because of changes that occur during the parsing or during the DOM load.

How to extract the file name from URI returned from Intent.ACTION_GET_CONTENT?

For Kotlin, You can use something like this :

object FileUtils {

   fun Context.getFileName(uri: Uri): String?
        = when (uri.scheme) {
            ContentResolver.SCHEME_FILE -> File(uri.path).name
            ContentResolver.SCHEME_CONTENT -> getCursorContent(uri)
            else -> null
        }

    private fun Context.getCursorContent(uri: Uri): String? 
        = try {
            contentResolver.query(uri, null, null, null, null)?.let { cursor ->
                cursor.run {
                    if (moveToFirst()) getString(getColumnIndex(OpenableColumns.DISPLAY_NAME))
                    else null
                }.also { cursor.close() }
            }
        } catch (e : Exception) { null }

CodeIgniter 404 Page Not Found, but why?

In my case I was using it on localhost and forgot to change RewriteBase in .htaccess.

How to redirect to the same page in PHP

Simple line below works just fine:

header("Location: ?");

Install an apk file from command prompt?

Commands for install APK files like it does in Android Studio you can see below.

1) To push your app:

adb push /pathOfApk/com.my.awesome.apk /data/local/tmp/com.my.awesome

where com.my.awesome is your package.

2) To install:

adb shell pm install -t -r "/data/local/tmp/com.my.awesome"

Batch file for PuTTY/PSFTP file transfer automation

set DSKTOPDIR="D:\test"
set IPADDRESS="23.23.3.23"

>%DSKTOPDIR%\script.ftp ECHO cd %PAY_REP%
>>%DSKTOPDIR%\script.ftp ECHO mget *.report
>>%DSKTOPDIR%\script.ftp ECHO bye

:: run PSFTP Commands
psftp <domain>@%IPADDRESS% -b %DSKTOPDIR%\script.ftp

Set values using set commands before above lines.

I believe this helps you.

Referre psfpt setup for below link https://www.ssh.com/ssh/putty/putty-manuals/0.68/Chapter6.html

How to break line in JavaScript?

Add %0D%0A to any place you want to encode a line break on the URL.

  • %0D is a carriage return character
  • %0A is a line break character

This is the new line sequence on windows machines, though not the same on linux and macs, should work in both.

If you want a linebreak in actual javascript, use the \n escape sequence.


onClick="parent.location='mailto:[email protected]?subject=Thanks for writing to me &body=I will get back to you soon.%0D%0AThanks and Regards%0D%0ASaurav Kumar'

Differences between Emacs and Vim

Firstly Vi (original realization) not used today. That you say is some Vim derivation.

To extend Vim functionality you must recompile Vim, Emacs not.

Emacs has Vim in self (viper-mode).

Emacs usually need manually installation, Vim typically preinstalled on all Unix like OS (but if you have ssh access to host tramp-mode win Vim :).

If you try Vim you hate Emacs, so start from Emacs first.

Also read http://www.dina.dk/~abraham/religion/vi-tutorial.html (link go down so use this)

Anwer search in hxxp://en.wikipedia.org/wiki/Editor_war

Proper MIME type for .woff2 fonts

In IIS you can declare the mime type for WOFF2 font files by adding the following to your project's web.config:

<system.webServer>
  <staticContent>
    <remove fileExtension=".woff2" />
    <mimeMap fileExtension=".woff2" mimeType="font/woff2" />
  </staticContent>
</system.webServer>

Update: The mime type may be changing according to the latest W3C Editor's Draft WOFF2 spec. See Appendix A: Internet Media Type Registration section 6.5. WOFF 2.0 which states the latest proposed format is font/woff2

How do I get the last four characters from a string in C#?

Ok, so I see this is an old post, but why are we rewriting code that is already provided in the framework?

I would suggest that you add a reference to the framework DLL "Microsoft.VisualBasic"

using Microsoft.VisualBasic;
//...

string value = Strings.Right("34234234d124", 4);

how to add value to a tuple?

    list_of_tuples = [('1', '2', '3', '4'),
                      ('2', '3', '4', '5'),
                      ('3', '4', '5', '6'),
                      ('4', '5', '6', '7')]


    def mod_tuples(list_of_tuples):
        for i in range(0, len(list_of_tuples)):
            addition = ''
            for x in list_of_tuples[i]:
                addition = addition + x
            list_of_tuples[i] = list_of_tuples[i] + (addition,)
        return list_of_tuples

    # check: 
    print mod_tuples(list_of_tuples)

Best ways to teach a beginner to program?

I think Python is a great idea. I would give him a few basic assignments to do on his own and tell him that any dead ends he hits can probably be resolved by a trip to google. For me, at least, solving a problem on my own always made it stick better than someone telling me the solution.

Some possible projects (in no particular order):

  • Coin flip simulator. Let the user input a desired number of trials for the coin flipping. Execute it and display the results along with the percentage for heads or tails.

  • Make a temperature converter with a menu that takes user input to choose which kind of conversion the user wants to do. After choosing the conversion and doing it, it should return to the main menu.

    Here's an example of an extended converter with the same idea: http://pastebin.org/6541

  • Make a program that takes a numeric input and displays the letter grade it would translate to. It'll end up evaluating the input against if and elif statements to find where it fits.

  • Make a simple quiz that goes through several multiple choice or fill in the blank questions. At the end it will display how the user did. He can pick any questions he wants.

  • Take an input of some (presumably large) number of pennies and convert it into bigger denominations. For example, 149 pennies = 1 dollar, 1 quarter, 2 dimes, and 4 pennies.

  • Create a simple list manager. Be able to add/delete lists and add/delete entries in those lists. Here's an example of a christmas list manager: http://pastebin.org/6543

  • Create a program that will build and then test whether entered numbers form a magic square (with a 2D array). Here's some sample code, but it should really print out the square at each step in order to show where the user is in terms of buliding the square: http://pastebin.org/6544

I would also suggest doing some stuff with xTurtle or another graphics module to mix things up and keep him from getting boring. Of course, this is very much practice programming and not the scripting that a lot of people would really be using python for, but the examples I gave are pretty much directly taken from when I was learning via python and it worked out great for me. Good luck!

What's the difference between an element and a node in XML?

As described in the various XML specifications, an element is that which consists of a start tag, and end tag, and the content in between, or alternately an empty element tag (which has no content or end tag). In other words, these are all elements:

<foo> stuff </foo>
<foo bar="baz"></foo>
<foo baz="qux" />

Though you hear "node" used with roughly the same meaning, it has no precise definition per XML specs. It's usually used to refer to nodes of things like DOMs, which may be closely related to XML or use XML for their representation.

Vertically align text within input field of fixed-height without display: table or padding?

In my opinion, the answer on this page with the most votes is the best answer, but his math was wrong and I couldn't comment on it.

I needed a text input box to be exactly 40 pixels high including a 1 pixel border all the way around. Of course I wanted the text vertically aligned in the center in all browsers.

1 pixel border top
1 pixel border bottom
8 pixel top padding
8 pixel bottom padding
22 pixel font size

1 + 1 + 8 + 8 + 22 = 40 pixels exactly.

One thing to remember is that you must remove your css height property or those pixels will get added to your total above.

<input type="text" style="padding-top:8px; padding-bottom:8px; margin: 0; border: solid 1px #000000; font-size:22px;" />

This is working in Firefox, Chrome, IE 8, and Safari. I can only assume that if something simple like this is working in IE8, it should work similarly in 6, 7, and 9 but I have not tested it. Please let me know and I'll edit this post accordingly.

Android java.lang.NoClassDefFoundError

Imaage

Go to Order and export from project properties and make sure you're including the required jars in the export, this did it for me

How to get WooCommerce order details

ONLY FOR WOOCOMMERCE VERSIONS 2.5.x AND 2.6.x

For WOOCOMMERCE VERSION 3.0+ see THIS UPDATE

Here is a custom function I have made, to make the things clear for you, related to get the data of an order ID. You will see all the different RAW outputs you can get and how to get the data you need…

Using print_r() function (or var_dump() function too) allow to output the raw data of an object or an array.

So first I output this data to show the object or the array hierarchy. Then I use different syntax depending on the type of that variable (string, array or object) to output the specific data needed.

IMPORTANT: With $order object you can use most of WC_order or WC_Abstract_Order methods (using the object syntax)…


Here is the code:

function get_order_details($order_id){

    // 1) Get the Order object
    $order = wc_get_order( $order_id );

    // OUTPUT
    echo '<h3>RAW OUTPUT OF THE ORDER OBJECT: </h3>';
    print_r($order);
    echo '<br><br>';
    echo '<h3>THE ORDER OBJECT (Using the object syntax notation):</h3>';
    echo '$order->order_type: ' . $order->order_type . '<br>';
    echo '$order->id: ' . $order->id . '<br>';
    echo '<h4>THE POST OBJECT:</h4>';
    echo '$order->post->ID: ' . $order->post->ID . '<br>';
    echo '$order->post->post_author: ' . $order->post->post_author . '<br>';
    echo '$order->post->post_date: ' . $order->post->post_date . '<br>';
    echo '$order->post->post_date_gmt: ' . $order->post->post_date_gmt . '<br>';
    echo '$order->post->post_content: ' . $order->post->post_content . '<br>';
    echo '$order->post->post_title: ' . $order->post->post_title . '<br>';
    echo '$order->post->post_excerpt: ' . $order->post->post_excerpt . '<br>';
    echo '$order->post->post_status: ' . $order->post->post_status . '<br>';
    echo '$order->post->comment_status: ' . $order->post->comment_status . '<br>';
    echo '$order->post->ping_status: ' . $order->post->ping_status . '<br>';
    echo '$order->post->post_password: ' . $order->post->post_password . '<br>';
    echo '$order->post->post_name: ' . $order->post->post_name . '<br>';
    echo '$order->post->to_ping: ' . $order->post->to_ping . '<br>';
    echo '$order->post->pinged: ' . $order->post->pinged . '<br>';
    echo '$order->post->post_modified: ' . $order->post->post_modified . '<br>';
    echo '$order->post->post_modified_gtm: ' . $order->post->post_modified_gtm . '<br>';
    echo '$order->post->post_content_filtered: ' . $order->post->post_content_filtered . '<br>';
    echo '$order->post->post_parent: ' . $order->post->post_parent . '<br>';
    echo '$order->post->guid: ' . $order->post->guid . '<br>';
    echo '$order->post->menu_order: ' . $order->post->menu_order . '<br>';
    echo '$order->post->post_type: ' . $order->post->post_type . '<br>';
    echo '$order->post->post_mime_type: ' . $order->post->post_mime_type . '<br>';
    echo '$order->post->comment_count: ' . $order->post->comment_count . '<br>';
    echo '$order->post->filter: ' . $order->post->filter . '<br>';
    echo '<h4>THE ORDER OBJECT (again):</h4>';
    echo '$order->order_date: ' . $order->order_date . '<br>';
    echo '$order->modified_date: ' . $order->modified_date . '<br>';
    echo '$order->customer_message: ' . $order->customer_message . '<br>';
    echo '$order->customer_note: ' . $order->customer_note . '<br>';
    echo '$order->post_status: ' . $order->post_status . '<br>';
    echo '$order->prices_include_tax: ' . $order->prices_include_tax . '<br>';
    echo '$order->tax_display_cart: ' . $order->tax_display_cart . '<br>';
    echo '$order->display_totals_ex_tax: ' . $order->display_totals_ex_tax . '<br>';
    echo '$order->display_cart_ex_tax: ' . $order->display_cart_ex_tax . '<br>';
    echo '$order->formatted_billing_address->protected: ' . $order->formatted_billing_address->protected . '<br>';
    echo '$order->formatted_shipping_address->protected: ' . $order->formatted_shipping_address->protected . '<br><br>';
    echo '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <br><br>';

    // 2) Get the Order meta data
    $order_meta = get_post_meta($order_id);

    echo '<h3>RAW OUTPUT OF THE ORDER META DATA (ARRAY): </h3>';
    print_r($order_meta);
    echo '<br><br>';
    echo '<h3>THE ORDER META DATA (Using the array syntax notation):</h3>';
    echo '$order_meta[_order_key][0]: ' . $order_meta[_order_key][0] . '<br>';
    echo '$order_meta[_order_currency][0]: ' . $order_meta[_order_currency][0] . '<br>';
    echo '$order_meta[_prices_include_tax][0]: ' . $order_meta[_prices_include_tax][0] . '<br>';
    echo '$order_meta[_customer_user][0]: ' . $order_meta[_customer_user][0] . '<br>';
    echo '$order_meta[_billing_first_name][0]: ' . $order_meta[_billing_first_name][0] . '<br><br>';
    echo 'And so on ……… <br><br>';
    echo '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <br><br>';

    // 3) Get the order items
    $items = $order->get_items();

    echo '<h3>RAW OUTPUT OF THE ORDER ITEMS DATA (ARRAY): </h3>';

    foreach ( $items as $item_id => $item_data ) {

        echo '<h4>RAW OUTPUT OF THE ORDER ITEM NUMBER: '. $item_id .'): </h4>';
        print_r($item_data);
        echo '<br><br>';
        echo 'Item ID: ' . $item_id. '<br>';
        echo '$item_data["product_id"] <i>(product ID)</i>: ' . $item_data['product_id'] . '<br>';
        echo '$item_data["name"] <i>(product Name)</i>: ' . $item_data['name'] . '<br>';

        // Using get_item_meta() method
        echo 'Item quantity <i>(product quantity)</i>: ' . $order->get_item_meta($item_id, '_qty', true) . '<br><br>';
        echo 'Item line total <i>(product quantity)</i>: ' . $order->get_item_meta($item_id, '_line_total', true) . '<br><br>';
        echo 'And so on ……… <br><br>';
        echo '- - - - - - - - - - - - - <br><br>';
    }
    echo '- - - - - - E N D - - - - - <br><br>';
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Usage (if your order ID is 159 for example):

get_order_details(159);

This code is tested and works.

Updated code on November 21, 2016

How to terminate process from Python using pid?

So, not directly related but this is the first question that appears when you try to find how to terminate a process running from a specific folder using Python.

It also answers the question in a way(even though it is an old one with lots of answers).

While creating a faster way to scrape some government sites for data I had an issue where if any of the processes in the pool got stuck they would be skipped but still take up memory from my computer. This is the solution I reached for killing them, if anyone knows a better way to do it please let me know!

import pandas as pd
import wmi
from re import escape
import os

def kill_process(kill_path, execs):
    f = wmi.WMI()
    esc = escape(kill_path)
    temp = {'id':[], 'path':[], 'name':[]}
    for process in f.Win32_Process():
        temp['id'].append(process.ProcessId)
        temp['path'].append(process.ExecutablePath)
        temp['name'].append(process.Name)
    temp = pd.DataFrame(temp)
    temp = temp.dropna(subset=['path']).reset_index().drop(columns=['index'])
    temp = temp.loc[temp['path'].str.contains(esc)].loc[temp.name.isin(execs)].reset_index().drop(columns=['index'])
    [os.system('taskkill /PID {} /f'.format(t)) for t in temp['id']]

How to present a simple alert message in java?

Even without importing swing, you can get the call in one, all be it long, string. Otherwise just use the swing import and simple call:

JOptionPane.showMessageDialog(null, "Thank you for using Java", "Yay, java", JOptionPane.PLAIN_MESSAGE);

Easy enough.

HttpClient - A task was cancelled?

Another possibility is that the result is not awaited on the client side. This can happen if any one method on the call stack does not use the await keyword to wait for the call to be completed.

How to copy a file to a remote server in Python using SCP or SSH?

fabric could be used to upload files vis ssh:

#!/usr/bin/env python
from fabric.api import execute, put
from fabric.network import disconnect_all

if __name__=="__main__":
    import sys
    # specify hostname to connect to and the remote/local paths
    srcdir, remote_dirname, hostname = sys.argv[1:]
    try:
        s = execute(put, srcdir, remote_dirname, host=hostname)
        print(repr(s))
    finally:
        disconnect_all()

How to create a multi line body in C# System.Net.Mail.MailMessage

I realise this may have been answered before. However, i had this issue this morning with Environment.Newline not being preserved in the email body. The following is a full (Now Working with Environment.NewLine being preserved) method i use for sending an email through my program.(The Modules.MessageUpdate portion can be skipped as this just writes to a log file i have.) This is located on the main page of my WinForms program.

    private void MasterMail(string MailContents)
    {
        Modules.MessageUpdate(this, ObjApp, EH, 3, 25, "", "", "", 0, 0, 0, 0, "Master Email - MasterMail Called.", "N", MainTxtDict, MessageResourcesTxtDict);

        Outlook.Application OApp = new Outlook.Application();
        //Location of email template to use. Outlook wont include my Signature through this automation so template contains only that.
        string Temp = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + ResourceDetails.DictionaryResources("SigTempEmail", MainTxtDict);

        Outlook.Folder folder = OApp.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderDrafts) as Outlook.Folder;

        //create the email object.
        Outlook.MailItem TestEmail = OApp.CreateItemFromTemplate(Temp, folder) as Outlook.MailItem;

        //Set subject line.
        TestEmail.Subject = "Automation Results";

        //Create Recipients object.
        Outlook.Recipients oRecips = (Outlook.Recipients)TestEmail.Recipients;

        //Set and check email addresses to send to.
        Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add("EmailAddressToSendTo");
        oRecip.Resolve();

        //Set the body of the email. (.HTMLBody for HTML Emails. .Body will preserve "Environment.NewLine")
        TestEmail.Body = MailContents + TestEmail.Body;
        try
        {
            //If outlook is not open, Open it.
            Process[] pName = Process.GetProcessesByName("OUTLOOK.EXE");
            if (pName.Length == 0)
            {
                System.Diagnostics.Process.Start(@"C:\Program Files\Microsoft Office\root\Office16\OUTLOOK.EXE");
            }

            //Send email
            TestEmail.Send();

            //Update logfile - Success.
            Modules.MessageUpdate(this, ObjApp, EH, 1, 17, "", "", "", 0, 0, 0, 0, "Master Email sent.", "Y", MainTxtDict, MessageResourcesTxtDict);
        }
        catch (Exception E)
        {
            //Update LogFile - Fail.
            Modules.MessageUpdate(this, ObjApp, EH, 5, 4, "", "", "", 0, 0, 0, 0, "Master Email - Error Occurred. System says: " + E.Message, "Y", MainTxtDict, MessageResourcesTxtDict);
        }
        finally
        {
            if (OApp != null)
            {
                OApp = null;
            }
            if (folder != null)
            {
                folder = null;
            }
            if (TestEmail != null)
            {
                TestEmail = null;
            }
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
    }

You can add multiple recipients by either including a "; " between email addresses manually, or in one of my other methods i populate from a Txt file into a dictionary and use that to create the recipients email addresses using the following snippet.

        foreach (KeyValuePair<string, string> kvp in EmailDict)
        {
            Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(kvp.Value);
            RecipientList += string.Format("{0}; ", kvp.Value);
            oRecip.Resolve();
        }

I hope at least some of this helps someone.

Download image with JavaScript

The problem is that jQuery doesn't trigger the native click event for <a> elements so that navigation doesn't happen (the normal behavior of an <a>), so you need to do that manually. For almost all other scenarios, the native DOM event is triggered (at least attempted to - it's in a try/catch).

To trigger it manually, try:

var a = $("<a>")
    .attr("href", "http://i.stack.imgur.com/L8rHf.png")
    .attr("download", "img.png")
    .appendTo("body");

a[0].click();

a.remove();

DEMO: http://jsfiddle.net/HTggQ/

Relevant line in current jQuery source: https://github.com/jquery/jquery/blob/1.11.1/src/event.js#L332

if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
        jQuery.acceptData( elem ) ) {

Multiple WHERE clause in Linq

Well, you can just put multiple "where" clauses in directly, but I don't think you want to. Multiple "where" clauses ends up with a more restrictive filter - I think you want a less restrictive one. I think you really want:

DataTable tempData = (DataTable)grdUsageRecords.DataSource;
var query = from r in tempData.AsEnumerable()
            where r.Field<string>("UserName") != "XXXX" &&
                  r.Field<string>("UserName") != "YYYY"
            select r;

DataTable newDT = query.CopyToDataTable();

Note the && instead of ||. You want to select the row if the username isn't XXXX and the username isn't YYYY.

EDIT: If you have a whole collection, it's even easier. Suppose the collection is called ignoredUserNames:

DataTable tempData = (DataTable)grdUsageRecords.DataSource;
var query = from r in tempData.AsEnumerable()
            where !ignoredUserNames.Contains(r.Field<string>("UserName"))
            select r;

DataTable newDT = query.CopyToDataTable();

Ideally you'd want to make this a HashSet<string> to avoid the Contains call taking a long time, but if the collection is small enough it won't make much odds.

PHP - Extracting a property from an array of objects

You can do it easily with ouzo goodies

$result = array_map(Functions::extract()->id, $arr);

or with Arrays (from ouzo goodies)

$result = Arrays::map($arr, Functions::extract()->id);

Check out: http://ouzo.readthedocs.org/en/latest/utils/functions.html#extract

See also functional programming with ouzo (I cannot post a link).

Using both Python 2.x and Python 3.x in IPython Notebook

Following are the steps to add the python2 kernel to jupyter notebook::

open a terminal and create a new python 2 environment: conda create -n py27 python=2.7

activate the environment: Linux source activate py27 or windows activate py27

install the kernel in the env: conda install notebook ipykernel

install the kernel for outside the env: ipython kernel install --user

close the env: source deactivate

Although a late answer hope someone finds it useful :p

Why aren't variable-length arrays part of the C++ standard?

This was considered for inclusion in C++/1x, but was dropped (this is a correction to what I said earlier).

It would be less useful in C++ anyway since we already have std::vector to fill this role.

Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610

If you are simply testing a local dev version of WordPress as I was an hitting timeouts when WordPress tries to update itself you can always disable updates for your local version like so: https://www.wpbeginner.com/wp-tutorials/how-to-disable-automatic-updates-in-wordpress/

Don't do this for a production site!

Error: Address already in use while binding socket with address but the port number is shown free by `netstat`

the error i received was:

cockpit.socket: Failed to listen on sockets: Address already in use

the fix I discovered is:

  1. I had to disable selinux
  2. in /usr/lib/systemd/system/cockpit service i changed the line :

    #ExecStartPre=/usr/sbin/remotectl certificate --ensure --user=root --group=cockpit-ws --selinux-type=etc_t
    

    to:

    #ExecStartPre=/usr/sbin/remotectl certificate --ensure --user=root --group=cockpit-ws 
    

so as you can see i took out the argument about selinux then i ran:

systemctl daemon-reload
systemctl start cockpit.service

then I browsed to:

I accepted the self-signed certificate and was able to login successfully to cockpit and use it normally.

this is all on a fedora25 machine. the 9090 port had already been added using firewall-cmd

How can I determine if a date is between two dates in Java?

Between dates Including end points can be written as

public static boolean isDateInBetweenIncludingEndPoints(final Date min, final Date max, final Date date){
    return !(date.before(min) || date.after(max));
}

Verify ImageMagick installation

EDIT: The info and script below only applies to iMagick class - which is not added by default with ImageMagick!!!

If I want to know if imagemagick is installed and actually working as a php extension, I paste this snippet into a web accessible file

<?php

error_reporting(E_ALL); 
ini_set( 'display_errors','1');

/* Create a new imagick object */
$im = new Imagick();

/* Create new image. This will be used as fill pattern */
$im->newPseudoImage(50, 50, "gradient:red-black");

/* Create imagickdraw object */
$draw = new ImagickDraw();

/* Start a new pattern called "gradient" */
$draw->pushPattern('gradient', 0, 0, 50, 50);

/* Composite the gradient on the pattern */
$draw->composite(Imagick::COMPOSITE_OVER, 0, 0, 50, 50, $im);

/* Close the pattern */
$draw->popPattern();

/* Use the pattern called "gradient" as the fill */
$draw->setFillPatternURL('#gradient');

/* Set font size to 52 */
$draw->setFontSize(52);

/* Annotate some text */
$draw->annotation(20, 50, "Hello World!");

/* Create a new canvas object and a white image */
$canvas = new Imagick();
$canvas->newImage(350, 70, "white");

/* Draw the ImagickDraw on to the canvas */
$canvas->drawImage($draw);

/* 1px black border around the image */
$canvas->borderImage('black', 1, 1);

/* Set the format to PNG */
$canvas->setImageFormat('png');

/* Output the image */
header("Content-Type: image/png");
echo $canvas;
?>

You should see a hello world graphic:

enter image description here

Scroll part of content in fixed position container

I changed scrollable div to be with absolute position, and everything works for me

div.sidebar {
    overflow: hidden;
    background-color: green;
    padding: 5px;
    position: fixed;
    right: 20px;
    width: 40%;
    top: 30px;
    padding: 20px;
    bottom: 30%;
}
div#fixed {
    background: #76a7dc;
    color: #fff;
    height: 30px;
}

div#scrollable {
    overflow-y: scroll;
    background: lightblue;

    position: absolute;
    top:55px; 
    left:20px;
    right:20px;
    bottom:10px;
}

DEMO with two scrollable divs

Find integer index of rows with NaN in pandas dataframe

Another simple solution is list(np.where(df['b'].isnull())[0])

SET NAMES utf8 in MySQL?

Thanks @all!

don't use: query("SET NAMES utf8"); this is setup stuff and not a query. put it right afte a connection start with setCharset() (or similar method)

some little thing in parctice:

status:

  • mysql server by default talks latin1
  • your hole app is in utf8
  • connection is made without any extra (so: latin1) (no SET NAMES utf8 ..., no set_charset() method/function)

Store and read data is no problem as long mysql can handle the characters. if you look in the db you will already see there is crap in it (e.g.using phpmyadmin).

until now this is not a problem! (wrong but works often (in europe)) ..

..unless another client/programm or a changed library, which works correct, will read/save data. then you are in big trouble!

How to place the ~/.composer/vendor/bin directory in your PATH?

my path didn't have /.composer, just /composer so my path was:-

export PATH="$PATH:$HOME/.config/composer/vendor/bin"

This worked for me on ubuntu 20.04

How can I check if a MySQL table exists with PHP?

SHOW TABLES LIKE 'TableName'

If you have ANY results, the table exists.

To use this approach in PDO:

$pdo         = new \PDO(/*...*/);
$result      = $pdo->query("SHOW TABLES LIKE 'tableName'");
$tableExists = $result !== false && $result->rowCount() > 0;

To use this approach with DEPRECATED mysql_query

$result      = mysql_query("SHOW TABLES LIKE 'tableName'");
$tableExists = mysql_num_rows($result) > 0;

How do I tokenize a string in C++?

/// split a string into multiple sub strings, based on a separator string
/// for example, if separator="::",
///
/// s = "abc" -> "abc"
///
/// s = "abc::def xy::st:" -> "abc", "def xy" and "st:",
///
/// s = "::abc::" -> "abc"
///
/// s = "::" -> NO sub strings found
///
/// s = "" -> NO sub strings found
///
/// then append the sub-strings to the end of the vector v.
/// 
/// the idea comes from the findUrls() function of "Accelerated C++", chapt7,
/// findurls.cpp
///
void split(const string& s, const string& sep, vector<string>& v)
{
    typedef string::const_iterator iter;
    iter b = s.begin(), e = s.end(), i;
    iter sep_b = sep.begin(), sep_e = sep.end();

    // search through s
    while (b != e){
        i = search(b, e, sep_b, sep_e);

        // no more separator found
        if (i == e){
            // it's not an empty string
            if (b != e)
                v.push_back(string(b, e));
            break;
        }
        else if (i == b){
            // the separator is found and right at the beginning
            // in this case, we need to move on and search for the
            // next separator
            b = i + sep.length();
        }
        else{
            // found the separator
            v.push_back(string(b, i));
            b = i;
        }
    }
}

The boost library is good, but they are not always available. Doing this sort of things by hand is also a good brain exercise. Here we just use the std::search() algorithm from the STL, see the above code.

Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?

Since the name is likely to change in future versions of Android (currently the latest is AppCompatActivity but it will probably change at some point), I believe a good thing to have is a class Activity that extends AppCompatActivity and then all your activities extend from that one. If tomorrow, they change the name to AppCompatActivity2 for instance you will have to change it just in one place.

Escape quotes in JavaScript

<html>
    <body>
        <a href="#" onclick="DoEdit('Preliminary Assessment &quot;Mini&quot;'); return false;">edit</a>
    </body>
</html>

Should do the trick.

What is the T-SQL To grant read and write access to tables in a database in SQL Server?

From SQLServer 2012 more elegant alter role:

use mydb
go

ALTER ROLE db_datareader
  ADD MEMBER MYUSER 
go
ALTER ROLE db_datawriter
  ADD MEMBER MYUSER 
go

Using variable in SQL LIKE statement

But in my opinion one important thing.

The "char(number)" it's lenght of variable.

If we've got table with "Names" like for example [Test1..Test200] and we declare char(5) in SELECT like:

DECLARE @variable char(5)
SET @variable = 'Test1%'
SELECT * FROM table WHERE Name like @variable

the result will be only - "Test1"! (char(5) - 5 chars in lenght; Test11 is 6 )

The rest of potential interested data like [Test11..Test200] will not be returned in the result.

It's ok if we want to limit the SELECT by this way. But if it's not intentional way of doing it could return incorrect results from planned ( Like "all Names begining with Test1..." ).

In my opinion if we don't know the precise lenght of a SELECTed value, a better solution could be something like this one:

DECLARE @variable varchar(max)
SET @variable = 'Test1%'
SELECT * FROM <table> WHERE variable1 like @variable

This returns (Test1 but also Test11..Test19 and Test100..Test199).

When to use MongoDB or other document oriented database systems?

You know, all this stuff about the joins and the 'complex transactions' -- but it was Monty himself who, many years ago, explained away the "need" for COMMIT / ROLLBACK, saying that 'all that is done in the logic classes (and not the database) anyway' -- so it's the same thing all over again. What is needed is a dumb yet incredibly tidy and fast data storage/retrieval engine, for 99% of what the web apps do.

no match for ‘operator<<’ in ‘std::operator

You need to overload operator << for mystruct class

Something like :-

friend ostream& operator << (ostream& os, const mystruct& m)
{
    os << m.m_a <<" " << m.m_b << endl;
    return os ;
}

See here

Multiple controllers with AngularJS in single page app

<div class="widget" ng-controller="widgetController">
    <p>Stuff here</p>
</div>

<div class="menu" ng-controller="menuController">
    <p>Other stuff here</p>
</div>
///////////////// OR ////////////


  <div class="widget" ng-controller="widgetController">
    <p>Stuff here</p>
    <div class="menu" ng-controller="menuController">
        <p>Other stuff here</p>
    </div>
</div>

menuController have access for menu div. And widgetController have access to both.

how to read xml file from url using php

$url = 'http://www.example.com'; $xml = simpleXML_load_file($url,"SimpleXMLElement",LIBXML_NOCDATA);

$url can be php file, as long as the file generate xml format data as output.

Does C# support multiple inheritance?

You cannot do multiple inheritance in C# till 3.5. I dont know how it works out on 4.0 since I have not looked at it, but @tbischel has posted a link which I need to read.

C# allows you to do "multiple-implementations" via interfaces which is quite different to "multiple-inheritance"

So, you cannot do:

class A{}

class B{}

class C : A, B{}

But, you can do:

interface IA{}
interface IB{}

class C : IA, IB{}

HTH

How to remove all non-alpha numeric characters from a string in MySQL?

SELECT teststring REGEXP '[[:alnum:]]+';

SELECT * FROM testtable WHERE test REGEXP '[[:alnum:]]+'; 

See: http://dev.mysql.com/doc/refman/5.1/en/regexp.html
Scroll down to the section that says: [:character_class:]

If you want to manipulate strings the fastest way will be to use a str_udf, see:
https://github.com/hholzgra/mysql-udf-regexp

Running shell command and capturing the output

I had the same problem but figured out a very simple way of doing this:

import subprocess
output = subprocess.getoutput("ls -l")
print(output)

Hope it helps out

Note: This solution is Python3 specific as subprocess.getoutput() doesn't work in Python2

Adding Table rows Dynamically in Android

You can use an inflater with TableRow:

for (int i = 0; i < months; i++) {
    
    View view = getLayoutInflater ().inflate (R.layout.list_month_data, null, false);
        
    TextView textView = view.findViewById (R.id.title);
    
    textView.setText ("Text");
        
    tableLayout.addView (view);
    
}

Layout:

<TableRow
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_centerInParent="true"
    android:gravity="center_horizontal"
    android:paddingTop="15dp"
    android:paddingRight="15dp"
    android:paddingLeft="15dp"
    android:paddingBottom="10dp"
    >
    
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:gravity="center"
        />
    
</TableRow>

How to markdown nested list items in Bitbucket?

Possibilities

  • It is possible to nest a bulleted-unnumbered list into a higher numbered list.
  • But in the bulleted-unnumbered list the automatically numbered list will not start: Its is not supported.
    • To start a new numbered list after a bulleted-unnumbered one, put a piece of text between them, or a subtitle: A new numbered list cannot start just behind the bulleted: The interpreter will not start the numbering.

in practice

  1. Dog

    1. German Shepherd - with only a single space ahead.
    2. Belgian Shepherd - max 4 spaces ahead.
      • Number in front of a line interpreted as a "numbering bullet", so making the indentation.
        • ..and ignores the written digit: Places/generates its own, in compliance with the structure.
        • So it is OK to use only just "1" ones, to get your numbered list.
          • Or whatever integer number, even of more digits: The list numbering will continue by increment ++1.
        • However, the first item in the numbered list will be kept, so the first leading will usually be the number "1".
    3. Malinois - 5 spaces makes 3rd level already.
      1. MalinoisB - 5 spaces makes 3rd level already.
      2. Groenendael - 8 spaces makes 3rd level yet too.
        1. Tervuren - 9 spaces for 4th level - Intentionaly started by "55".
        2. TervurenB - numbered by "88", in the source code.
  2. Cat

    1. Siberian; a. SiberianA - problem reproduced: letters (i.e. "a" here) not recognized by the interpreter as "numbering".
      • No matter, it is indented to its separated line, in the source code.
    2. Siamese
      • a. so written manually as a workaround misusing bullets, unnumbered list.

How to Cast Objects in PHP

a better aproach:

class Animal
{
    private $_name = null;

    public function __construct($name = null)
    {
        $this->_name = $name;
    }

    /**
     * casts object
     * @param Animal $to
     * @return Animal
     */
    public function cast($to)
    {
        if ($to instanceof Animal) {
            $to->_name = $this->_name;
        } else {
            throw(new Exception('cant cast ' . get_class($this) . ' to ' . get_class($to)));
        return $to;
    }

    public function getName()
    {
        return $this->_name;
    }
}

class Cat extends Animal
{
    private $_preferedKindOfFish = null;

    public function __construct($name = null, $preferedKindOfFish = null)
    {
        parent::__construct($name);
        $this->_preferedKindOfFish = $preferedKindOfFish;
    }

    /**
     * casts object
     * @param Animal $to
     * @return Animal
     */
    public function cast($to)
    {
        parent::cast($to);
        if ($to instanceof Cat) {
            $to->_preferedKindOfFish = $this->_preferedKindOfFish;
        }
        return $to;
    }

    public function getPreferedKindOfFish()
    {
        return $this->_preferedKindOfFish;
    }
}

class Dog extends Animal
{
    private $_preferedKindOfCat = null;

    public function __construct($name = null, $preferedKindOfCat = null)
    {
        parent::__construct($name);
        $this->_preferedKindOfCat = $preferedKindOfCat;
    }

    /**
     * casts object
     * @param Animal $to
     * @return Animal
     */
    public function cast($to)
    {
        parent::cast($to);
        if ($to instanceof Dog) {
            $to->_preferedKindOfCat = $this->_preferedKindOfCat;
        }
        return $to;
    }

    public function getPreferedKindOfCat()
    {
        return $this->_preferedKindOfCat;
    }
}

$dogs = array(
    new Dog('snoopy', 'vegetarian'),
    new Dog('coyote', 'any'),
);

foreach ($dogs as $dog) {
    $cat = $dog->cast(new Cat());
    echo get_class($cat) . ' - ' . $cat->getName() . "\n";
}

How do I remove an object from an array with JavaScript?

Use delete-keyword.

delete obj[1];

EDIT: see: Deleting array elements in JavaScript - delete vs splice delete will undefine the offset but not completly remove the entry. Splice would be correct like David said.

CodeIgniter query: How to move a column value to another column in the same row and save the current time in the original column?

Yes, this is possible and I would like to provide a slight alternative to Rajeev's answer that does not pass a php-generated datetime formatted string to the query.

The important distinction about how to declare the values to be SET in the UPDATE query is that they must not be quoted as literal strings.

To prevent CodeIgniter from doing this "favor" automatically, use the set() method with a third parameter of false.

$userId = 444;
$this->db->set('Last', 'Current', false);
$this->db->set('Current', 'NOW()', false);
$this->db->where('Id', $userId);
// return $this->db->get_compiled_update('Login');  // uncomment to see the rendered query
$this->db->update('Login');
return $this->db->affected_rows();  // this is expected to return the integer: 1

The generated query (depending on your database adapter) would be like this:

UPDATE `Login` SET Last = Current, Current = NOW() WHERE `Id` = 444

Demonstrated proof that the query works: https://www.db-fiddle.com/f/vcc6PfMcYhDD87wZE5gBtw/0

In this case, Last and Current ARE MySQL Keywords, but they are not Reserved Keywords, so they don't need to be backtick-wrapped.

If your precise query needs to have properly quoted identifiers (table/column names), then there is always protectIdentifiers().

Spring Boot Java Config Set Session Timeout

  • Spring Boot version 1.0: server.session.timeout=1200
  • Spring Boot version 2.0: server.servlet.session.timeout=10m
    NOTE: If a duration suffix is not specified, seconds will be used.

jQuery Toggle Text?

Perhaps I'm oversimplifying the problem, but this is what I use.

$.fn.extend({
    toggleText: function(a, b) {
        $.trim(this.html()) == a ? this.html(b) : this.html(a);
    }
});

Excel Macro : How can I get the timestamp in "yyyy-MM-dd hh:mm:ss" format?

Timestamp in saving workbook path, the ":" needs to be changed. I used ":" -> "." which implies that I need to add the extension back "xlsx".

wb(x).SaveAs ThisWorkbook.Path & "\" & unique(x) & " - " & Format(Now(), "mm-dd-yy, hh.mm.ss") & ".xlsx"

Drop all tables command

I had the same problem with SQLite and Android. Here is my Solution:

List<String> tables = new ArrayList<String>();
Cursor cursor = db.rawQuery("SELECT * FROM sqlite_master WHERE type='table';", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
    String tableName = cursor.getString(1);
    if (!tableName.equals("android_metadata") &&
            !tableName.equals("sqlite_sequence"))
        tables.add(tableName);
    cursor.moveToNext();
}
cursor.close();

for(String tableName:tables) {
    db.execSQL("DROP TABLE IF EXISTS " + tableName);
}

android image button

just use a Button with android:drawableRight properties like this:

<Button android:id="@+id/btnNovaCompra" android:layout_width="wrap_content"
        android:text="@string/btn_novaCompra"
        android:gravity="center"
        android:drawableRight="@drawable/shoppingcart"
        android:layout_height="wrap_content"/>

How To Set Text In An EditText

You need to:

  1. Declare the EditText in the xml file
  2. Find the EditText in the activity
  3. Set the text in the EditText

Wavy shape with css

I'm not sure it's your shape but it's close - you can play with the values:

https://jsfiddle.net/7fjSc/9/

_x000D_
_x000D_
#wave {_x000D_
  position: relative;_x000D_
  height: 70px;_x000D_
  width: 600px;_x000D_
  background: #e0efe3;_x000D_
}_x000D_
#wave:before {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  border-radius: 100% 50%;_x000D_
  width: 340px;_x000D_
  height: 80px;_x000D_
  background-color: white;_x000D_
  right: -5px;_x000D_
  top: 40px;_x000D_
}_x000D_
#wave:after {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  border-radius: 100% 50%;_x000D_
  width: 300px;_x000D_
  height: 70px;_x000D_
  background-color: #e0efe3;_x000D_
  left: 0;_x000D_
  top: 27px;_x000D_
}
_x000D_
<div id="wave"></div>
_x000D_
_x000D_
_x000D_

Python find elements in one list that are not in the other

TL;DR:
SOLUTION (1)

import numpy as np
main_list = np.setdiff1d(list_2,list_1)
# yields the elements in `list_2` that are NOT in `list_1`

SOLUTION (2) You want a sorted list

def setdiff_sorted(array1,array2,assume_unique=False):
    ans = np.setdiff1d(array1,array2,assume_unique).tolist()
    if assume_unique:
        return sorted(ans)
    return ans
main_list = setdiff_sorted(list_2,list_1)




EXPLANATIONS:
(1) You can use NumPy's setdiff1d (array1,array2,assume_unique=False).

assume_unique asks the user IF the arrays ARE ALREADY UNIQUE.
If False, then the unique elements are determined first.
If True, the function will assume that the elements are already unique AND function will skip determining the unique elements.

This yields the unique values in array1 that are not in array2. assume_unique is False by default.

If you are concerned with the unique elements (based on the response of Chinny84), then simply use (where assume_unique=False => the default value):

import numpy as np
list_1 = ["a", "b", "c", "d", "e"]
list_2 = ["a", "f", "c", "m"] 
main_list = np.setdiff1d(list_2,list_1)
# yields the elements in `list_2` that are NOT in `list_1`


(2) For those who want answers to be sorted, I've made a custom function:

import numpy as np
def setdiff_sorted(array1,array2,assume_unique=False):
    ans = np.setdiff1d(array1,array2,assume_unique).tolist()
    if assume_unique:
        return sorted(ans)
    return ans

To get the answer, run:

main_list = setdiff_sorted(list_2,list_1)

SIDE NOTES:
(a) Solution 2 (custom function setdiff_sorted) returns a list (compared to an array in solution 1).

(b) If you aren't sure if the elements are unique, just use the default setting of NumPy's setdiff1d in both solutions A and B. What can be an example of a complication? See note (c).

(c) Things will be different if either of the two lists is not unique.
Say list_2 is not unique: list2 = ["a", "f", "c", "m", "m"]. Keep list1 as is: list_1 = ["a", "b", "c", "d", "e"]
Setting the default value of assume_unique yields ["f", "m"] (in both solutions). HOWEVER, if you set assume_unique=True, both solutions give ["f", "m", "m"]. Why? This is because the user ASSUMED that the elements are unique). Hence, IT IS BETTER TO KEEP assume_unique to its default value. Note that both answers are sorted.

Python circular importing?

For those of you who, like me, come to this issue from Django, you should know that the docs provide a solution: https://docs.djangoproject.com/en/1.10/ref/models/fields/#foreignkey

"...To refer to models defined in another application, you can explicitly specify a model with the full application label. For example, if the Manufacturer model above is defined in another application called production, you’d need to use:

class Car(models.Model):
    manufacturer = models.ForeignKey(
        'production.Manufacturer',
        on_delete=models.CASCADE,
)

This sort of reference can be useful when resolving circular import dependencies between two applications...."

jQuery multiple conditions within if statement

i == 'InvKey' && i == 'PostDate' will never be true, since i can never equal two different things at once.

You're probably trying to write

if (i !== 'InvKey' && i !== 'PostDate')) 

Set the layout weight of a TextView programmatically

I had a fair amount of difficulty with a solution something very similar to this: trying to have two buttons in a TableRow, with each being half the screen width. For whatever reason, the left button would always be about 70% of the width, and the right button 30%. Calling table_layout.setStretchAllColumns(true) had no effect, nor did setting the button's width to half the screen, nor setting their layout weight.

The solution I ended up with was nesting a LinearLayout in the TableRows, which did take into account the value of the buttons' width.

    TableLayout layout = new TableLayout(this);
    TableRow top_row = new TableRow(this);
    left_button = styleButton();
    right_button = styleButton();
    LinearLayout toprow_layout = new LinearLayout (this);
    toprow_layout.setOrientation(LinearLayout.HORIZONTAL);
    toprow_layout.addView (left_button);
    toprow_layout.addView(right_button);
    toprow.addView(top_layout);
    layout.addView(top_row)

    private Button styleButton() {
            Button btn = new Button (this);
            android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();      
            btn.setWidth((int)(display.getWidth()/2));    // set width to half
            btn.setHeight(((int)display.getHeight()/6));  // set height to whatevs
            btn.setText("foo");
            return btn;
        }

How to set the title text color of UIButton?

This is swift 5 compatible answer. If you want to use one of the built-in colours then you can simply use

button.setTitleColor(.red, for: .normal)

If you want some custom colours, then create an extension for a UIColor as below first.

import UIKit
extension UIColor {
    static var themeMoreButton = UIColor.init(red: 53/255, green: 150/255, blue: 36/255, alpha: 1)
}

Then use it for your button as below.

button.setTitleColor(UIColor.themeMoreButton, for: .normal)

Tip: You can use this method to store custom colours from rgba colour code and reuse it throughout your application.

Anaconda version with Python 3.5

It is very simple, first, you need to be inside the virtualenv you created, then to install a specific version of python say 3.5, use Anaconda, conda install python=3.5

In general you can do this for any python package you want

conda install package_name=package_version

Parsing jQuery AJAX response

 $.ajax({     
     type: "POST",
     url: '/admin/systemgoalssystemgoalupdate?format=html',
     data: formdata,
     success: function (data) {
         console.log(data);
     },
     dataType: "json"
 });

How to change an input button image using CSS?

You can use the <button> tag. For a submit, simply add type="submit". Then use a background image when you want the button to appear as a graphic.

Like so:

<button type="submit" style="border: 0; background: transparent">
    <img src="/images/Btn.PNG" width="90" height="50" alt="submit" />
</button>

More info: http://htmldog.com/reference/htmltags/button/

Class has no objects member

If you use python 3

python3 -m pip install pylint-django

If python < 3

python -m pip install pylint-django==0.11.1

NOTE: Version 2.0, requires pylint >= 2.0 which doesn’t support Python 2 anymore! (https://pypi.org/project/pylint-django/)

Hidden features of Windows batch files

Here how to build a CLASSPATH by scanning a given directory.

setlocal ENABLEDELAYEDEXPANSION
if defined CLASSPATH (set CLASSPATH=%CLASSPATH%;.) else (set CLASSPATH=.)
FOR /R .\lib %%G IN (*.jar) DO set CLASSPATH=!CLASSPATH!;%%G
Echo The Classpath definition is %CLASSPATH%

works in XP (or better). With W2K, you need to use a couple of BAT files to achieve the same result (see Include all jars in the classpath definition ).

It's not needed for 1.6 since you can specify a wildcard directly in CLASSPATH (ex. -cp ".\lib*").

Regular expression: find spaces (tabs/space) but not newlines

Note: For those dealing with CJK text (Chinese, Japanese, and Korean), the double-byte space (Unicode \u3000) is not included in \s for any implementation I've tried so far (Perl, .NET, PCRE, Python). You'll need to either normalize your strings first (such as by replacing all \u3000 with \u0020), or you'll have to use a character set that includes this codepoint in addition to whatever other whitespace you're targeting, such as [ \t\u3000].

If you're using Perl or PCRE, you have the option of using the \h shorthand for horizontal whitespace, which appears to include the single-byte space, double-byte space, and tab, among others. See the Match whitespace but not newlines (Perl) thread for more detail.

However, this \h shorthand has not been implemented for .NET and C#, as best I've been able to tell.

ParseError: not well-formed (invalid token) using cElementTree

The only thing that worked for me is I had to add mode and encoding while opening the file like below:

with open(filenames[0], mode='r',encoding='utf-8') as f:
     readFile()

Otherwise it was failing every time with invalid token error if I simply do this:

 f = open(filenames[0], 'r')
 readFile()

Getting a directory name from a filename

Use boost::filesystem. It will be incorporated into the next standard anyway so you may as well get used to it.

The default XML namespace of the project must be the MSBuild XML namespace

I was getting the same messages while I was running just msbuild from powershell.

dotnet msbuild "./project.csproj" worked for me.

Java SSLHandshakeException "no cipher suites in common"

Having had this exception myself, I delved into the JRE source code. It became apparent that the message is rather misleading. It could mean what it says, but it more generally means that the server doesn't have the data it needs to respond to the client in the requested way. This can happen, for example, if certificates are missing from the keystore, or haven't been generated with the an appropriate algoritm. Indeed, given the cipher suites that are installed by default, one would have to go to some lengths to really get this exception because of lack of common cipher suites. In my particular case I'd generated the certificates with the default algorithm of DSA, when what I needed to get the server to work with Firefox was RSA.

Get index of selected option with jQuery

The first methods seem to work in the browsers that I tested, but the option tags doesn't really correspond to actual elements in all browsers, so the result may vary.

Just use the selectedIndex property of the DOM element:

alert($("#dropDownMenuKategorie")[0].selectedIndex);

Update:

Since version 1.6 jQuery has the prop method that can be used to read properties:

alert($("#dropDownMenuKategorie").prop('selectedIndex'));

How to set selected value on select using selectpicker plugin from bootstrap

Also, you can just call this for multi-value

$(<your select picker>).selectpicker("val", ["value1", "value2"])

You can find more here https://developer.snapappointments.com/bootstrap-select/methods/

When should null values of Boolean be used?

ANSWER TO OWN QUESTION: I thought it would be useful to answer my own question as I have learnt a lot from the answers. This answer is intended to help those - like me - who do not have a complete understanding of the issues. If I use incorrect language please correct me.

  • The null "value" is not a value and is fundamentally different from true and false. It is the absence of a pointer to objects. Therefore to think that Boolean is 3-valued is fundamentally wrong
  • The syntax for Boolean is abbreviated and conceals the fact that the reference points to Objects:

    Boolean a = true;

conceals the fact that true is an object. Other equivalent assignments might be:

Boolean a = Boolean.TRUE;

or

Boolean a = new Boolean(true);
  • The abbreviated syntax

    if (a) ...

is different from most other assignments and conceals the fact that a might be an object reference or a primitive. If an object it is necessary to test for null to avoid NPE. For me it is psychologically easier to remember this if there is an equality test:

if (a == true) ...

where we might be prompted to test for null. So the shortened form is only safe when a is a primitive.

For myself I now have the recommendations:

  • Never use null for a 3-valued logic. Only use true and false.
  • NEVER return Boolean from a method as it could be null. Only return boolean.
  • Only use Boolean for wrapping elements in containers, or arguments to methods where objects are required

Code line wrapping - how to handle long lines

I think that moving last operator to the beginning of the next line is a good practice. That way you know right away the purpose of the second line, even it doesn't start with an operator. I also recommend 2 indentation spaces (2 tabs) for a previously broken tab, to differ it from the normal indentation. That is immediately visible as continuing previous line. Therefore I suggest this:

private static final Map<Class<? extends Persistent>, PersistentHelper> class2helper 
            = new HashMap<Class<? extends Persistent>, PersistentHelper>();

How to remove duplicate objects in a List<MyObject> without equals/hashcode?

First override equals() method:

@Override
public boolean equals(Object obj)
{
    if(obj == null) return false;
    else if(obj instanceof MyObject && getTitle() == obj.getTitle() && getAuthor() == obj.getAuthor() && getURL() == obj.getURL() && getDescription() == obj.getDescription()) return true;
    else return false;
}

and then use:

List<MyObject> list = new ArrayList<MyObject>;
for(MyObject obj1 : list)
{
    for(MyObject obj2 : list)
    {
        if(obj1.equals(obj2)) list.remove(obj1); // or list.remove(obj2);
    }
}

What's the best practice to round a float to 2 decimals?

I've tried to support the -ve values for @Ivan Stin excellent 2nd method. (Major credit goes to @Ivan Stin for his method)

public static float round(float value, int scale) {
    int pow = 10;
    for (int i = 1; i < scale; i++) {
        pow *= 10;
    }
    float tmp = value * pow;
    float tmpSub = tmp - (int) tmp;

    return ( (float) ( (int) (
            value >= 0
            ? (tmpSub >= 0.5f ? tmp + 1 : tmp)
            : (tmpSub >= -0.5f ? tmp : tmp - 1)
            ) ) ) / pow;

    // Below will only handles +ve values
    // return ( (float) ( (int) ((tmp - (int) tmp) >= 0.5f ? tmp + 1 : tmp) ) ) / pow;
}

Below are the tests cases I've tried. Please let me know if this is not addressing any other cases.

@Test
public void testFloatRound() {
    // +ve values
    Assert.assertEquals(0F, NumberUtils.round(0F), 0);
    Assert.assertEquals(1F, NumberUtils.round(1F), 0);
    Assert.assertEquals(23.46F, NumberUtils.round(23.4567F), 0);
    Assert.assertEquals(23.45F, NumberUtils.round(23.4547F), 0D);
    Assert.assertEquals(1.00F, NumberUtils.round(0.49999999999999994F + 0.5F), 0);
    Assert.assertEquals(123.12F, NumberUtils.round(123.123F), 0);
    Assert.assertEquals(0.12F, NumberUtils.round(0.123F), 0);
    Assert.assertEquals(0.55F, NumberUtils.round(0.55F), 0);
    Assert.assertEquals(0.55F, NumberUtils.round(0.554F), 0);
    Assert.assertEquals(0.56F, NumberUtils.round(0.556F), 0);
    Assert.assertEquals(123.13F, NumberUtils.round(123.126F), 0);
    Assert.assertEquals(123.15F, NumberUtils.round(123.15F), 0);
    Assert.assertEquals(123.17F, NumberUtils.round(123.1666F), 0);
    Assert.assertEquals(123.46F, NumberUtils.round(123.4567F), 0);
    Assert.assertEquals(123.87F, NumberUtils.round(123.8711F), 0);
    Assert.assertEquals(123.15F, NumberUtils.round(123.15123F), 0);
    Assert.assertEquals(123.89F, NumberUtils.round(123.8909F), 0);
    Assert.assertEquals(124.00F, NumberUtils.round(123.9999F), 0);
    Assert.assertEquals(123.70F, NumberUtils.round(123.7F), 0);
    Assert.assertEquals(123.56F, NumberUtils.round(123.555F), 0);
    Assert.assertEquals(123.00F, NumberUtils.round(123.00F), 0);
    Assert.assertEquals(123.50F, NumberUtils.round(123.50F), 0);
    Assert.assertEquals(123.93F, NumberUtils.round(123.93F), 0);
    Assert.assertEquals(123.93F, NumberUtils.round(123.9312F), 0);
    Assert.assertEquals(123.94F, NumberUtils.round(123.9351F), 0);
    Assert.assertEquals(123.94F, NumberUtils.round(123.9350F), 0);
    Assert.assertEquals(123.94F, NumberUtils.round(123.93501F), 0);
    Assert.assertEquals(99.99F, NumberUtils.round(99.99F), 0);
    Assert.assertEquals(100.00F, NumberUtils.round(99.999F), 0);
    Assert.assertEquals(100.00F, NumberUtils.round(99.9999F), 0);

    // -ve values
    Assert.assertEquals(-123.94F, NumberUtils.round(-123.93501F), 0);
    Assert.assertEquals(-123.00F, NumberUtils.round(-123.001F), 0);
    Assert.assertEquals(-0.94F, NumberUtils.round(-0.93501F), 0);
    Assert.assertEquals(-1F, NumberUtils.round(-1F), 0);
    Assert.assertEquals(-0.50F, NumberUtils.round(-0.50F), 0);
    Assert.assertEquals(-0.55F, NumberUtils.round(-0.55F), 0);
    Assert.assertEquals(-0.55F, NumberUtils.round(-0.554F), 0);
    Assert.assertEquals(-0.56F, NumberUtils.round(-0.556F), 0);
    Assert.assertEquals(-0.12F, NumberUtils.round(-0.1234F), 0);
    Assert.assertEquals(-0.12F, NumberUtils.round(-0.123456789F), 0);
    Assert.assertEquals(-0.13F, NumberUtils.round(-0.129F), 0);
    Assert.assertEquals(-99.99F, NumberUtils.round(-99.99F), 0);
    Assert.assertEquals(-100.00F, NumberUtils.round(-99.999F), 0);
    Assert.assertEquals(-100.00F, NumberUtils.round(-99.9999F), 0);
}

SecurityError: Blocked a frame with origin from accessing a cross-origin frame

  • Open the start menu
  • Type windows+R or open "Run
  • Execute the following command.

chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security

Trying to check if username already exists in MySQL database using PHP

$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$email = $_POST["email"];
$pass = $_POST["password"];

$check_email = mysqli_query($conn, "SELECT Email FROM crud where Email = '$email' ");
if(mysqli_num_rows($check_email) > 0){
    echo('Email Already exists');
}
else{
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $result = mysqli_query($conn, "INSERT INTO crud (Firstname, Lastname, Email, Password) VALUES ('$firstname', '$lastname', '$email', '$pass')");
}
    echo('Record Entered Successfully');
}

Tooltips for cells in HTML table (no Javascript)

have you tried?

<td title="This is Title">

its working fine here on Firefox v 18 (Aurora), Internet Explorer 8 & Google Chrome v 23x

What does file:///android_asset/www/index.html mean?

it's file:///android_asset/... not file:///android_assets/... notice the plural of assets is wrong even if your file name is assets

How to bind 'touchstart' and 'click' events but not respond to both?

For simple features, just recognize touch or click I use the following code:

var element = $("#element");

element.click(function(e)
{
  if(e.target.ontouchstart !== undefined)
  {
    console.log( "touch" );
    return;
  }
  console.log( "no touch" );
});

This will return "touch" if the touchstart event is defined and "no touch" if not. Like I said this is a simple approach for click/tap events just that.

Excel VBA Password via Hex Editor

I have your answer, as I just had the same problem today:

Someone made a working vba code that changes the vba protection password to "macro", for all excel files, including .xlsm (2007+ versions). You can see how it works by browsing his code.

This is the guy's blog: http://lbeliarl.blogspot.com/2014/03/excel-removing-password-from-vba.html Here's the file that does the work: https://docs.google.com/file/d/0B6sFi5sSqEKbLUIwUTVhY3lWZE0/edit

Pasted from a previous post from his blog:

For Excel 2007/2010 (.xlsm) files do following steps:

  1. Create a new .xlsm file.
  2. In the VBA part, set a simple password (for instance 'macro').
  3. Save the file and exit.
  4. Change file extention to '.zip', open it by any archiver program.
  5. Find the file: 'vbaProject.bin' (in 'xl' folder).
  6. Extract it from archive.
  7. Open the file you just extracted with a hex editor.
  8. Find and copy the value from parameter DPB (value in quotation mark), example: DPB="282A84CBA1CBA1345FCCB154E20721DE77F7D2378D0EAC90427A22021A46E9CE6F17188A". (This value generated for 'macro' password. You can use this DPB value to skip steps 1-8)

  9. Do steps 4-7 for file with unknown password (file you want to unlock).

  10. Change DBP value in this file on value that you have copied in step 8.

    If copied value is shorter than in encrypted file you should populate missing characters with 0 (zero). If value is longer - that is not a problem (paste it as is).

  11. Save the 'vbaProject.bin' file and exit from hex editor.

  12. Replace existing 'vbaProject.bin' file with modified one.
  13. Change extention from '.zip' back to '.xlsm'
  14. Now, open the excel file you need to see the VBA code in. The password for the VBA code will simply be macro (as in the example I'm showing here).

R apply function with multiple parameters

Just pass var2 as an extra argument to one of the apply functions.

mylist <- list(a=1,b=2,c=3)
myfxn <- function(var1,var2){
  var1*var2
}
var2 <- 2

sapply(mylist,myfxn,var2=var2)

This passes the same var2 to every call of myfxn. If instead you want each call of myfxn to get the 1st/2nd/3rd/etc. element of both mylist and var2, then you're in mapply's domain.

How to create a backup of a single table in a postgres database?

I was trying to run pg_dump from within psql command prompt and I was not able to trace output file anywhere on my ubuntu 20.04 box. I tried finding by find / -name "myfilename.sql".

Instead When I tried pg_dump from /home/ubuntu, I found my output file in /home/ubuntu

Why use getters and setters/accessors?

One of the basic principals of OO design: Encapsulation!

It gives you many benefits, one of which being that you can change the implementation of the getter/setter behind the scenes but any consumer of that value will continue to work as long as the data type remains the same.

Char array declaration and initialization in C

Yes, this is a kind of inconsistency in the language.

The "=" in myarray = "abc"; is assignment (which won't work as the array is basically a kind of constant pointer), whereas in char myarray[4] = "abc"; it's an initialization of the array. There's no way for "late initialization".

You should just remember this rule.

First Or Create

Previous answer is obsolete. It's possible to achieve in one step since Laravel 5.3, firstOrCreate now has second parameter values, which is being used for new record, but not for search

$user = User::firstOrCreate([
    'email' => '[email protected]'
], [
    'firstName' => 'Taylor',
    'lastName' => 'Otwell'
]);

How can I compare a date and a datetime in Python?

Here is another take, "stolen" from a comment at can't compare datetime.datetime to datetime.date ... convert the date to a datetime using this construct:

datetime.datetime(d.year, d.month, d.day)

Suggestion:

from datetime import datetime

def ensure_datetime(d):
    """
    Takes a date or a datetime as input, outputs a datetime
    """
    if isinstance(d, datetime):
        return d
    return datetime.datetime(d.year, d.month, d.day)

def datetime_cmp(d1, d2):
    """
    Compares two timestamps.  Tolerates dates.
    """
    return cmp(ensure_datetime(d1), ensure_datetime(d2))

How to find item with max value using linq?

With EF or LINQ to SQL:

var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();

With LINQ to Objects I suggest to use morelinq extension MaxBy (get morelinq from nuget):

var item = items.MaxBy(i => i.Value);

How to un-commit last un-pushed git commit without losing the changes

If you pushed the changes, you can undo it and move the files back to stage without using another branch.

git show HEAD > patch
git revert HEAD
git apply patch

It will create a patch file that contain the last branch changes. Then it revert the changes. And finally, apply the patch files to the working tree.

Plot multiple boxplot in one graph

ggplot version of the lattice plot:

library(reshape2)
library(ggplot2)
df <- read.csv("TestData.csv", header=T)
df.m <- melt(df, id.var = "Label")

ggplot(data = df.m, aes(x=Label, y=value)) + 
         geom_boxplot() + facet_wrap(~variable,ncol = 4)

Plot: enter image description here

Can someone post a well formed crossdomain.xml sample?

Take a look at Twitter's:

http://twitter.com/crossdomain.xml

<?xml version="1.0" encoding="UTF-8"?>
<cross-domain-policy xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.adobe.com/xml/schemas/PolicyFile.xsd">
    <allow-access-from domain="twitter.com" />
    <allow-access-from domain="api.twitter.com" />
    <allow-access-from domain="search.twitter.com" />
    <allow-access-from domain="static.twitter.com" />
    <site-control permitted-cross-domain-policies="master-only"/>
    <allow-http-request-headers-from domain="*.twitter.com" headers="*" secure="true"/>
</cross-domain-policy>

Ruby Arrays: select(), collect(), and map()

EDIT: I just realized you want to filter details, which is an array of hashes. In that case you could do

details.reject { |item| item[:qty].empty? }

The inner data structure itself is not an Array, but a Hash. You can also use select here, but the block is given the key and value in this case:

irb(main):001:0> h = {:sku=>"507772-B21", :desc=>"HP 1TB 3G SATA 7.2K RPM LFF (3 .", :qty=>"", :qty2=>"1", :price=>"5,204.34 P"}
irb(main):002:0> h.select { |key, value| !value.empty? }
=> {:sku=>"507772-B21", :desc=>"HP 1TB 3G SATA 7.2K RPM LFF (3 .", 
    :qty2=>"1", :price=>"5,204.34 P"}

Or using reject, which is the inverse of select (excludes all items for which the given condition holds):

h.reject { |key, value| value.empty? }

Note that this is Ruby 1.9. If you have to maintain compatibility with 1.8, you could do:

Hash[h.reject { |key, value| value.empty? }]

-bash: export: `=': not a valid identifier

Try to surround the path with quotes, and remove the spaces

export PYTHONPATH="/home/user/my_project":$PYTHONPATH

And don't forget to preserve previous content suffixing by :$PYTHONPATH (which is the value of the variable)

Execute the following command to check everything is configured correctly:

echo $PYTHONPATH

How do pointer-to-pointer's work in C? (and when might you use them?)

Let's assume an 8 bit computer with 8 bit addresses (and thus only 256 bytes of memory). This is part of that memory (the numbers at the top are the addresses):

  54   55   56   57   58   59   60   61   62   63   64   65   66   67   68   69
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
|    | 58 |    |    | 63 |    | 55 |    |    | h  | e  | l  | l  | o  | \0 |    |
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+

What you can see here, is that at address 63 the string "hello" starts. So in this case, if this is the only occurrence of "hello" in memory then,

const char *c = "hello";

... defines c to be a pointer to the (read-only) string "hello", and thus contains the value 63. c must itself be stored somewhere: in the example above at location 58. Of course we can not only point to characters, but also to other pointers. E.g.:

const char **cp = &c;

Now cp points to c, that is, it contains the address of c (which is 58). We can go even further. Consider:

const char ***cpp = &cp;

Now cpp stores the address of cp. So it has value 55 (based on the example above), and you guessed it: it is itself stored at address 60.


As to why one uses pointers to pointers:

  • The name of an array usually yields the address of its first element. So if the array contains elements of type t, a reference to the array has type t *. Now consider an array of arrays of type t: naturally a reference to this 2D array will have type (t *)* = t **, and is hence a pointer to a pointer.
  • Even though an array of strings sounds one-dimensional, it is in fact two-dimensional, since strings are character arrays. Hence: char **.
  • A function f will need to accept an argument of type t ** if it is to alter a variable of type t *.
  • Many other reasons that are too numerous to list here.

How do you set the width of an HTML Helper TextBox in ASP.NET MVC?

The original answer is no longer working as written:

<%=Html.TextBox("test", new { style="width:50px" })%> 

will get you a text box with "{ style="width:50px" }" as its text content.

To adjust this for the current release of MVC 1.0, use the following script (note the addition of the second parameter - I have mine starting as blank, adjust accordingly based on your needs):

<%=Html.TextBox("test", "", new { style="width:50px" })%> 

Java: How to read a text file

This example code shows you how to read file in Java.

import java.io.*;

/**
 * This example code shows you how to read file in Java
 *
 * IN MY CASE RAILWAY IS MY TEXT FILE WHICH I WANT TO DISPLAY YOU CHANGE WITH YOUR   OWN      
 */

 public class ReadFileExample 
 {
    public static void main(String[] args) 
    {
       System.out.println("Reading File from Java code");
       //Name of the file
       String fileName="RAILWAY.txt";
       try{

          //Create object of FileReader
          FileReader inputFile = new FileReader(fileName);

          //Instantiate the BufferedReader Class
          BufferedReader bufferReader = new BufferedReader(inputFile);

          //Variable to hold the one line data
          String line;

          // Read file line by line and print on the console
          while ((line = bufferReader.readLine()) != null)   {
            System.out.println(line);
          }
          //Close the buffer reader
          bufferReader.close();
       }catch(Exception e){
          System.out.println("Error while reading file line by line:" + e.getMessage());                      
       }

     }
  }

How do I 'git diff' on a certain directory?

What I was looking for was this:

git diff <ref1>..<ref2> <dirname>

How to get file extension from string in C++

For char array-type strings you can use this:

#include <ctype.h>
#include <string.h>

int main()
{
    char filename[] = "apples.bmp";
    char extension[] = ".jpeg";

    if(compare_extension(filename, extension) == true)
    {
        // .....
    } else {
        // .....
    }

    return 0;
}

bool compare_extension(char *filename, char *extension)
{
    /* Sanity checks */

    if(filename == NULL || extension == NULL)
        return false;

    if(strlen(filename) == 0 || strlen(extension) == 0)
        return false;

    if(strchr(filename, '.') == NULL || strchr(extension, '.') == NULL)
        return false;

    /* Iterate backwards through respective strings and compare each char one at a time */

    for(int i = 0; i < strlen(filename); i++)
    {
        if(tolower(filename[strlen(filename) - i - 1]) == tolower(extension[strlen(extension) - i - 1]))
        {
            if(i == strlen(extension) - 1)
                return true;
        } else
            break;
    }

    return false;
}

Can handle file paths in addition to filenames. Works with both C and C++. And cross-platform.

Android: How to add R.raw to project?

To get it to recognize the raw file, make sure you create it, and add it as a raw resource file. Then go to build.gradle file and add this block of code.

sourceSets {
    main {

        assets.srcDirs = ['/res/raw']

    }
}

How can I brew link a specific version?

if @simon's answer is not working in some of the mac's please follow the below process.

If you have already installed swiftgen using the following commands:

$ brew update $ brew install swiftgen

then follow the steps below in order to run swiftgen with older version.

Step 1: brew uninstall swiftgen Step 2: Navigate to: https://github.com/SwiftGen/SwiftGen/releases and download the swiftgen with version: swiftgen-4.2.0.zip.

Unzip the package in any of the directories.

Step 3: Execute the following in a terminal:

$ mkdir -p ~/dependencies/swiftgen
$ cp -R ~/<your_directory_name>/swiftgen-4.2.0/ ~/dependencies/swiftgen
$ cd /usr/local/bin
$ ln -s ~/dependencies/swiftgen/bin/swiftgen swiftgen
$ mkdir ~/Library/Application\ Support/SwiftGen
$ ln -s ~/dependencies/swiftgen/templates/ ~/Library/Application\ Support/SwiftGen/

$ swiftgen --version

You should get: SwiftGen v0.0 (Stencil v0.8.0, StencilSwiftKit v1.0.0, SwiftGenKit v1.0.1)

enter image description here

Properties file in python (similar to Java Properties)

You can use the following function, which is the modified code of @mvallebr. It respects the properties file comments, ignores empty new lines, and allows retrieving a single key value.

def getProperties(propertiesFile ="/home/memin/.config/customMemin/conf.properties", key=''):
    """
    Reads a .properties file and returns the key value pairs as dictionary.
    if key value is specified, then it will return its value alone.
    """
    with open(propertiesFile) as f:
        l = [line.strip().split("=") for line in f.readlines() if not line.startswith('#') and line.strip()]
        d = {key.strip(): value.strip() for key, value in l}

        if key:
            return d[key]
        else:
            return d

Combine two ActiveRecord::Relation objects

There is a gem called active_record_union that might be what you are looking for.

It's example usages is the following:

current_user.posts.union(Post.published)
current_user.posts.union(Post.published).where(id: [6, 7])
current_user.posts.union("published_at < ?", Time.now)
user_1.posts.union(user_2.posts).union(Post.published)
user_1.posts.union_all(user_2.posts)

HttpListener Access Denied

Can I make it run without admin mode? if yes how? If not how can I make the app change to admin mode after start running?

You can't, it has to start with elevated privileges. You can restart it with the runas verb, which will prompt the user to switch to admin mode

static void RestartAsAdmin()
{
    var startInfo = new ProcessStartInfo("yourApp.exe") { Verb = "runas" };
    Process.Start(startInfo);
    Environment.Exit(0);
}

EDIT: actually, that's not true; HttpListener can run without elevated privileges, but you need to give permission for the URL on which you want to listen. See Darrel Miller's answer for details.

What port is used by Java RMI connection?

All the answers so far are incorrect. The Registry normally uses port 1099, but you can change it. But that's not the end of the story. Remote objects also use ports, and not necessarily 1099.

If you don't specify a port when exporting, RMI uses a random port. The solution is therefore to specify a port number when exporting. And this is a port that needs opening in the firewall, if any.

  • In the case where your remote object extends UnicastRemoteObject, have its constructor call super(port) with some non-zero port number.

  • In the case where it doesn't extend UnicastRemoteObject, provide a non-zero port number to UnicastRemoteObject.exportObject().

There are several wrinkles to this.

  • If you aren't using socket factories, and you provide a non-zero port number when exporting your first remote object, RMI will automatically share that port with subsequently exported remote objects without specified port numbers, or specifying zero. That first remote object includes a Registry created with LocateRegistry.createRegistry(). So if you create a Registry on port 1099, all other objects exported from that JVM can share port 1099.

  • If you are using socket factories, your RMIServerSocketFactory must have a sensible implementation of equals() for port sharing to work, i.e. one that doesn't just rely on object identity via == or Object.equals().

  • If either you don't provide a server socket factory, or you do provide one with a sensible equals() method, but not both, you can use the same non-zero explicit port number for all remote objects, e.g. createRegistry(1099) followed by any number of super(1099) or exportObject(..., 1099) calls.

2 "style" inline css img tags?

if use Inline CSS you use

<img src="http://img705.imageshack.us/img705/119/original120x75.png" style="height:100px;width:100px;" alt="705"/>

Otherwise you can use class properties which related with a separate css file (styling your website) as like In CSS File

.imgSize {height:100px;width:100px;}

In HTML File

<img src="http://img705.imageshack.us/img705/119/original120x75.png" style="height:100px;width:100px;" alt="705"/>

How to change a css class style through Javascript?

I'd highly recommend jQuery. It then becomes as simple as:

$('#mydiv').addClass('newclass');

You don't have to worry about removing the old class then as addClass() will only append to it. You also have removeClass();

The other advantage over the getElementById() method is you can apply it to multiple elements at the same time with a single line of code.

$('div').addClass('newclass');
$('.oldclass').addClass('newclass');

The first example will add the class to all DIV elements on the page. The second example will add the new class to all elements that currently have the old class.

Multi-threading in VBA

I am adding this answer since programmers coming to VBA from more modern languages and searching Stack Overflow for multithreading in VBA might be unaware of a couple of native VBA approaches which sometimes help to compensate for VBA's lack of true multithreading.

If the motivation of multithreading is to have a more responsive UI that doesn't hang when long-running code is executing, VBA does have a couple of low-tech solutions that often work in practice:

1) Userforms can be made to display modelessly - which allows the user to interact with Excel while the form is open. This can be specified at runtime by setting the Userform's ShowModal property to false or can be done dynamically as the from loads by putting the line

UserForm1.Show vbModeless

in the user form's initialize event.

2) The DoEvents statement. This causes VBA to cede control to the OS to execute any events in the events queue - including events generated by Excel. A typical use-case is updating a chart while code is executing. Without DoEvents the chart won't be repainted until after the macro is run, but with Doevents you can create animated charts. A variation of this idea is the common trick of creating a progress meter. In a loop which is to execute 10,000,000 times (and controlled by the loop index i ) you can have a section of code like:

If i Mod 10000 = 0 Then
    UpdateProgressBar(i) 'code to update progress bar display
    DoEvents
End If

None of this is multithreading -- but it might be an adequate kludge in some cases.

Can't access to HttpContext.Current

This is because you are referring to property of controller named HttpContext. To access the current context use full class name:

System.Web.HttpContext.Current

However this is highly not recommended to access context like this in ASP.NET MVC, so yes, you can think of System.Web.HttpContext.Current as being deprecated inside ASP.NET MVC. The correct way to access current context is

this.ControllerContext.HttpContext

or if you are inside a Controller, just use member

this.HttpContext