This is a setting in IntelliJ IDEA ($JAVA_HOME
and language level were set to 1.8):
File
> Settings
> Build, Execution, Deployment
> Gradle
> Gradle JVM
Select eg. Project SDK (corretto-1.8)
(or any other compatible version).
Then delete the build
directory and restart the IDE.
Tried this on Android Studio and it worked for me:
Tools > SDK Manager (Make sure to check Show Packages below)
I found this solution.I download JDK 8.Then I add downloading jdk file path name of JAVA_HOME into user variables in environment variable.
Apparently if you use "commandlinetools" version greater than 3.6.0 you may use JDK11+ to install Android SDK components.
They are available here: https://developer.android.com/studio#command-tools
Official issue tracker saying it is fixed: https://issuetracker.google.com/issues/122210344#comment11
I got the same problem after creating a new TestCase: Eclipse -> New -> JUnit Test Case. It creates a class without access level modifier. I could solve the problem by just putting a public before the class keyword.
As @steven pointed out, install Java 8 (here a link for Ubuntu 16.04, 18.04 and 20.04/20.10 https://computingforgeeks.com/how-to-install-java-8-on-ubuntu/) and then set it as the default Java version with this command:
sudo update-alternatives --config java
If issue remains even after updating dependency version, then delete everything present under
C:\Users\[your_username]\.m2\repository\com\fasterxml
And, make sure following dependencies are present:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
When your app and the libraries it references exceed 65,536 methods, you encounter a build error that indicates your app has reached the limit of the Android build architecture
To avoid this limitation you have to configure your app for multidex
If your minSdkVersion is set to 21 or higher, all you need to do is set multiDexEnabled to true in your module-level build.gradle file, as shown here:
android { defaultConfig { ... minSdkVersion 21 multiDexEnabled true } ... }
Else, if your minSdkVersion is set to 20 or lower, then you must use the multidex support library as follows:
1.Modify the module-level build.gradle file to enable multidex and add the multidex library as a dependency, as shown here:
android { defaultConfig { ... minSdkVersion 15 multiDexEnabled true } ... } dependencies { implementation 'com.android.support:multidex:1.0.3' }
2.Depending on whether you override the Application class, perform one of the following:
- If you do not override the Application class, edit your manifest file to set android:name in the tag as follows:
<application android:name="android.support.multidex.MultiDexApplication" > ... </application>
- Else If you do override the Application class, change it to extend MultiDexApplication (if possible) as follows:
public class MyApplication extends MultiDexApplication { ... }
- Else you do override the Application class but it's not possible to change the base class, then you can instead override the attachBaseContext() method and call MultiDex.install(this) to enable multidex:
public class MyApplication extends SomeOtherApplication { @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); MultiDex.install(this); } }
Yeah, resolved the exception by adding commons-collections4-4.1 jar file to the CLASSPATH user varible of system. Downloaded from https://mvnrepository.com/artifact/org.apache.commons/commons-collections4/4.1
Faced the same issue. To solve it,
$ sdk install gradle
using the package manager or $ brew install gradle
for mac. You might need to first install brew if not yet. Your code was compiled with Java 8.
Either compile your code with an older JDK (compliance level) or run it on a Java 8 JRE.
Hope this helps...
Things are much easier nowadays: the builtin Snippet Generator supports the 'build' step (I don't know since when though).
The problem specified:
Exception in thread "main" java.lang.UnsupportedClassVersionError: com/android/dx/command/Main : Unsupported major.minor version 52.
is caused when is declared inside the build.gradle
, buildToolsVersion 24
and we don´t have Java 8 installed that is required for this version. To solve this problem we have to change from buildToolsVersion
from 24 to maximum 23:
Java 8 must be required in the future for Android Studio
, so we have to start using Java 8.
I had different version of annotations jar. Changed all 3 jars to use SAME version of databind,annotations and core jackson jars
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.6</version>
</dependency>
This was my stupidity, but a stupidity that was not easy to identify :).
Problem:
If you are deploying manually into your server, ensure your JAVA_HOME, JDK_HOME points to the correct JDK which you used to compile the project and build the war.
If you do not like to change JAVA_HOME, JDK_HOME, you can always change the JAVA_HOME and JDK_HOME in catalina.bat(for tomcat server) and that'll enable your life to be easy!
The problem is because you haven't set JDK version properly.You should use jdk 7 for major number 51. Like this:
JAVA_HOME=/usr/java/jdk1.7.0_79
Spring Data JPA 1.11 now supports the exists
projection in repository query derivation.
See documentation here.
In your case the following will work:
public interface MyEntityRepository extends CrudRepository<MyEntity, String> {
boolean existsByFoo(String foo);
}
That looks like you tried to add the libraries servlet.jar
or servlet-api.jar
into your project /lib/
folder, but Tomcat already should provide you with those libraries. Remove them from your project and classpath. Search for that anywhere in your project or classpath and remove it.
The requested jar is probably not jackson-annotations-x.y.z.jar but jackson-core-x.y.z.jar which could be found here: http://www.java2s.com/Code/Jar/j/Downloadjacksoncore220rc1jar.htm
Well, you're getting a java.lang.NoClassDefFoundError
. In your pom.xml
, hibernate-core
version is 3.3.2.GA
and declared after hibernate-entitymanager
, so it prevails. You can remove that dependency, since will be inherited version 3.6.7.Final
from hibernate-entitymanager
.
You're using spring-boot
as parent, so no need to declare version of some dependencies, since they are managed by spring-boot
.
Also, hibernate-commons-annotations
is inherited from hibernate-entitymanager
and hibernate-annotations
is an old version of hibernate-commons-annotations
, you can remove both.
Finally, your pom.xml
can look like this:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.elsys.internetprogramming.trafficspy.server</groupId>
<artifactId>TrafficSpyService</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.3.RELEASE</version>
</parent>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cloud-connectors</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.0.0</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<properties>
<java.version>1.7</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
<repository>
<id>codehaus</id>
<url>http://repository.codehaus.org/org/codehaus</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
Let me know if you have a problem.
I solved it putting a old version of maven (2.x), using brew:
brew uninstall maven
brew tap homebrew/versions
brew install maven2
A CLASSPATH entry is either a directory at the head of a package hierarchy of .class files, or a .jar file. If you're expecting ./lib
to include all the .jar files in that directory, it won't. You have to name them explicitly.
I have this method for deserializing an XML and converting the type:
public <T> Object deserialize(String xml, Class objClass ,TypeReference<T> typeReference ) throws IOException {
XmlMapper xmlMapper = new XmlMapper();
Object obj = xmlMapper.readValue(xml,objClass);
return xmlMapper.convertValue(obj,typeReference );
}
and this is the call:
List<POJO> pojos = (List<POJO>) MyUtilClass.deserialize(xml, ArrayList.class,new TypeReference< List< POJO >>(){ });
Added AWS dependency and had this error. When I remove it from pom the error is gone. Probably you might have the same situation.
The Exception it self says it all java.lang.ClassNotFoundException: org.json.JSONObject
You have not added the necessary jar file which will be having org.json.JSONObject
class to your classpath
.
You can Download it From Here
Here's a one-liner using Maven:
mvn dependency:get -Dartifact=mysql:mysql-connector-java:5.1.38
Then, with default settings, it's available in:
$HOME/.m2/repository/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar
Just replace the version number if you need a different one.
For those of you who still don't understand after reading @meda answer, here is my concise and complete explanation for this issue:
Let's say you have 2 Fragments, Fragment_A
and Fragment_B
which are auto-generated from the app. On the bottom part of your generated fragments, you're going to find this code:
public class Fragment_A extends Fragment {
//rest of the code is omitted
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
public class Fragment_B extends Fragment {
//rest of the code is omitted
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
To overcome the issue, you have to add onFragmentInteraction
method into your activity, which in my case is named MainActivity2
. After that, you need to implements
all fragments in the MainActivity
like this:
public class MainActivity2 extends ActionBarActivity
implements Fragment_A.OnFragmentInteractionListener,
Fragment_B.OnFragmentInteractionListener,
NavigationDrawerFragment.NavigationDrawerCallbacks {
//rest code is omitted
@Override
public void onFragmentInteraction(Uri uri){
//you can leave it empty
}
}
P.S.: In short, this method could be used for communicating between fragments. For those of you who want to know more about this method, please refer to this link.
Add the jar files on class path NOT modulepath.
in case your project use dagger, and then this error show up you can add this at android manifest
<application
...
android: name = ".BaseApplication"
...> ...
Clearly you aren't sending the data with ObjectOutputStream:
you are just writing the bytes.
readObject()
you must write with writeObject().
readUTF()
you must write with writeUTF().
readXXX()
you must write with writeXXX(),
for most values of XXX.@RequestMapping(
value="person",
method=RequestMethod.POST,
consumes="application/json",
produces="application/json")
@ResponseBody
public List<String> savePerson(@RequestBody Person[] personArray) {
List<String> response = new ArrayList<String>();
for (Person person: personArray) {
personService.save(person);
response.add("Saved person: " + person.toString());
}
return response;
}
We can use Array as shown above.
Setup:
My OS windows 8 64bit
Eclipse version Standard/SDK Kepler Service Release 2
My JDK is jdk-8u5-windows-i586
My JRE is jre-8u5-windows-i586
This how I overcome my error.
At the very first my Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")
also didn't work.
Then I login to this website and downloaded the UCanAccess 2.0.8 zip (as Mr.Gord Thompson said) file and unzip it.
Then you will also able to find these *.jar files in that unzip folder:
ucanaccess-2.0.8.jar
commons-lang-2.6.jar
commons-logging-1.1.1.jar
hsqldb.jar
jackcess-2.0.4.jar
Then what I did was I copied all these 5 files and paste them in these 2 locations:
C:\Program Files (x86)\eclipse\lib
C:\Program Files (x86)\eclipse\lib\ext
(I did that funny thing becoz I was unable to import these libraries to my project)
Then I reopen the eclipse with my project.then I see all that *.jar files in my project's JRE System Library folder.
Finally my code works.
public static void main(String[] args)
{
try
{
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\Hasith\\Documents\\JavaDatabase1.mdb");
Statement stment = conn.createStatement();
String qry = "SELECT * FROM Table1";
ResultSet rs = stment.executeQuery(qry);
while(rs.next())
{
String id = rs.getString("ID") ;
String fname = rs.getString("Nama");
System.out.println(id + fname);
}
}
catch(Exception err)
{
System.out.println(err);
}
//System.out.println("Hasith Sithila");
}
Just try Clean Project & Rebuild Project.
I agree with the accepted answer. But for me, the issue was not that, instead I had to modify my Servlet-Class name from:-
<servlet-class>org.glassfish.jersey.servlet.ServletContainer.class</servlet-class>
To:
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
So, removing .class worked fine in my case. Hope it will help somebody!
All of these answers appear to be incomplete and/or kludges. Looking at the RestTemplate interface, it sure looks like it is intended to have a ClientHttpRequestFactory
injected into it, and then that requestFactory will be used to create the request, including any customizations of headers, body, and request params.
You either need a universal ClientHttpRequestFactory
to inject into a single shared RestTemplate
or else you need to get a new template instance via new RestTemplate(myHttpRequestFactory)
.
Unfortunately, it looks somewhat non-trivial to create such a factory, even when you just want to set a single Authorization header, which is pretty frustrating considering what a common requirement that likely is, but at least it allows easy use if, for example, your Authorization header can be created from data contained in a Spring-Security Authorization
object, then you can create a factory that sets the outgoing AuthorizationHeader on every request by doing SecurityContextHolder.getContext().getAuthorization()
and then populating the header, with null checks as appropriate. Now all outbound rest calls made with that RestTemplate will have the correct Authorization header.
Without more emphasis placed on the HttpClientFactory mechanism, providing simple-to-overload base classes for common cases like adding a single header to requests, most of the nice convenience methods of RestTemplate
end up being a waste of time, since they can only rarely be used.
I'd like to see something simple like this made available
@Configuration
public class MyConfig {
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate(new AbstractHeaderRewritingHttpClientFactory() {
@Override
public HttpHeaders modifyHeaders(HttpHeaders headers) {
headers.addHeader("Authorization", computeAuthString());
return headers;
}
public String computeAuthString() {
// do something better than this, but you get the idea
return SecurityContextHolder.getContext().getAuthorization().getCredential();
}
});
}
}
At the moment, the interface of the available ClientHttpRequestFactory's are harder to interact with than that. Even better would be an abstract wrapper for existing factory implementations which makes them look like a simpler object like AbstractHeaderRewritingRequestFactory for the purposes of replacing just that one piece of functionality. Right now, they are very general purpose such that even writing those wrappers is a complex piece of research.
my problem was with @WebServelet annotation and it was because of the name was repeated, I had two of @WebServlet("/route")
in my code by mistake(I copy and pasted and forgot to change the route name)
Check in Deployment Assembly,
I have the same error, when i generate the war file with the "maven clean install" way and deploy manualy, it works fine, but when i use the runtime enviroment (eclipse) the problems come.
The solution for me (for eclipse IDE) go to: "proyect properties" --> "Deployment Assembly" --> "Add" --> "the jar you need", in my case java "build path entries". Maybe can help a litle!
Here the packaging is jar type, hence you need to use manifest plugin, in order to add dependencies into the Manifest.mf
The problem here is that maven could find the dependencies in pom file and compile the source code and create the output jar. But when executing the jar, manifest.mf file contains no details of dependencies. Hence you got this error. This is a case of classpath errors.
Here you can find the details on how to do it.
This is because of a higher JDK during compile time and lower JDK during runtime. So you just need to update your JDK version, possible to JDK 7
You may also check Unsupported major.minor version 51.0
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to id.co.bni.switcherservice.model.SwitcherServiceSource
Problem is
(List<SwitcherServiceSource>) LoadSource.list();
This will return a List of Object arrays (Object[]) with scalar values for each column in the SwitcherServiceSource
table. Hibernate will use ResultSetMetadata to deduce the actual order and types of the returned scalar values.
List<Object> result = (List<Object>) LoadSource.list();
Iterator itr = result.iterator();
while(itr.hasNext()){
Object[] obj = (Object[]) itr.next();
//now you have one array of Object for each row
String client = String.valueOf(obj[0]); // don't know the type of column CLIENT assuming String
Integer service = Integer.parseInt(String.valueOf(obj[1])); //SERVICE assumed as int
//same way for all obj[2], obj[3], obj[4]
}
You Can not Use the Intent's Context
for Creating Intent. So You need to use your Fragment's
Parent Activity
Context
Intent intent = new Intent(getActivity(),MyClass.class);
I have had the same problem in my project. I used an IntelliJ Idea 14 and Maven 8. And what I've noticed is that when I added a tomcat destination to to IDE it automaticly linked two jars from tomcat lib directory, they were servlet-api and jsp-api. Also I had them in my pom.xml. I killed a whole day trying to figure out why I'm getting java.lang.ClassNotFoundException: org.apache.jsp.index_jsp. And kewpiedoll99 is right. That is because there are dependency conflicts. When I added provided to those two jars in my pom.xml I found a happiness :)
This works for me. It should be in your onOptionsItemSelected(MenuItem item)
method item.setIcon(R.drawable.your_icon);
You need to include xmlbeans-xxx.jar and if you have downloaded the POI binary zip, you will get the xmlbeans-xxx.jar in ooxml-lib folder (eg: \poi-3.11\ooxml-lib)
This jar is used for XML binding which is applicable for .xlsx files.
Didn't work with ODBC-Bridge for me too. I got the way around to initialize ODBC connection using ODBC driver.
import java.sql.*;
public class UserLogin
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// C:\\databaseFileName.accdb" - location of your database
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";
// specify url, username, pasword - make sure these are valid
Connection conn = DriverManager.getConnection(url, "username", "password");
System.out.println("Connection Succesfull");
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
I had this issue, raised by several causes, but i see this in your stacktrace "**Unable to instantiate activity ComponentInfo{...}: java.lang.ClassNotFoundException: Didn't find class "..." on path: DexPathList[[**
", I found a diference in my .classpath
before it stop working.
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
<classpathentry kind="src" path="gen"/>
<classpathentry kind="output" path="bin/classes"/>
</classpath>
I've ADDED the line:
<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
this is the final version:
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
<classpathentry kind="src" path="gen"/>
<classpathentry kind="output" path="bin/classes"/>
</classpath>
Now it works! =)
The link has the driver for sqlserver
, download and add it your eclipse
buildpath.
From version 4.x, only Android SDK 24+ is supported by default, and androidx is required.
Add the following to your build.gradle file:
repositories {
jcenter()
}
dependencies {
implementation 'com.journeyapps:zxing-android-embedded:4.1.0'
implementation 'androidx.appcompat:appcompat:1.0.2'
}
android {
buildToolsVersion '28.0.3' // Older versions may give compile errors
}
Older SDK versions
For Android SDK versions < 24, you can downgrade zxing:core to 3.3.0 or earlier for Android 14+ support:
repositories {
jcenter()
}
dependencies {
implementation('com.journeyapps:zxing-android-embedded:4.1.0') { transitive = false }
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'com.google.zxing:core:3.3.0'
}
android {
buildToolsVersion '28.0.3'
}
You'll also need this in your Android manifest:
<uses-sdk tools:overrideLibrary="com.google.zxing.client.android" />
Source : https://github.com/journeyapps/zxing-android-embedded
Try this:
{
"ACCOUNT_EXIST": true,
"MultipleContacts": false
}
boolean success ((Boolean) jsonObject.get("ACCOUNT_EXIST")).booleanValue()
Does the class org.apache.maven.shared.filtering.MavenFilteringException
exist in file:/C:/Users/utopcu/.m2/repository/org/apache/maven/shared/maven-filtering/1.0-beta-2/maven-filtering-1.0-beta-2.jar
?
The error message suggests that it doesn't. Maybe the JAR was corrupted somehow.
I'm also wondering where the version 1.0-beta-2
comes from; I have 1.0
on my disk. Try version 2.3
of the WAR plugin.
JSONObject obj=(JSONObject)JSONValue.parse(content);
JSONArray arr=(JSONArray)obj.get("units");
System.out.println(arr.get(1)); //this will print {"id":42,...sities ..}
@cyberz is right but explain it reverse
Just go to the project Properties->Project Facets
Uncheck the dynamic module, click apply.
Maven->update the project.
These are all too long.
Just use:
new Date(System.currentTimeMillis())
If you are using jersey 2.x then you need different configuration in web.xml as servlet class is change in it. you can update your web.xml with following configuration.
<servlet>
<servlet-name>myrest</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>your.package.path</param-value>
</init-param>
<init-param>
<param-name>unit:WidgetPU</param-name>
<param-value>persistence/widget</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>myrest</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
if you recently added multidex support in android studio like this:
// To Support MultiDex
implementation 'com.android.support:multidex:1.0.1'
so your solution is just extend From MultiDexApplication instead of Application
public class MyApp extends MultiDexApplication {
You will have to include driver jar for MySQL MySQL Connector Jar in your classpath.
If you are using Eclipse: How to add dependent libraries in Eclipse
If you are using command line include the path to the driver jar using the -cp parameter of java.
java -cp C:\lib\* Main
In my case the class thrown as class not found exception has properties related to ssl certificates. Close the eclipse and open with as “Run as Administrator” then issue got resolved. As eclipse have issue related permission it will throw such kind of exception.
Maybe there is a file got locked in the target folder
The number of results can (theoretically) be greater than the range of an integer. I would refactor the code and work with the returned long value instead.
com.sun.mail.util.MailLogger
is part of JavaMail API. It is already included in EE environment (that's why you can use it on your live server), but it is not included in SE environment.
The JavaMail API is available as an optional package for use with Java SE platform and is also included in the Java EE platform.
99% that you run your tests in SE environment which means what you have to bother about adding it manually to your classpath when running tests.
If you're using maven add the following dependency (you might want to change version):
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.0</version>
</dependency>
Easy way and it works for me. Using Android Studio 0.8.2.
Search here for centos jre install all users:
The easiest way to set an environment variable in CentOS is to use export as in
$> export JAVA_HOME=/usr/java/jdk.1.5.0_12
$> export PATH=$PATH:$JAVA_HOME
However, variables set in such a manner are transient i.e. they will disappear the moment you exit the shell. Obviously this is not helpful when setting environment variables that need to persist even when the system reboots.
In such cases, you need to set the variables within the system wide profile. In CentOS (I’m using v5.2), the folder /etc/profile.d/ is the recommended place to add customizations to the system profile.
For example, when installing the Sun JDK, you might need to set the JAVA_HOME and JRE_HOME environment variables. In this case:
Create a new file called java.sh
vim /etc/profile.d/java.sh
Within this file, initialize the necessary environment variables
export JRE_HOME=/usr/java/jdk1.5.0_12/jre
export PATH=$PATH:$JRE_HOME/bin
export JAVA_HOME=/usr/java/jdk1.5.0_12
export JAVA_PATH=$JAVA_HOME
export PATH=$PATH:$JAVA_HOME/bin
Now when you restart your machine, the environment variables within java.sh will be automatically initialized (checkout /etc/profile if you are curious how the files in /etc/profile.d/ are loaded).
PS: If you want to load the environment variables within java.sh
without having to restart the machine, you can use the source command as in:
$> source java.sh
The private key password defined in your app/config is incorrect. First try verifying the the private key password by changing to another one as follows:
keytool -keypasswd -new changeit -keystore cacerts -storepass changeit -alias someapp -keypass password
The above example changes the password from password to changeit. This command will succeed if the private key password was password.
Just use the exec-maven-plugin
.
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<configuration>
<mainClass>com.example.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>
Then you run you program:
mvn exec:java
problem is not in the code, but you don't have added the driver to your project!!!
You have to add the *.jar
driver to your project...
Try putting this in your lib directory, then re-starting tomcat...
problem is Class.forName("com.mysql.jdbc.Driver");
it tries to load the driver, but it is not getting it, this is the reason you are getting:
java.lang.ClassNotFoundException.
Try to insert this:
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
before getting the JDBC Connection.
Class.forName("oracle.jdbc.driver.OracleDriver");
This line causes ClassNotFoundException
, because you haven't placed ojdbc14.jar
file in your lib folder of the project. or YOu haven't set the classpath
of the required jar
I tried the option above of moving the plugins but it didn't work. My solution was to delete the entire .metadata folder. This meant that I lost my defaults and had to import my projects again.
intellij idea 2019
or ub Gradle set "compile" compile group: 'com.microsoft.sqlserver', name: 'mssql-jdbc', version: '7.2.2.jre11'
In my case I have changed project name in pom.xml so the new target directory was generated and junit was searching classes in old directory. You need to change directory for JUnit also in Eclipse
Properties -> Java Build Path -> Source (Default output folder)
And also check because some of source folders listed in the same window may have former directory name. You need to change them too.
Java 7 introduced stricter verification and changed the class format a bit—to contain a stack map used to verify that code is correct. The exception you see means that some method doesn't have a valid stack map.
Java version or bytecode instrumentation could both be to blame. Usually this means that a library used by the application generates invalid bytecode that doesn't pass the stricter verification. So nothing else than reporting it as a bug to the library can be done by the developer.
As a workaround you can add -noverify
to the JVM arguments in order to disable verification. In Java 7 it was also possible to use -XX:-UseSplitVerifier
to use the less strict verification method, but that option was removed in Java 8.
Probably the jstl libraries are missing from your classpath/not accessible by tomcat.
You need to add at least the following jar files in your WEB-INF/lib
directory:
The above problem can be solved by adding the following dependencies in your project, as i was facing the same problem.For more detail answer to this solution please refer link SEVERE:MessageBodyWriter not found for media type=application/xml type=class java.util.HashMap
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.25</version>
</dependency>
I stumble upon this question and it grabbed my interest. The accepted answer is completely correct, but I thought I do provide my findings at JVM byte code level to explain why the OP encounter the ClassCastException
.
I have the code which is pretty much the same as OP's code:
public static <T> T convertInstanceOfObject(Object o) {
try {
return (T) o;
} catch (ClassCastException e) {
return null;
}
}
public static void main(String[] args) {
String k = convertInstanceOfObject(345435.34);
System.out.println(k);
}
and the corresponding byte code is:
public static <T> T convertInstanceOfObject(java.lang.Object);
Code:
0: aload_0
1: areturn
2: astore_1
3: aconst_null
4: areturn
Exception table:
from to target type
0 1 2 Class java/lang/ClassCastException
public static void main(java.lang.String[]);
Code:
0: ldc2_w #3 // double 345435.34d
3: invokestatic #5 // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
6: invokestatic #6 // Method convertInstanceOfObject:(Ljava/lang/Object;)Ljava/lang/Object;
9: checkcast #7 // class java/lang/String
12: astore_1
13: getstatic #8 // Field java/lang/System.out:Ljava/io/PrintStream;
16: aload_1
17: invokevirtual #9 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
20: return
Notice that checkcast
byte code instruction happens in the main method not the convertInstanceOfObject
and convertInstanceOfObject
method does not have any instruction that can throw ClassCastException
. Because the main method does not catch the ClassCastException
hence when you execute the main method you will get a ClassCastException
and not the expectation of printing null
.
Now I modify the code to the accepted answer:
public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
try {
return clazz.cast(o);
} catch (ClassCastException e) {
return null;
}
}
public static void main(String[] args) {
String k = convertInstanceOfObject(345435.34, String.class);
System.out.println(k);
}
The corresponding byte code is:
public static <T> T convertInstanceOfObject(java.lang.Object, java.lang.Class<T>);
Code:
0: aload_1
1: aload_0
2: invokevirtual #2 // Method java/lang/Class.cast:(Ljava/lang/Object;)Ljava/lang/Object;
5: areturn
6: astore_2
7: aconst_null
8: areturn
Exception table:
from to target type
0 5 6 Class java/lang/ClassCastException
public static void main(java.lang.String[]);
Code:
0: ldc2_w #4 // double 345435.34d
3: invokestatic #6 // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
6: ldc #7 // class java/lang/String
8: invokestatic #8 // Method convertInstanceOfObject:(Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Object;
11: checkcast #7 // class java/lang/String
14: astore_1
15: getstatic #9 // Field java/lang/System.out:Ljava/io/PrintStream;
18: aload_1
19: invokevirtual #10 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
22: return
Notice that there is an invokevirtual
instruction in the convertInstanceOfObject
method that calls Class.cast()
method which throws ClassCastException
which will be catch by the catch(ClassCastException e)
bock and return null
; hence, "null" is printed to console without any exception.
team! For execute SQL-query from your Servlet you should add JDBC jar library in folder
WEB-INF/lib
After this you could call driver, example :
Class.forName("oracle.jdbc.OracleDriver");
Now Y can use connection to DB-server
==> 73!
Add Google Play Services to Your Project
To make the Google Play services APIs available to your app:
follow the steps present in this link : http://developer.android.com/google/play-services/setup.html#Setup
This will not work java -cp lib\*.jar -jar myproject.jar
. You have to put it jar by jar.
So in case of commons-codec-1.3.jar
.
java -cp lib/commons-codec-1.3.jar;lib/next_jar.jar
and so on.
The other solution might be putting all your jars to ext
directory of your JRE. This is ok if you are using a standalone JRE. If you are using the same JRE for running more than one application I do not recommend doing it.
Right click on project properties and follow below steps Project Properties" --> "Deployment Assembly", adding "Java Build Path Entries -> Maven Dependencies
Another option is to delete all the classes and rebuild. Having build file is an ideal solution to control whole process like compilation, packaging and deployment. You can also specify source/target versions
I am assuming you are using Eclipse as your developing environment.
Eclipse Juno, Indigo and Kepler when using the bundled maven version(m2e), are not suppressing the message SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". This behaviour is present from the m2e version 1.1.0.20120530-0009 and onwards.
Although, this is indicated as an error your logs will be saved normally. The highlighted error will still be present until there is a fix of this bug. More about this in the m2e support site.
The current available solution is to use an external maven version rather than the bundled version of Eclipse. You can find about this solution and more details regarding this bug in the question below which i believe describes the same problem you are facing.
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error
The first parameter to LayoutParams is the width and the second is the height. So if you want the width to be FILL_PARENT, but the width to be, say, 20px, then use something new LayoutParams(FILL_PARENT, 20). Of course you should never use actual pixels in your code; you'll need to conver that to density-independent pixels, but you get the idea. Also, you need to make sure your parent LinearLayout has the right width and height that you're looking for. Seems to be you want the LinearLayout to fill the parent width-wise and then have the adview fill that linearlayout witdh-wise as well, so you probably need to specify android:layout_width:"fill_parent" and android:layout_height:"wrap_content" in your linear layout's xml.
Well I am not sure what actual cause is but I have done this way for the same error. I have comment out this annotation for the servelet and its working.
//@WebServlet("/HelloWorld")
public class HelloWorld extends HttpServlet {
Dont know that could be proper solution of not. but this worked and another thing that can be test is add servlet jar into class path. That might work.
If you use the static method and load the properties file from the classpath folder so you can use the below code :
//load a properties file from class path, inside static method
Properties prop = new Properties();
prop.load(Classname.class.getClassLoader().getResourceAsStream("foo.properties"));
Using " ; " as delimiter on windows issue got resolved.
java -cp "path of class files; testng jar file path" org.testng.TestNG testng.xml
ex:-
java -cp ".\bin;..\common_lib\*;" org.testng.TestNG testng.xml
The simplest and the most efficient way is to use an uber plugin like this:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
<configuration>
<finalName>uber-${project.artifactId}-${project.version}</finalName>
</configuration>
</plugin>
You will have de-normalized all in one JAR file.
Turns out I will missing a class called mysql-connector-java-5.1.2.jar, I added it this folder (C:\Program Files\pentaho\design-tools\data-integration\lib) and it worked with a MySQL connection and my data and tables appear.
Might be you forgotten to place the Main class and Test Case class in /src/test/java. Check it Once.
These guys gave you the reason why is failing but not how to solve it. This problem may appear even if you have a jdk which matches JVM which you are trying it into.
Project -> Properties -> Java Compiler
Enable project specific settings.
Then select Compiler Compliance Level to 1.6 or 1.5, build and test your app.
Now, it should be fine.
I solved by following these steps:
This fixes the "Deployment Assembly" settings of the project.
You can use jackson library and simply use these 3 lines to convert your json file to Java Object.
ObjectMapper mapper = new ObjectMapper();
InputStream is = Test.class.getResourceAsStream("/test.json");
testObj = mapper.readValue(is, Test.class);
For Eclipse compiler to work properly you need to remove final/src from the source path and add final/src/main/java instead. This may also solve your problem as now the build directory won't be inside the Java source folder.
In my environment, I just added the two files to class path. And is work fine.
slf4j-jdk14-1.7.25.jar
slf4j-api-1.7.25.jar
This is due to Morphia jar not being part of your output war/jar. Eclipse or local build includes them as part of classpath, but remote builds or auto/scheduled build don't consider them part of classpath.
You can include dependent jars using plugin.
Add below snippet into your pom's plugins section
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
This one is for all the Maven users out there, using their dependencies for the classpath and not copying them into /WEB-INF/lib:
just add this (which copies the dependency libraries) before </plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>process-sources</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>WebContent/WEB-INF/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
I solved it. I ran:
JAVA_HOME=/usr/lib/jvm/java-7-openjdk-i386
The error is misleading, Unsupported major.minor version 51.0
. This gives the impression that version 51 (Java 7) is not supported. And we should use Java 6.
The error should have been:
The current Java version, 50, is unsupported. Use Java version 7 (51:0 and greater) instead.`
EDIT
With the content of your XML, I can see that you use a ScrollView. If you want to use your custom view, you must write com.your.packagename.ScrollViewExt and you will be able to use it in your code.
<com.your.packagename.ScrollViewExt
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<WebView
android:id="@+id/textterms"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:textColor="@android:color/black" />
</com.your.packagename.ScrollViewExt>
EDIT END
Could you post the xml content ?
I think that you could simply add a scroll listener and check if the last item showed is the lastest one from the listview like :
mListView.setOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
if(view.getLastVisiblePosition()==(totalItemCount-1)){
//dosomething
}
}
});
I had the same issue on the Linux server I was working on. Connecting java to a X11 display worked on the head node, but not on any other. After contacting the administrator, it turned out that the current version of our job-scheduling system (SLURM) did not support X11 forwarding. They had to update SLURM (newer versions of SLURM support it) for it to work.
<activity
android:name="MyBookActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.ALTERNATIVE" />
</intent-filter>
</activity>
where is your dot before MyBookActivity?
Edit the build path in this order, this worked for me.
Make sure the /gen
is before /src
after creating the view we have to add layout parameters .
change like this
TextView tv = new TextView(this);
tv.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
llview.addView(tv);
tv.setTextColor(Color.WHITE);
tv.setTextSize(2,25);
tv.setText(chat);
if (mine) {
leftMargin = 5;
tv.setBackgroundColor(0x7C5B77);
}
else {
leftMargin = 50;
tv.setBackgroundColor(0x778F6E);
}
final ViewGroup.MarginLayoutParams lpt =(MarginLayoutParams)tv.getLayoutParams();
lpt.setMargins(leftMargin,lpt.topMargin,lpt.rightMargin,lpt.bottomMargin);
I was facing the same issue. In my case, I had a dependency of httpclient with an older version while sendgrid required a newer version of httpclient. Just make sure that the version of httpclient is correct in your dependencies and it would work fine.
The column in the database is probably a DECIMAL
. You should process it as a BigInteger
, not an Integer
, otherwise you are losing digits. Or else change the column to int
.
Use the doubleNumber.intValue();
method.
In your case don't need casting, you need call toString().
Integer i = 33;
String s = i.toString();
//or
s = String.valueOf(i);
//or
s = "" + i;
Casting. How does it work?
Given:
class A {}
class B extends A {}
(A)
|
(B)
B b = new B(); //no cast
A a = b; //upcast with no explicit cast
a = (A)b; //upcast with an explicit cast
b = (B)a; //downcast
A and B in the same inheritance tree and we can this:
a = new A();
b = (B)a; // again downcast. Compiles but fails later, at runtime: java.lang.ClassCastException
The compiler must allow things that might possibly work at runtime. However, if the compiler knows with 100% that the cast couldn't possibly work, compilation will fail.
Given:
class A {}
class B1 extends A {}
class B2 extends A {}
(A)
/ \
(B1) (B2)
B1 b1 = new B1();
B2 b2 = (B2)b1; // B1 can't ever be a B2
Error: Inconvertible types B1 and B2. The compiler knows with 100% that the cast couldn't possibly work. But you can cheat the compiler:
B2 b2 = (B2)(A)b1;
but anyway at runtime:
Exception in thread "main" java.lang.ClassCastException: B1 cannot be cast to B2
in your case:
(Object)
/ \
(Integer) (String)
Integer i = 33;
//String s = (String)i; - compiler error
String s = (String)(Object)i;
at runtime: Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
When I ran into this error the fix was simple. I was simply missing a setter for a property. Make sure you define matching getters / setters for all your properties.
Comparable
is Fegan
.The method compareTo
you are overidding in it should have a Fegan
object as a parameter whereas you are casting it to a FoodItems
. Your compareTo
implementation should describe how a Fegan
compare to another Fegan
.
FoodItems
implement Comparable
aswell and copy paste your actual compareTo
logic in it.1)In Manifest file mention your activity name and action for it and also category . 2)In your Activity mention your starting contentview and mention your view id's in the activity.
I know im very late to answer this. But it will help others, I was also stucked on this.
Here is what i did to get it work.
String[] namesArr = (String[]) names.toArray(new String[names.size()]);
I had the same problem, What helped me was:
Done .
Sounds like you need to change the path to your java
executable to match the newest version.
Basically, installing the latest Java does not necessarily mean your machine is configured to use the latest version. You didn't mention any platform details, so that's all I can say.
According to the stack trace, your issue is that your app cannot find org.apache.commons.dbcp.BasicDataSource
, as per this line:
java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource
I see that you have commons-dbcp in your list of jars, but for whatever reason, your app is not finding the BasicDataSource
class in it.
Convert an integer directly to long by adding 'L' to the end of Integer.
Long i = 1234L;
You need to use a ServerSocket
. You can find an explanation here.
Put <packaging>war</packaging>
in your pom.xml if you are using Maven.
In that case, maybe it is with jar packaging
You must have Maven libs in Deployment Assembly
This can mean a lot of things, but the most common one is that the class contained in the file doesn't have the same name as the file itself. So, check if your class is also called HelloWorld2.
If you have a maven project try to run:
mvn clean compile
and then in eclipse clean & build your project.
System.setProperty("gate.home", "/some/directory");
After that you can retrieve its value later by calling
String value = System.getProperty("gate.home");
I had the same problem when developing a KNIME Node/plugin in the Eclipse environment. The solution was not only to add the gson.jar as an externar JAR to the build path, it was also required to go to plugin.xml
, then the Dependencies tab and add com.google.gson as a required plugin.
query.setParameterList("name", new String[] { "Ron", "Som", "Roxi"}); fixed my issue
Also if you're retrieving something from intent
of another activity using getIntent
in the current activity and setting those retrieved data before/above onCreate
then this exception is thrown.
For eg. if i retrieve a string like this
final String slot1 = getIntent().getExtras().getString("Slot1");
and put this line of code before/above onCreate
then this exception is thrown.
Had the same error: java.lang.RuntimeException: Unable to instantiate activity (classnotfound) FIRST try to change the build platform (2.3.3 -> 2.2 -> 2.3.3) worked for me.
Cheesle is right. There's no way for the classloader to find the embedded jars. If you put enough debug commands on the command line you should be able to see the 'java' command failing to add the jars to a classpath
What you want to make is sometimes called an 'uberjar'. I found one-jar as a tool to help make them, but I haven't tried it. Sure there's many other approaches.
i had the same error while working with hibernate, i had added below dependency in my pom.xml that solved the problem
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.10</version>
</dependency>
reference https://mvnrepository.com/artifact/org.slf4j/slf4j-api
Ensure that your 3rd party jars are in your projects "libs" folder and they will be put in the .apk when you package your application. You may see runtime errors on the device if something in the jar is not supported, but other than that I have had great success with this.
Have you tried (from a command line)
java -jar jbpm-installer-3.2.7.jar
or double clicking it with the mouse ?
Found this and this by googling.
Hope it helps
To avoid x !instance of Long
prob
Add
<property name="openjpa.Compatibility" value="StrictIdentityValues=false"/>
in your persistence.xml
You might be launching your application from a Product file which is not linked to the plugin file. Reset your workspace and launch using the MANIFEST.MF > Overview > Testing > Launch.
Hope this helps...
class SomeClass{
//Code snippet here...
}
Code snippet 1: Absolutely OK - all checked exceptions handled
static void m1(){
try{
throw new Exception();
} catch(Exception e){
System.out.println(e);
}
}
static{
m1();
}
Code snippet 2: Won't compile - unreported checked exception
static void m1() throws Exception{
throw new Exception();
}
static{
m1();
}
Code snippet 3: OK (see code snippet 1)
static void m1() throws Exception{
throw new Exception();
}
static{
try{m1();}
catch(Exception e){
System.out.println(e);
//or whatever
}
}
Code snippet 4: Compilation error, initilalizer must be able to complete normally
static{
throw new RuntimeException();
}
Basically it boils down to this:
This makes sense as A CLASS SHOULD BE ABLE TO COMPLETE INITIALIZATION NORMALLY. If this happens to be a problem, this should be categorized as an Error (from which recovery is usually difficult or impossible) rather than an Exception (which is usually recoverable)...
I have same problem!
Found following in oracle site link text
As mentioned above, the 11.1 drivers by default convert SQL DATE to Timestamp when reading from the database. This always was the right thing to do and the change in 9i was a mistake. The 11.1 drivers have reverted to the correct behavior. Even if you didn't set V8Compatible in your application you shouldn't see any difference in behavior in most cases. You may notice a difference if you use getObject to read a DATE column. The result will be a Timestamp rather than a Date. Since Timestamp is a subclass of Date this generally isn't a problem. Where you might notice a difference is if you relied on the conversion from DATE to Date to truncate the time component or if you do toString on the value. Otherwise the change should be transparent.
If for some reason your app is very sensitive to this change and you simply must have the 9i-10g behavior, there is a connection property you can set. Set mapDateToTimestamp to false and the driver will revert to the default 9i-10g behavior and map DATE to Date.
Hey i have checked your code, there is no serious error in your code. this is complete code:
main.xml:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:id="@+id/info"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
this is Stackoverflow.java
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;
public class Stackoverflow extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View linearLayout = findViewById(R.id.info);
//LinearLayout layout = (LinearLayout) findViewById(R.id.info);
TextView valueTV = new TextView(this);
valueTV.setText("hallo hallo");
valueTV.setId(5);
valueTV.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
((LinearLayout) linearLayout).addView(valueTV);
}
}
copy this code, and run it. it is completely error free. take care...
This because the input that the user inserts into the JOptionPane
is a String
and it is stored and returned as a String
.
Java cannot convert between strings and number by itself, you have to use specific functions, just use:
int ans = Integer.parseInt(JOptionPane.showInputDialog(...))
We face this error when permanent generation heap is full and some of us we use command prompt to build our maven project in windows. since we need to increase heap size, we could set our environment variable @ControlPanel/System and Security/System and there you click on Change setting and select Advanced and set Environment variable as below
I have also faced same problem....
Actually this problem is raised due to the fact that your program .class
files are not saved in that directory. Remove your CLASSPATH from your environment variable (you do no need to set classpath for simple Java programs) and reopen cmd prompt, then compile and execute.
If you observe carefully your .class
file will save in the same location. (I am not an expert, I am also basic programer if there is any mistake in my sentences please ignore it :-))
This question has lasted for a long time but I want to pitch in something. I have been working on a Spring project challenge and I discovered that in Eclipse IDE. If you are using Maven or Gradle for Spring Boot Rest APIs, you have to remove the Junit 4 or 5 in the build path and include Junit in your pom.xml or Gradle build file. I guess that applies to yml configuration file too.
MySQL JDBC Connection with useSSL.
private String db_server = BaseMethods.getSystemData("db_server");
private String db_user = BaseMethods.getSystemData("db_user");
private String db_password = BaseMethods.getSystemData("db_password");
private String connectToDb() throws Exception {
String jdbcDriver = "com.mysql.jdbc.Driver";
String dbUrl = "jdbc:mysql://" + db_server +
"?verifyServerCertificate=false" +
"&useSSL=true" +
"&requireSSL=true";
System.setProperty(jdbcDriver, "");
Class.forName(jdbcDriver).newInstance();
Connection conn = DriverManager.getConnection(dbUrl, db_user, db_password);
Statement statement = conn.createStatement();
String query = "SELECT EXTERNAL_ID FROM offer_letter where ID =" + "\"" + letterID + "\"";
ResultSet resultSet = statement.executeQuery(query);
resultSet.next();
return resultSet.getString(1);
}
public static Comparator<JobSet> JobEndTimeComparator = new Comparator<JobSet>() {
public int compare(JobSet j1, JobSet j2) {
int cost1 = j1.cost;
int cost2 = j2.cost;
return cost1-cost2;
}
};
I've designed and implemented Dollar for this kind of tasks:
String[] strarray= $(strlist).toArray();
Ok, after had the same issue and after reading some answers here and other places. it seems that putting external lib
into WEB-INF/lib
is not that good idea as it pollute webapp/JRE libs with server-specific libraries
- for more information check this answer"
Another solution that i do NOT recommend is: to copy it into tomcat/lib folder. although this may work, it will be hard to manage dependency for a shared(git for example) project.
Create vendor
folder. put there all your external lib. then, map this folder as dependency to your project. in eclipse you need to
build path
Project Properties
-> Java build path
Libraries
-> add external lib or any other solution to add your files/folderdeployment Assembly
(reference)
Project Properties
-> Deployment Assembly
Add
-> Java Build Path Entries
Use maven
(or any alternative) to manage project dependency
package pac001;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Entry_box{
public static final String[] relationship = {"Marrid", "Unmarried"};
public static void main(String[] args)
{
//TAKING USER ID NUMBER
int a = Integer.parseInt(JOptionPane.showInputDialog("Enter ID no: "));
// TAKING INPUT FOR RELATIONSHIP
JFrame frame = new JFrame("Input Dialog Example #3");
String Relationship = (String) JOptionPane.showInputDialog(frame,"Select Your Relationship","Married",
JOptionPane.QUESTION_MESSAGE, null, relationship,relationship[0]);
//PRINTING THE ID NUMBER
System.out.println("ID no: "+a);
// PRINTING RESULT FOR RELATIONSHIP INPUT
System.out.printf("Mariitual Status: %s\n", Relationship);
}
}
I got the same error and the cause was the directory:
U:.....WEB\WebRoot\WEB-INF\classes\com\yourcompany\cc\dao
was corrupted(directory or file not readable or damaged).. solved with
both the problem will be because of classpathref="master-classpath", please check the value is correct
Try this code
Convert ArrayList to Collection
ArrayList<User> usersArrayList = new ArrayList<User>();
Collection<User> userCollection = new HashSet<User>(usersArrayList);
Convert Collection to ArrayList
Collection<User> userCollection = new HashSet<User>(usersArrayList);
List<User> userList = new ArrayList<User>(userCollection );
If you're using Maven, just follow the maven-war-plugin
documentation about "How do I create a JAR containing the classes in my webapp?": add <attachClasses>true</attachClasses>
to the <configuration>
of the plugin:
<project>
...
<artifactId>mywebapp</artifactId>
<version>1.0-SNAPSHOT</version>
...
<build>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<attachClasses>true</attachClasses>
</configuration>
</plugin>
</plugins>
</build>
...
</project>
The you will have 2 products in the target/
folder:
project.war
itselfproject-classes.jar
which contains all the compiled classes in a jarThen you will be able to execute a main class using classic method: java -cp target/project-classes.jar 'com.mycompany.MainClass' param1 param2
I have the same problem but I found this after a long search: http://www.herongyang.com/JDBC/MySQL-JDBC-Driver-Load-Class.html
But I made some change. I put the driver in the same folder as my ConTest.java
file,
and compile it, resulting in ConTest.class
.
So in this folder have
ConTest.class
mysql-connector-java-5.1.14-bin.jar
and I write this
java -cp .;mysql-connector-java-5.1.14-bin.jar ConTest
This way if you not use any IDE just cmd in windows or shell in linux.
Class.cast()
is rarely ever used in Java code. If it is used then usually with types that are only known at runtime (i.e. via their respective Class
objects and by some type parameter). It is only really useful in code that uses generics (that's also the reason it wasn't introduced earlier).
It is not similar to reinterpret_cast
, because it will not allow you to break the type system at runtime any more than a normal cast does (i.e. you can break generic type parameters, but can't break "real" types).
The evils of the C-style cast operator generally don't apply to Java. The Java code that looks like a C-style cast is most similar to a dynamic_cast<>()
with a reference type in Java (remember: Java has runtime type information).
Generally comparing the C++ casting operators with Java casting is pretty hard since in Java you can only ever cast reference and no conversion ever happens to objects (only primitive values can be converted using this syntax).
Issue solved by adding commons-logging.jar
Imp files are ,
antlr-runtime-3.0.1
org.springframework.aop-3.1.0.M2
org.springframework.asm-3.1.0.M2
org.springframework.aspects-3.1.0.M2
org.springframework.beans-3.1.0.M2
org.springframework.context.support-3.1.0.M2
org.springframework.context-3.1.0.M2
org.springframework.core-3.1.0.M2
org.springframework.expression-3.1.0.M2
commons-logging-1.1.1
If you are using netbeans Download the sqlitejdbc driver Right click the Libraries folder from the Project window and select Add Library , then click on the Create button enter the Library name (SQLite) and hit OK
You have to add the sqlitejdbc driver to the class path , click on the Add Jar/Folder.. button and select the sqlitejdbc file you've downloaded previously Hit OK and you are ready to go !
If you have in your java source
package mypackage;
and your class is hello.java with
public class hello {
and in that hello.java you have
public static void main(String[] args) {
Then (after compilation) changeDir (cd) to the directory where your hello.class is. Then
java -cp . mypackage.hello
Mind the current directory and the package name before the class name. It works for my on linux mint and i hope on the other os's also
Thanks Stack overflow for a wealth of info.
Use java.utils.Arrays:
public int getTheNumber(int[] factors) {
int[] f = (int[])factors.clone();
Arrays.sort(f);
return f[0]*f[(f.length-1];
}
Or if you want to be efficient avoid all the object allocation just actually do the work:
public static int getTheNumber(int[] array) {
if (array.length == 0)
throw new IllegalArgumentException();
int min = array[0];
int max = array[0];
for (int i = 1; i< array.length;++i) {
int v = array[i];
if (v < min) {
min = v;
} else if (v > max) {
max = v;
}
}
return min * max;
}
Or do the following:
...
Integer[] integerArray = new Integer[integerList.size()];
integerList.toArray(integerArray);
return integerArray;
}
I solve that Bulit path--->libraries--->add library--->Junit check junit4
for me that issue happened because i generated .jks file on my laptop with 1.8.0_251 and i copied it on server witch had java 1.8.0_45 and when I used that .jks file in my code i got java.io.IOException: Invalid Keystore format.
to solve this issue i generated .jks file directly on the server instead of copy there from my laptop which had different java version.
Another alternative to System.arraycopy
:
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
You can use all functions from Long, if you put the number into "(" ")". That way you can cast the long to an int:
<c:out value="${map[(1).intValue()]}"/>
First - I have to direct you to http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html -- she does an amazing job.
The basic idea is that you use
<T extends SomeClass>
when the actual parameter can be SomeClass
or any subtype of it.
In your example,
Map<String, Class<? extends Serializable>> expected = null;
Map<String, Class<java.util.Date>> result = null;
assertThat(result, is(expected));
You're saying that expected
can contain Class objects that represent any class that implements Serializable
. Your result map says it can only hold Date
class objects.
When you pass in result, you're setting T
to exactly Map
of String
to Date
class objects, which doesn't match Map
of String
to anything that's Serializable
.
One thing to check -- are you sure you want Class<Date>
and not Date
? A map of String
to Class<Date>
doesn't sound terribly useful in general (all it can hold is Date.class
as values rather than instances of Date
)
As for genericizing assertThat
, the idea is that the method can ensure that a Matcher
that fits the result type is passed in.
There are many ways to do this. I did something below convenient to me and always works fine.
On the server, .Xauthority file is generated and notice that the DISPLAY variable is already set.
$ xauth list
$ xauth add
To test it, type xclock or xeyes
Note: To switch user, copy the .Xauthority file to the home directory of the respective user and also export the DISPLAY variable from that user.
To do downcasting in Java, and avoid run-time exceptions, take a reference of the following code:
if (animal instanceof Dog) {
Dog dogObject = (Dog) animal;
}
Here, Animal is the parent class and Dog is the child class.
instanceof is a keyword that is used for checking if a reference variable is containing a given type of object reference or not.
i had the same problem with my jar the solution
Manifest-Version: 1.0
Sealed: true
Class-Path: . lib/jarX1.jar lib/jarX2.jar lib/jarX3.jar
Main-Class: com.MainClass
select export all outpout folders for checked project
This worked for me :)
This page may give you some hints - http://www.zanthan.com/itymbi/archives/000337.html
There may be a subtle bug in the body of that method that javac fails to spot. Difficult to diagnose unless you post the whole method here.
You could start by declaring as many variables as possible as final... that would have caught the bug mentioned on the zanthan site, and is often a good practice anyways.
A couple of additional points re use of vector
here.
Unlike ArrayList
and Array
in Java, you don't need to do anything special to treat a vector
as an array - the underlying storage in C++ is guaranteed to be contiguous and efficiently indexable.
Unlike ArrayList
, a vector
can efficiently hold primitive types without encapsulation as a full-fledged object.
When removing items from a vector
, be aware that the items above the removed item have to be moved down to preserve contiguous storage. This can get expensive for large containers.
Make sure if you store complex objects in the vector
that their copy constructor and assignment operators are efficient. Under the covers, C++ STL uses these during container housekeeping.
Advice about reserve()
ing storage upfront (ie. at vector construction or initialilzation time) to minimize memory reallocation on later extension carries over from Java to C++.
document.activeElement.blur();
Works wrong on IE9 - it blurs the whole browser window if active element is document body. Better to check for this case:
if (document.activeElement != document.body) document.activeElement.blur();
remove the margin for the h4 tag
h4 {
margin:0px;
}
Fiddle link
The simplest is using the OpenCV Mat class:
img=cv::Scalar(blue_value, green_value, red_value);
where img
was defined as a cv::Mat
.
dateTimePicker1.Value = DateTime.Today();
I would use the DateTime.TryParse() method: http://msdn.microsoft.com/en-us/library/system.datetime.tryparse.aspx
I'm amazed nobody has mentioned Pragmata. It's the BMW of programming fonts. Condensed, readable, and the pinnacle of simple elegance.
alt text http://www.fsd.it/fonts/imm/pr_abc.gif
There is now a fundraising project going on for PragmataPro (which covers a larger portion of Unicode than Pragmata) to make it available for free under a Creative Commons license!
http://example.com/subdir/?lold=13666
=> http://www.example.com/subdir/?lold=13666
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Visual C++ Redistributable for VS2012
VSU_4\vcredist_x64.exe
or VSU_4\vcredist_x84.exe
depending upon your system configurationdll
files inside the lib
folder, along with your other libraries (eg \lib\win32-x86\your dll files
).I needed to update/upsert a document into one collection, what I did was to create a new object literal like this:
notificationObject = {
user_id: user.user_id,
feed: {
feed_id: feed.feed_id,
channel_id: feed.channel_id,
feed_title: ''
}
};
composed from data that I get from somewhere else in my database and then call update on the Model
Notification.update(notificationObject, notificationObject, {upsert: true}, function(err, num, n){
if(err){
throw err;
}
console.log(num, n);
});
this is the ouput that I get after running the script for the first time:
1 { updatedExisting: false,
upserted: 5289267a861b659b6a00c638,
n: 1,
connectionId: 11,
err: null,
ok: 1 }
And this is the output when I run the script for the second time:
1 { updatedExisting: true, n: 1, connectionId: 18, err: null, ok: 1 }
I'm using mongoose version 3.6.16
Use getDeclaredMethod()
to get a private Method object and then use method.setAccessible()
to allow to actually call it.
use this
@Temporal(TemporalType.TIMESTAMP)
@Column(name="create_date")
private Calendar createDate;
public Calendar getCreateDate() {
return createDate;
}
public void setCreateDate(Calendar createDate) {
this.createDate = createDate;
}
Lazy simple version for forgetfuls like me:
git rebase -i HEAD~3
or however many commits instead of 3.
Turn this
pick YourCommitMessageWhatever
pick YouGetThePoint
pick IdkManItsACommitMessage
into this
pick YourCommitMessageWhatever
s YouGetThePoint
s IdkManItsACommitMessage
and do some action where you hit esc
then enter
to save the changes. [1]
When the next screen comes up, get rid of those garbage # lines [2] and create a new commit message or something, and do the same escape
enter
action. [1]
Wowee, you have fewer commits. Or you just broke everything.
[1] - or whatever works with your git configuration. This is just a sequence that's efficient given my setup.
[2] - you'll see some stuff like # this is your n'th commit
a few times, with your original commits right below these message. You want to remove these lines, and create a commit message to reflect the intentions of the n commits that you're combining into 1.
To disable all form, as easy as write:
jQuery 1.6+
$("#form :input").prop("disabled", true);
jQuery 1.5 and below
$("#form :input").attr('disabled','disabled');
For me, this helped: I checked locale on my local shell in terminal
$ locale
LANG="cs_CZ.UTF-8"
LC_COLLATE="cs_CZ.UTF-8"
Then connected to any remote host I am using via ssh and edited file /etc/profile as root - at the end I added line:
export LANG=cs_CZ.UTF-8
After next connection it works fine in bash, ls and nano.
You need to define the enum outside of the class.
public enum card_suits
{
Clubs,
Hearts,
Spades,
Diamonds
}
public class Card
{
// ...
That being said, you may also want to consider using the standard naming guidelines for Enums, which would be CardSuit instead of card_suits, since Pascal Casing is suggested, and the enum is not marked with the FlagsAttribute, suggesting multiple values are appropriate in a single variable.
Have you tried:
SELECT Cast( 2.555 as decimal(53,8))
This would return 2.55500000
. Is that what you want?
UPDATE:
Apparently you can also use SQL_VARIANT_PROPERTY to find the precision and scale of a value. Example:
SELECT SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Precision'),
SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Scale')
returns 8|7
You may be able to use this in your conversion process...
I tried most of these solutions but ran into problems leaving and coming back with another fragment it wouldn't work, so I did something a bit different that works 100%, and gets rid of the ugly hash in the URL.
tl;dr here's a better way than what I've seen so far.
import { Component, OnInit, AfterViewChecked, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'app-hero',
templateUrl: './hero.component.html',
styleUrls: ['./hero.component.scss']
})
export class HeroComponent implements OnInit, AfterViewChecked, OnDestroy {
private fragment: string;
fragSub: Subscription;
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.fragSub = this.route.fragment.subscribe( fragment => { this.fragment = fragment; })
}
ngAfterViewChecked(): void {
try {
document.querySelector('#' + this.fragment).scrollIntoView({behavior: 'smooth'});
window.location.hash = "";
} catch (e) { }
}
ngOnDestroy() {
this.fragSub.unsubscribe();
}
}
I thought it could be worthwhile to have a micro-benchmark comparing the run-times of the different approaches mentioned here.
Disclaimer: I'm using simple_benchmark
(a library written by me) for the benchmarks and also include iteration_utilities.count_items
(a function in a third-party-library written by me).
To provide a more differentiated result I've done two benchmarks, one only including the approaches that don't build an intermediate container just to throw it away and one including these:
from simple_benchmark import BenchmarkBuilder
import more_itertools as mi
import iteration_utilities as iu
b1 = BenchmarkBuilder()
b2 = BenchmarkBuilder()
@b1.add_function()
@b2.add_function()
def summation(it):
return sum(1 for _ in it)
@b1.add_function()
def len_list(it):
return len(list(it))
@b1.add_function()
def len_listcomp(it):
return len([_ for _ in it])
@b1.add_function()
@b2.add_function()
def more_itertools_ilen(it):
return mi.ilen(it)
@b1.add_function()
@b2.add_function()
def iteration_utilities_count_items(it):
return iu.count_items(it)
@b1.add_arguments('length')
@b2.add_arguments('length')
def argument_provider():
for exp in range(2, 18):
size = 2**exp
yield size, [0]*size
r1 = b1.run()
r2 = b2.run()
import matplotlib.pyplot as plt
f, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=[15, 18])
r1.plot(ax=ax2)
r2.plot(ax=ax1)
plt.savefig('result.png')
The results were:
It uses log-log-axis so that all ranges (small values, large values) can be inspected. Since the plots are intended for qualitative comparison the actual values aren't too interesting. In general the y-axis (vertical) represents the time and the x-axis (horizontal) represents the number of elements in the input "iterable". Lower on the vertical axis means faster.
The upper plot shows the approaches where no intermediate list was used. Which shows that the iteration_utilities
approach was fastest, followed by more_itertools
and the slowest was using sum(1 for _ in iterator)
.
The lower plot also included the approaches that used len()
on an intermediate list, once with list
and once with a list comprehension. The approach with len(list)
was fastest here, but the difference to the iteration_utilities
approach is almost negligible. The approach using the comprehension was significantly slower than using list
directly.
Any approach mentioned here did show a dependency on the length of the input and iterated over ever element in the iterable. There is no way to get the length without the iteration (even if the iteration is hidden).
If you don't want third-party extensions then using len(list(iterable))
is definitely the fastest approach of the tested approaches, it however generates an intermediate list which could use significant more memory.
If you don't mind additional packages then iteration_utilities.count_items
would be almost as fast as the len(list(...))
function but doesn't require additional memory.
However it's important to note that the micro-benchmark used a list as input. The result of the benchmark could be different depending on the iterable you want to get the length of. I also tested with range
and a simple genertor-expression and the trends were very similar, however I cannot exclude that the timing won't change depending on the type of input.
First Method:(if STS is available in eclipse)
1.right click on project->run as ->Spring Boot app.
Second Method:
1.right click on project->run as ->run configuration
2. set base directory of you project ie.${workspace_loc:/first}
3. set goal spring-boot:run
4. Run
Third Method:
1.Right click on @SpringBootApplication annotation class ->Run as ->Java Application
It ignores the cached content when refreshing...
https://support.google.com/a/answer/3001912?hl=en
F5 or Control + R = Reload the current page
Control+Shift+R or Shift + F5 = Reload your current page, ignoring cached content
You can use 'category_name' in parameters. http://codex.wordpress.org/Template_Tags/get_posts
Note: The category_name parameter needs to be a string, in this case, the category name.
I was impatient and chose not to wait for answers... for reference it doesn't look that hard to do something like this (which works for my application, I don't need to worry about escaped quotes, as the stuff in quotes is limited to a few constrained forms):
final static private Pattern splitSearchPattern = Pattern.compile("[\",]");
private List<String> splitByCommasNotInQuotes(String s) {
if (s == null)
return Collections.emptyList();
List<String> list = new ArrayList<String>();
Matcher m = splitSearchPattern.matcher(s);
int pos = 0;
boolean quoteMode = false;
while (m.find())
{
String sep = m.group();
if ("\"".equals(sep))
{
quoteMode = !quoteMode;
}
else if (!quoteMode && ",".equals(sep))
{
int toPos = m.start();
list.add(s.substring(pos, toPos));
pos = m.end();
}
}
if (pos < s.length())
list.add(s.substring(pos));
return list;
}
(exercise for the reader: extend to handling escaped quotes by looking for backslashes also.)
By default WampServer is installed to port 80 which is already used by IIS. To set WampServer to use an open port, left click on the WampServer icon in the system tray and go to Apache > httpd.conf
Open the httpd.conf in Notepad. press ctrl+f and search for "Listen 80", change this line to "Listen 8080" (u can change this port as what you want), and then close and save the httpd.conf file.
Open a web browser and enter "[];, this will open the WampServer configuration page where you can configure Apache, MySQL, and PHP.
and some times this problem may occur because of skype also use 80 as default port hope this will help
XCODE 10.1
1. Goto Xcode -> Preferences (Shortcut CMD,)
2. Select Components
3. Download Simulator version
4. XCode -> Open Developer Tool -> Simulator This will launch Simulator as stand alone application
5 Hardware -> Device -> Manage Devices...
6. Click on + iCon to create new simulator version.
7. Specify Simulator Name, Device Type and Choose OS version from drop down.
8. Click Create.
9. Hardware -> Device -> iOS 11.0 -> iPhone 6
Thats it run enjoy coding!
It's actually a sensible question. Here's the answer from Excel 2010 help:
"The Workbook object is a member of the Workbooks collection. The Workbooks collection contains all the Workbook objects currently open in Microsoft Excel."
So, since that workbook isn't open - at least I assume it isn't - it can't be set as a workbook object. If it was open you'd just set it like:
Set wbk = workbooks("Master Benchmark Data Sheet.xlsx")
I had the same issue, to solve it just add exactly the same parameter name to your parameter collection as in your stored procedures.
Example
Let's say you create a stored procedure:
create procedure up_select_employe_by_ID
(@ID int)
as
select *
from employe_t
where employeID = @ID
So be sure to name your parameter exactly as it is in your stored procedure this would be
cmd.parameter.add("@ID", sqltype,size).value = @ID
if you go
cmd.parameter.add("@employeID", sqltype,size).value = @employeid
then the error happens.
You should remember if you want to use the Firefox only solution, if you want to add it to the whole document you should add contextmenu="mymenu"
to the <html>
tag not to the body
tag.
You should pay attention to this.
As of C++11, the memory-safe way to do this (still using a similar construction) is with std::unique_ptr
:
std::unique_ptr<int[]> array(new int[n]);
This creates a smart pointer to a memory block large enough for n
integers that automatically deletes itself when it goes out of scope. This automatic clean-up is important because it avoids the scenario where your code quits early and never reaches your delete [] array;
statement.
Another (probably preferred) option would be to use std::vector
if you need an array capable of dynamic resizing. This is good when you need an unknown amount of space, but it has some disadvantages (non-constant time to add/delete an element). You could create an array and add elements to it with something like:
std::vector<int> array;
array.push_back(1); // adds 1 to end of array
array.push_back(2); // adds 2 to end of array
// array now contains elements [1, 2]
I am joining the choir recommending that you skip the now long outdated classes Date
, Calendar
, SimpleDateFormat
and friends. In particular I would warn against using the deprecated methods and constructors of the Date
class, like the Date(String)
constructor you used. They were deprecated because they don’t work reliably across time zones, so don’t use them. And yes, most of the constructors and methods of that class are deprecated.
While at the time you asked the question, Joda-Time was (from all I know) a clearly better alternative, time has moved on again. Today Joda-Time is a largely finished project, and its developers recommend you use java.time
, the modern Java date and time API, instead. I will show you how.
ZonedDateTime localTime = ZonedDateTime.now(ZoneId.systemDefault());
// Convert Local Time to UTC
OffsetDateTime gmtTime
= localTime.toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC);
System.out.println("Local:" + localTime.toString()
+ " --> UTC time:" + gmtTime.toString());
// Reverse Convert UTC Time to Local time
localTime = gmtTime.atZoneSameInstant(ZoneId.systemDefault());
System.out.println("Local Time " + localTime.toString());
For starters, note that not only is the code only half as long as yours, it is also clearer to read.
On my computer the code prints:
Local:2017-09-02T07:25:46.211+02:00[Europe/Berlin] --> UTC time:2017-09-02T05:25:46.211Z
Local Time 2017-09-02T07:25:46.211+02:00[Europe/Berlin]
I left out the milliseconds from the epoch. You can always get them from System.currentTimeMillis();
as in your question, and they are independent of time zone, so I didn’t find them intersting here.
I hesitatingly kept your variable name localTime
. I think it’s a good name. The modern API has a class called LocalTime
, so using that name, only not capitalized, for an object that hasn’t got type LocalTime
might confuse some (a LocalTime
doesn’t hold time zone information, which we need to keep here to be able to make the right conversion; it also only holds the time-of-day, not the date).
Your conversion from local time to UTC was incorrect and impossible
The outdated Date
class doesn’t hold any time zone information (you may say that internally it always uses UTC), so there is no such thing as converting a Date
from one time zone to another. When I just ran your code on my computer, the first line it printed, was:
Local:Sat Sep 02 07:25:45 CEST 2017,1504329945967 --> UTC time:Sat Sep 02 05:25:45 CEST 2017-1504322745000
07:25:45 CEST
is correct, of course. The correct UTC time would have been 05:25:45 UTC
, but it says CEST
again, which is incorrect.
Now you will never need the Date
class again, :-) but if you were ever going to, the must-read would be All about java.util.Date on Jon Skeet’s coding blog.
Question: Can I use the modern API with my Java version?
If using at least Java 6, you can.
Complete guide related to Screen sizes
JavaScript
For height:
document.body.clientHeight // Inner height of the HTML document body, including padding
// but not the horizontal scrollbar height, border, or margin
screen.height // Device screen height (i.e. all physically visible stuff)
screen.availHeight // Device screen height minus the operating system taskbar (if present)
window.innerHeight // The current document's viewport height, minus taskbars, etc.
window.outerHeight // Height the current window visibly takes up on screen
// (including taskbars, menus, etc.)
Note: When the window is maximized this will equal screen.availHeight
For width:
document.body.clientWidth // Full width of the HTML page as coded, minus the vertical scroll bar
screen.width // Device screen width (i.e. all physically visible stuff)
screen.availWidth // Device screen width, minus the operating system taskbar (if present)
window.innerWidth // The browser viewport width (including vertical scroll bar, includes padding but not border or margin)
window.outerWidth // The outer window width (including vertical scroll bar,
// toolbars, etc., includes padding and border but not margin)
Jquery
For height:
$(document).height() // Full height of the HTML page, including content you have to
// scroll to see
$(window).height() // The current document's viewport height, minus taskbars, etc.
$(window).innerHeight() // The current document's viewport height, minus taskbars, etc.
$(window).outerHeight() // The current document's viewport height, minus taskbars, etc.
For width:
$(document).width() // The browser viewport width, minus the vertical scroll bar
$(window).width() // The browser viewport width (minus the vertical scroll bar)
$(window).innerWidth() // The browser viewport width (minus the vertical scroll bar)
$(window).outerWidth() // The browser viewport width (minus the vertical scroll bar)
C++17 inline
variables
This awesome C++17 feature allow us to:
constexpr
: How to declare constexpr extern?main.cpp
#include <cassert>
#include "notmain.hpp"
int main() {
// Both files see the same memory address.
assert(¬main_i == notmain_func());
assert(notmain_i == 42);
}
notmain.hpp
#ifndef NOTMAIN_HPP
#define NOTMAIN_HPP
inline constexpr int notmain_i = 42;
const int* notmain_func();
#endif
notmain.cpp
#include "notmain.hpp"
const int* notmain_func() {
return ¬main_i;
}
Compile and run:
g++ -c -o notmain.o -std=c++17 -Wall -Wextra -pedantic notmain.cpp
g++ -c -o main.o -std=c++17 -Wall -Wextra -pedantic main.cpp
g++ -o main -std=c++17 -Wall -Wextra -pedantic main.o notmain.o
./main
See also: How do inline variables work?
C++ standard on inline variables
The C++ standard guarantees that the addresses will be the same. C++17 N4659 standard draft 10.1.6 "The inline specifier":
6 An inline function or variable with external linkage shall have the same address in all translation units.
cppreference https://en.cppreference.com/w/cpp/language/inline explains that if static
is not given, then it has external linkage.
Inline variable implementation
We can observe how it is implemented with:
nm main.o notmain.o
which contains:
main.o:
U _GLOBAL_OFFSET_TABLE_
U _Z12notmain_funcv
0000000000000028 r _ZZ4mainE19__PRETTY_FUNCTION__
U __assert_fail
0000000000000000 T main
0000000000000000 u notmain_i
notmain.o:
0000000000000000 T _Z12notmain_funcv
0000000000000000 u notmain_i
and man nm
says about u
:
"u" The symbol is a unique global symbol. This is a GNU extension to the standard set of ELF symbol bindings. For such a symbol the dynamic linker will make sure that in the entire process there is just one symbol with this name and type in use.
so we see that there is a dedicated ELF extension for this.
C++17 standard draft on "global" const
implies static
This is the quote for what was mentioned at: https://stackoverflow.com/a/12043198/895245
C++17 n4659 standard draft 6.5 "Program and linkage":
3 A name having namespace scope (6.3.6) has internal linkage if it is the name of
- (3.1) — a variable, function or function template that is explicitly declared static; or,
- (3.2) — a non-inline variable of non-volatile const-qualified type that is neither explicitly declared extern nor previously declared to have external linkage; or
- (3.3) — a data member of an anonymous union.
"namespace" scope is what we colloquially often refer to as "global".
Annex C (informative) Compatibility, C.1.2 Clause 6: "basic concepts" gives the rationale why this was changed from C:
6.5 [also 10.1.7]
Change: A name of file scope that is explicitly declared const, and not explicitly declared extern, has internal linkage, while in C it would have external linkage.
Rationale: Because const objects may be used as values during translation in C++, this feature urges programmers to provide an explicit initializer for each const object. This feature allows the user to put const objects in source files that are included in more than one translation unit.
Effect on original feature: Change to semantics of well-defined feature.
Difficulty of converting: Semantic transformation.
How widely used: Seldom.
See also: Why does const imply internal linkage in C++, when it doesn't in C?
Tested in GCC 7.4.0, Ubuntu 18.04.
There are a bunch of good solutions here but I'd suggest going the other route with this. If searching is the most important thing and the 'secret' property is not used on the view at all; my approach for this would be to use the built-in angular filter with all its benefits and simply map the model to a new array of objects.
Example from the question:
$scope.people = members.map(function(member) {
return {
name: member.name,
phone: member.phone
}});
Now, in html simply use the regular filter to search both these properties.
<div ng-repeat="member in people | filter: searchString">
You either need to run "update-database" from the package manager console to push your changes to the database OR you can delete the pending migration file ([201203170856167_left]) from your Migrations folder and then re-run "add-migration" to create a brand new migration based off of your edits.
First of all you missed ScriptService attribute to add in webservice.
[ScriptService]
After then try following method to call webservice via JSON.
var webAddr = "http://Domain/VBRService.asmx/callJson"; var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr); httpWebRequest.ContentType = "application/json; charset=utf-8"; httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { string json = "{\"x\":\"true\"}"; streamWriter.Write(json); streamWriter.Flush(); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); return result; }
Lua implementation, for posterity:
function levenshtein_distance(str1, str2)
local len1, len2 = #str1, #str2
local char1, char2, distance = {}, {}, {}
str1:gsub('.', function (c) table.insert(char1, c) end)
str2:gsub('.', function (c) table.insert(char2, c) end)
for i = 0, len1 do distance[i] = {} end
for i = 0, len1 do distance[i][0] = i end
for i = 0, len2 do distance[0][i] = i end
for i = 1, len1 do
for j = 1, len2 do
distance[i][j] = math.min(
distance[i-1][j ] + 1,
distance[i ][j-1] + 1,
distance[i-1][j-1] + (char1[i] == char2[j] and 0 or 1)
)
end
end
return distance[len1][len2]
end
you need to understand difference between std::array::size and sizeof() operator. if you want loop to array elements in conventional way then you could use std::array::size. this will return number of elements in array but if you keen to use C++11 then prefer below code
for(const string &text : texts)
cout << "value of text: " << text << endl;
Here is a version that also checks for transparent, I needed this since my object was to insert the result into a style attribute, where the transparent version of a hex color is actually the word "transparent"..
function rgb2hex(rgb) {
if ( rgb.search("rgb") == -1 ) {
return rgb;
}
else if ( rgb == 'rgba(0, 0, 0, 0)' ) {
return 'transparent';
}
else {
rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
}
In Java, when you type a decimal number as 3.6
, its interpreted as a double
. double
is a 64-bit precision IEEE 754 floating point, while float
is a 32-bit precision IEEE 754 floating point. As a float
is less precise than a double
, the conversion cannot be performed implicitly.
If you want to create a float, you should end your number with f
(i.e.: 3.6f
).
For more explanation, see the primitive data types definition of the Java tutorial.
It is indeed possible.
Here is an example calling the Weather SOAP Service using plain requests lib:
import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
</SOAP-ENV:Envelope>"""
response = requests.post(url,data=body,headers=headers)
print response.content
Some notes:
application/soap+xml
is probably the more correct header to use (but the weatherservice prefers text/xml
For example:
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()
Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).
You can do the above with suds like so:
from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service
result = client.service.GetWeatherInformation()
print result
Note: when using suds, you will almost always end up needing to use the doctor!
Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:
sudo tcpdump -As 0
This can be helpful for inspecting the requests that actually go over the wire.
The above two code snippets are also available as gists:
Step 1: Create a Type as Table with name TableType that will accept a table having one varchar column
create type TableType
as table ([value] varchar(100) null)
Step 2: Create a function that will accept above declared TableType as Table-Valued Parameter and String Value as Separator
create function dbo.fn_get_string_with_delimeter (@table TableType readonly,@Separator varchar(5))
returns varchar(500)
As
begin
declare @return varchar(500)
set @return = stuff((select @Separator + value from @table for xml path('')),1,1,'')
return @return
end
Step 3: Pass table with one varchar column to the user-defined type TableType and ',' as separator in the function
select dbo.fn_get_string_with_delimeter(@tab, ',')
Use this style attribute for no word wrapping:
white-space: nowrap;
Because the view must return render
, not just call it. Change the last line to
return render(request, 'auth_lifecycle/user_profile.html',
context_instance=RequestContext(request))
Data transfer between two platform requires a common data format. JSON is a common global format to send cross platform data.
drawChart(600/50, JSON.parse('<?php echo json_encode($day); ?>'), JSON.parse('<?php echo json_encode($week); ?>'), JSON.parse('<?php echo json_encode($month); ?>'), JSON.parse('<?php echo json_encode(createDatesArray(cal_days_in_month(CAL_GREGORIAN, date('m',strtotime('-1 day')), date('Y',strtotime('-1 day'))))); ?>'))
This is the answer to your question. The answer may look very complex. You can see a simple example describing the communication between server side and client side here
$employee = array(
"employee_id" => 10011,
"Name" => "Nathan",
"Skills" =>
array(
"analyzing",
"documentation" =>
array(
"desktop",
"mobile"
)
)
);
Conversion to JSON format is required to send the data back to client application ie, JavaScript. PHP has a built in function json_encode(), which can convert any data to JSON format. The output of the json_encode function will be a string like this.
{
"employee_id": 10011,
"Name": "Nathan",
"Skills": {
"0": "analyzing",
"documentation": [
"desktop",
"mobile"
]
}
}
On the client side, success function will get the JSON string. Javascript also have JSON parsing function JSON.parse() which can convert the string back to JSON object.
$.ajax({
type: 'POST',
headers: {
"cache-control": "no-cache"
},
url: "employee.php",
async: false,
cache: false,
data: {
employee_id: 10011
},
success: function (jsonString) {
var employeeData = JSON.parse(jsonString); // employeeData variable contains employee array.
});
function String2Stars($string='',$first=0,$last=0,$rep='*'){
$begin = substr($string,0,$first);
$middle = str_repeat($rep,strlen(substr($string,$first,$last)));
$end = substr($string,$last);
$stars = $begin.$middle.$end;
return $stars;
}
example
$string = 'abcdefghijklmnopqrstuvwxyz';
echo String2Stars($string,5,-5); // abcde****************vwxyz
Oh man, solutions in all above answers provided so far didn't work for me. I had a similar problem just now. I managed to solve it with wrapping with the quote. See the screenshot. Whoo.
Original:
var products = [{_x000D_
"name": "Pizza",_x000D_
"price": "10",_x000D_
"quantity": "7"_x000D_
}, {_x000D_
"name": "Cerveja",_x000D_
"price": "12",_x000D_
"quantity": "5"_x000D_
}, {_x000D_
"name": "Hamburguer",_x000D_
"price": "10",_x000D_
"quantity": "2"_x000D_
}, {_x000D_
"name": "Fraldas",_x000D_
"price": "6",_x000D_
"quantity": "2"_x000D_
}];_x000D_
console.log(products);_x000D_
var b = JSON.parse(products); //unexpected token o
_x000D_
You can use strcmp()
if you wish to order/compare strings lexicographically. If you just wish to check for equality then ==
is just fine.
If you save color code in the colors.xml which is under the values folder,then you should call the following:
root.setBackgroundColor(getResources().getColor(R.color.name));
name
means you declare in the <color/>
tag.
Run the JVM with -XX:MaxHeapSize=512m
(or any big number as you need) (or -Xmx512m
for short)
Just insert this code on your page:
$(function(){_x000D_
var hash = window.location.hash;_x000D_
hash && $('ul.nav a[href="' + hash + '"]').tab('show');_x000D_
_x000D_
$('.nav-tabs a').click(function (e) {_x000D_
$(this).tab('show');_x000D_
var scrollmem = $('body').scrollTop();_x000D_
window.location.hash = this.hash;_x000D_
$('html,body').scrollTop(scrollmem);_x000D_
});_x000D_
});
_x000D_
You can also use the cell property.
Cells(1, 1).Value = "Hey, what's up?"
Make sure to use a .
before Cells(1,1).Value
as in .Cells(1,1).Value
, if you are using it within With
function. If you are selecting some sheet.
Both of these are primary from the old printing days.
Carriage return is from the days of the teletype printers/old typewriters, where literally the carriage would return to the next line, and push the paper up. This is what we now call \r
.
Line feed LF
signals the end of the line, it signals that the line has ended - but doesn't move the cursor to the next line. In other words, it doesn't "return" the cursor/printer head to the next line.
For more sundry details, the mighty wikipedia to the rescue.
I'm using following code from Application_Start
String baseUrl = Path.GetDirectoryName(HttpContext.Current.Request.Url.OriginalString);
This might help:
select * from tbl where col like '[ABC-XYZ-PQR]%'
I've used this in SQL Server 2005 and it worked.
To apply an ORDER BY or LIMIT clause to an individual SELECT, parenthesize the SELECT and place the clause inside the parentheses:
(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);
You can't move a mouse but can lock it. Note: that you must call requestPointerLock in click event.
Small Example:
var canvas = document.getElementById('mycanvas');
canvas.requestPointerLock = canvas.requestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
canvas.requestPointerLock();
Documentation and full code example:
https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API
Find root build.gradle
file and add google maven repo inside allprojects
tag
repositories {
mavenLocal()
mavenCentral()
maven { // <-- Add this
url 'https://maven.google.com/'
name 'Google'
}
}
It's better to use specific version instead of variable version
compile 'com.android.support:appcompat-v7:27.0.0'
If you're using Android Plugin for Gradle 3.0.0 or latter version
repositories {
mavenLocal()
mavenCentral()
google() //---> Add this
}
and inject dependency in this way :
implementation 'com.android.support:appcompat-v7:27.0.0'
org.apache.commons.lang.StringUtils#chopNewline
java.time.Period
Use the java.time.Period
class to count days.
Since Java 8 calculating the difference is more intuitive using LocalDate
, LocalDateTime
to represent the two dates
LocalDate now = LocalDate.now();
LocalDate inputDate = LocalDate.of(2018, 11, 28);
Period period = Period.between( inputDate, now);
int diff = period.getDays();
System.out.println("diff = " + diff);
JavaScript validation is not secure as anybody can change what your script does in the browser. Using it for enhancing the visual experience is ok though.
var textBox = document.getElementById("myTextBox");
var textLength = textBox.value.length;
if(textLength > 5)
{
//red
textBox.style.backgroundColor = "#FF0000";
}
else
{
//green
textBox.style.backgroundColor = "#00FF00";
}
you may use this - https://github.com/chanakyachatterjee/JSLightGrid ..JSLightGrid. have a look.. I found this one really very useful. Good performance, very light weight, all important browser friendly and fluid in itself, so you don't really need bootstrap for the grid.
Most likely it means that the directory and/or sub-directories are not writable. Many forget about sub-directories.
Symfony 2
chmod -R 777 app/cache app/logs
Symfony 3 directory structure
chmod -R 777 var/cache var/logs
Permissions solution by Symfony (mentioned previously).
Permissions solution by KPN University - additionally includes an screen-cast on installation.
Note: If you're using Symfony 3 directory structure, substitute app/cache
and app/logs
with var/cache
and var/logs
.
You can use a table
<table class="formcontrols" >
<tr>
<td>
<label for="firstName">FirstName:</label>
</td>
<td style="padding-left:10px;">
<input id="firstName" name="firstName" value="John">
</td>
</tr>
<tr>
<td>
<label for="Test">Last name:</label>
</td>
<td style="padding-left:10px;">
<input id="lastName" name="lastName" value="Travolta">
</td>
</tr>
</table>
The result would be: ImageResult
You can add parameter columns or use dict
with key which is converted to column name:
np.random.seed(123)
e = np.random.normal(size=10)
dataframe=pd.DataFrame(e, columns=['a'])
print (dataframe)
a
0 -1.085631
1 0.997345
2 0.282978
3 -1.506295
4 -0.578600
5 1.651437
6 -2.426679
7 -0.428913
8 1.265936
9 -0.866740
e_dataframe=pd.DataFrame({'a':e})
print (e_dataframe)
a
0 -1.085631
1 0.997345
2 0.282978
3 -1.506295
4 -0.578600
5 1.651437
6 -2.426679
7 -0.428913
8 1.265936
9 -0.866740
For Visual Studio 2017
and Visual Studio 2015
, IIS Express
settings is stored in the hidden .vs
directory and the path is something like this .vs\config\applicationhost.config
, add binding like below will work
<bindings>
<binding protocol="http" bindingInformation="*:8802:localhost" />
<binding protocol="http" bindingInformation="*:8802:127.0.0.1" />
</bindings>
var count=0;
let myArray = '{"1":"a","2":"b","3":"c","4":"d"}'
var data = JSON.parse(myArray);
for (let key in data) {
let value = data[key]; // get the value by key
console.log("key: , value:", key, value);
count = count + 1;
}
console.log("size:",count);
Or you can simply use OleDbDataAdapter to get data from Excel
This is answer based on answer from iraSenthil but with annotation (Captor). In my opinion it has some advantages:
Example:
@RunWith(MockitoJUnitRunner.class)
public class SomeTest{
@Captor
private ArgumentCaptor<List<SomeType>> captor;
//...
@Test
public void shouldTestArgsVals() {
//...
verify(mockedObject).someMethodOnMockedObject(captor.capture());
assertThat(captor.getValue().getXXX(), is("expected"));
}
}
Hashing algorithms are usually cryptographic in nature, but the principal difference is that encryption is reversible through decryption, and hashing is not.
An encryption function typically takes input and produces encrypted output that is the same, or slightly larger size.
A hashing function takes input and produces a typically smaller output, typically of a fixed size as well.
While it isn't possible to take a hashed result and "dehash" it to get back the original input, you can typically brute-force your way to something that produces the same hash.
In other words, if a authentication scheme takes a password, hashes it, and compares it to a hashed version of the requires password, it might not be required that you actually know the original password, only its hash, and you can brute-force your way to something that will match, even if it's a different password.
Hashing functions are typically created to minimize the chance of collisions and make it hard to just calculate something that will produce the same hash as something else.
I used Custom Action separately coded in C++ DLL and used the DLL to call appropriate function on Uninstalling using this syntax :
<CustomAction Id="Uninstall" BinaryKey="Dll_Name"
DllEntry="Function_Name" Execute="deferred" />
Using the above code block, I was able to run any function defined in C++ DLL on uninstall. FYI, my uninstall function had code regarding Clearing current user data and registry entries.
You can use date:'yyyy-MM-dd'
pipe
curDate=new Date();
<p>{{curDate | date:'yyyy-MM-dd'}}</p>
What Tgr said. Background:
http://www.example.com/düsseldorf?neighbourhood=Lörick
That's not a URI. But it is an IRI.
You can't include an IRI in an HTML4 document; the type of attributes like href
is defined as URI and not IRI. Some browsers will handle an IRI here anyway, but it's not really a good idea.
To encode an IRI into a URI, take the path and query parts, UTF-8-encode them then percent-encode the non-ASCII bytes:
http://www.example.com/d%C3%BCsseldorf?neighbourhood=L%C3%B6rick
If there are non-ASCII characters in the hostname part of the IRI, eg. http://??.???/
, they have be encoded using Punycode instead.
Now you have a URI. It's an ugly URI. But most browsers will hide that for you: copy and paste it into the address bar or follow it in a link and you'll see it displayed with the original Unicode characters. Wikipedia have been using this for years, eg.:
http://en.wikipedia.org/wiki/?
The one browser whose behaviour is unpredictable and doesn't always display the pretty IRI version is...
...well, you know.
You could fill the C Column with variations on the following formula:
=IF(ISERROR(MATCH(A1,$B:$B,0)),"",A1)
Then C would only contain values that were in A and C.
Exit
[construct], and intelisense will tell you which one(s) are valid in a particular place.
.so
files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.
.a
files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar
command -- a predecessor of tar
that's now just used for making libraries) of the original .o object files.
.la
files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?
Static and dynamic libraries each have pros and cons.
Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.
Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.
Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.
Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.
Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.
Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.
Dynamic libraries are especially useful for system libraries, like libc
. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.
You can use Series.isin
:
df = df[~df.datecolumn.isin(a)]
While the error message suggests that all()
or any()
can be used, they are useful only when you want to reduce the result into a single Boolean value. That is however not what you are trying to do now, which is to test the membership of every values in the Series against the external list, and keep the results intact (i.e., a Boolean Series which will then be used to slice the original DataFrame).
You can read more about this in the Gotchas.
Another easiest solution is to use Key.RETUEN
Click here for solution in detail
driver.findElement(By.name("q")).sendKeys("Selenium Tutorial", Key.RETURN);
This is partially pseudocode, but you will want something like:
rows = ActiveSheet.UsedRange.Rows
n = 0
while n <= rows
if ActiveSheet.Rows(n).Cells(DateColumnOrdinal).Value > '8/1/08' AND < '8/30/08' then
ActiveSheet.Rows(n).CopyTo(DestinationSheet)
endif
n = n + 1
wend
You can of course format the result of current_timestamp()
.
Please have a look at the various formatting functions in the official documentation.
I've captured the communication of Outlook plugin for Facebook and here is the POST request
https://api.facebook.com/method/fql.multiquery
access_token=TOKEN&queries={"USER0":"select '0', uid, name, birthday_date, profile_url, pic, website from user where uid in (select uid from email where email in ('EMAIL_HASH'))","PENDING_OUT":"select uid_to from friend_request where uid_from = MY_ID and (uid_to IN (select uid from #USER0))"}
where
TOKEN - valid access token
EMAIL_HASH - combination of CRC32 and MD5 hash of searched email address in format crc32_md5
MY_ID - ID of facebook profile of access token owner
But when I run this query with different access token (generated for my own application) the server response is: "The table you requested does not exist" I also haven't found the table email in Facebook API documentation. Does Microsoft have some extra rights at Facebook?
It's not a nice solution but try it like this:
<table>
<tr>
<td>
<div>Lorem</div>
</td>
</tr>
<tr>
<td>
<div>Ipsum</div>
</td>
</tr>
</table>
and set the divs to the min-height:
div {
min-height: 300px;
}
Hope this is what you want ...
If you don't need any features which YAML has and JSON doesn't, I would prefer JSON because it is very simple and is widely supported (has a lot of libraries in many languages). YAML is more complex and has less support. I don't think the parsing speed or memory use will be very much different, and maybe not a big part of your program's performance.
partition() may be better then split() for this purpose as it has the better predicable results for situations you have no delimiter or more delimiters.
I do my own approach used for calling super with safety inside multiple inheritance scenario (I put all the code)
def safe_super(_class, _inst):
"""safe super call"""
try:
return getattr(super(_class, _inst), _inst.__fname__)
except:
return (lambda *x,**kx: None)
def with_name(function):
def wrap(self, *args, **kwargs):
self.__fname__ = function.__name__
return function(self, *args, **kwargs)
return wrap
sample usage:
class A(object):
def __init__():
super(A, self).__init__()
@with_name
def test(self):
print 'called from A\n'
safe_super(A, self)()
class B(object):
def __init__():
super(B, self).__init__()
@with_name
def test(self):
print 'called from B\n'
safe_super(B, self)()
class C(A, B):
def __init__():
super(C, self).__init__()
@with_name
def test(self):
print 'called from C\n'
safe_super(C, self)()
testing it :
a = C()
a.test()
output:
called from C
called from A
called from B
Inside each @with_name decorated method you have access to self.__fname__ as the current function name.
The clean
, install
and deploy
phases are valid lifecycle phases and invoking them will trigger all the phases preceding them, and the goals bound to these phases.
mvn clean install
This command invokes the clean
phase and then the install
phase sequentially:
clean
: removes files generated at build-time in a project's directory (target
by default)install
: installs the package into the local repository, for use as a dependency in other projects locally.mvn deploy
This command invokes the deploy
phase:
deploy
: copies the final package to the remote repository for sharing with other developers and projects.mvn release
This is not a valid phase nor a goal so this won't do anything. But if refers to the Maven Release Plugin that is used to automate release management. Releasing a project is done in two steps: prepare
and perform
. As documented:
Preparing a release goes through the following release phases:
- Check that there are no uncommitted changes in the sources
- Check that there are no SNAPSHOT dependencies
- Change the version in the POMs from x-SNAPSHOT to a new version (you will be prompted for the versions to use)
- Transform the SCM information in the POM to include the final destination of the tag
- Run the project tests against the modified POMs to confirm everything is in working order
- Commit the modified POMs
- Tag the code in the SCM with a version name (this will be prompted for)
- Bump the version in the POMs to a new value y-SNAPSHOT (these values will also be prompted for)
- Commit the modified POMs
And then:
Performing a release runs the following release phases:
- Checkout from an SCM URL with optional tag
- Run the predefined Maven goals to release the project (by default, deploy site-deploy)
Busy waiting won't be a severe drawback if it is short. In my case there was the need to give visual feedback to the user by flashing a control (it is a chart control that can be copied to clipboard, which changes its background for some milliseconds). It works fine this way:
using System.Threading;
...
Clipboard.SetImage(bm); // some code
distribution_chart.BackColor = Color.Gray;
Application.DoEvents(); // ensure repaint, may be not needed
Thread.Sleep(50);
distribution_chart.BackColor = Color.OldLace;
....
I have found the solution posted by jillykate works, but only if the target element is the most nested. If this is not the case, this can be rectified by iterating over the parents, i.e.
function on_window_click(event)
{
let e = event.target;
while (e !== null)
{
// --- Handle clicks here, e.g. ---
if (e.getAttribute(`data-say_hello`))
{
console.log("Hello, world!");
}
e = e.parentElement;
}
}
window.addEventListener("click", on_window_click);
Also note we can handle events by any attribute, or attach our listener at any level. The code above uses a custom attribute and window
. I doubt there is any pragmatic difference between the various methods.
If you need to organize data in columns of 1 / 2 / 4 depending of the viewport size then push and pull may be no option at all. No matter how you order your items in the first place, one of the sizes may give you a wrong order.
A solution in this case is to use nested rows and cols without any push or pull classes.
In XS you want...
A
B
C
D
E
F
G
H
In SM you want...
A E
B F
C G
D H
In MD and above you want...
A C E G
B D F H
Use nested two-column child elements in a surrounding two-column parent element:
Here is a working snippet:
<script src="https://code.jquery.com/jquery-1.12.4.min.js" type="text/javascript" ></script>_x000D_
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"> _x000D_
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
<div class="row">_x000D_
<div class="col-sm-6">_x000D_
<div class="row">_x000D_
<div class="col-md-6"><p>A</p><p>B</p></div>_x000D_
<div class="col-md-6"><p>C</p><p>D</p></div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-sm-6">_x000D_
<div class="row">_x000D_
<div class="col-md-6"><p>E</p><p>F</p></div>_x000D_
<div class="col-md-6"><p>G</p><p>H</p></div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Another beauty of this solution is, that the items appear in the code in their natural order (A, B, C, ... H) and don't have to be shuffled, which is nice for CMS generation.
default_scope
This works for Rails 4+:
class Book < ActiveRecord::Base
default_scope { order(created_at: :desc) }
end
For Rails 2.3, 3, you need this instead:
default_scope order('created_at DESC')
For Rails 2.x:
default_scope :order => 'created_at DESC'
Where created_at
is the field you want the default sorting to be done on.
Note: ASC is the code to use for Ascending and DESC is for descending (desc
, NOT dsc
!).
scope
Once you're used to that you can also use scope
:
class Book < ActiveRecord::Base
scope :confirmed, :conditions => { :confirmed => true }
scope :published, :conditions => { :published => true }
end
For Rails 2 you need named_scope
.
:published
scope gives you Book.published
instead of
Book.find(:published => true)
.
Since Rails 3 you can 'chain' those methods together by concatenating them with periods between them, so with the above scopes you can now use Book.published.confirmed
.
With this method, the query is not actually executed until actual results are needed (lazy evaluation), so 7 scopes could be chained together but only resulting in 1 actual database query, to avoid performance problems from executing 7 separate queries.
You can use a passed in parameter such as a date or a user_id (something that will change at run-time and so will need that 'lazy evaluation', with a lambda, like this:
scope :recent_books, lambda
{ |since_when| where("created_at >= ?", since_when) }
# Note the `where` is making use of AREL syntax added in Rails 3.
Finally you can disable default scope with:
Book.with_exclusive_scope { find(:all) }
or even better:
Book.unscoped.all
which will disable any filter (conditions) or sort (order by).
Note that the first version works in Rails2+ whereas the second (unscoped) is only for Rails3+
So
... if you're thinking, hmm, so these are just like methods then..., yup, that's exactly what these scopes are!
They are like having def self.method_name ...code... end
but as always with ruby they are nice little syntactical shortcuts (or 'sugar') to make things easier for you!
In fact they are Class level methods as they operate on the 1 set of 'all' records.
Their format is changing however, with rails 4 there are deprecation warning when using #scope without passing a callable object. For example scope :red, where(color: 'red') should be changed to scope :red, -> { where(color: 'red') }
.
As a side note, when used incorrectly, default_scope can be misused/abused.
This is mainly about when it gets used for actions like where
's limiting (filtering) the default selection (a bad idea for a default) rather than just being used for ordering results.
For where
selections, just use the regular named scopes. and add that scope on in the query, e.g. Book.all.published
where published
is a named scope.
In conclusion, scopes are really great and help you to push things up into the model for a 'fat model thin controller' DRYer approach.
// this is a Jquery plugin function that fires an event when the size of an element is changed
// usage: $().sizeChanged(function(){})
(function ($) {
$.fn.sizeChanged = function (handleFunction) {
var element = this;
var lastWidth = element.width();
var lastHeight = element.height();
setInterval(function () {
if (lastWidth === element.width()&&lastHeight === element.height())
return;
if (typeof (handleFunction) == 'function') {
handleFunction({ width: lastWidth, height: lastHeight },
{ width: element.width(), height: element.height() });
lastWidth = element.width();
lastHeight = element.height();
}
}, 100);
return element;
};
}(jQuery));
None of the above works for me, I solved this by not using jQuery's $(document).ready, but use addEventListener instead.
document.addEventListener("turbolinks:load", function() {
// do something
});
If you are using Vim on Windows, you can get access to the clipboard (MS copy/paste) using:
"*dd -- cut a line (or 3dd to cut three lines)
"*yy -- copy a line (or 3yy to copy three lines)
"*p -- paste line(s) on line after the cursor
"*P -- paste line(s) on line before the cursor
The lets you paste between separate Vim windows or between Vim and PC applications (Notepad, Microsoft Word, etc.).
I would recommend creating a HashMap
from set A, and then iterating through set B and checking if any element of B is in A. This would run in O(|A|+|B|)
time (as there would be no collisions), whereas retainAll(Collection<?> c)
must run in O(|A|*|B|)
time.
For PHP 8:
sudo apt update
sudo apt-get install php8.0-soap
I wrote a snippet that will check for the change of an element on an event.
So if you are using third party javascript code or something and you need to know when something appears or changes when you have clicked then you can.
For the below snippet, lets say you need to know when a table content changes after you clicked a button.
$('.button').live('click', function() {
var tableHtml = $('#table > tbody').html();
var timeout = window.setInterval(function(){
if (tableHtml != $('#table > tbody').
console.log('no change');
} else {
console.log('table changed!');
clearInterval(timeout);
}
}, 10);
});
Pseudo Code:
Change the query to
"INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) VALUES(@na,@occ); SELECT SCOPE_IDENTITY()"
This will return the last inserted ID which you can then get with ExecuteScalar
Yes, there is. The -r
option tells rm
to be recursive, and remove the entire file hierarchy rooted at its arguments; in other words, if given a directory, it will remove all of its contents and then perform what is effectively an rmdir
.
The other two options you should know are -i
and -f
. -i
stands for interactive; it makes rm
prompt you before deleting each and every file. -f
stands for force; it goes ahead and deletes everything without asking. -i
is safer, but -f
is faster; only use it if you're absolutely sure you're deleting the right thing. You can specify these with -r
or not; it's an independent setting.
And as usual, you can combine switches: rm -r -i
is just rm -ri
, and rm -r -f
is rm -rf
.
Also note that what you're learning applies to bash
on every Unix OS: OS X, Linux, FreeBSD, etc. In fact, rm
's syntax is the same in pretty much every shell on every Unix OS. OS X, under the hood, is really a BSD Unix system.
The problem is that your code is creating a blank UIViewController, not a SecondViewController. You need to create an instance of your subclass, not a UIViewController,
func transition(Sender: UIButton!) {
let secondViewController:SecondViewController = SecondViewController()
self.presentViewController(secondViewController, animated: true, completion: nil)
}
If you've overridden init(nibName nibName: String!,bundle nibBundle: NSBundle!) in your SecondViewController class, then you need to change the code to,
let sec: SecondViewController = SecondViewController(nibName: nil, bundle: nil)
Since Marco's answer is deprecated, you must use the following syntax (according jasonlfunk's comment) :
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'http://www.example.com/user/create', [
'form_params' => [
'email' => '[email protected]',
'name' => 'Test user',
'password' => 'testpassword',
]
]);
$response = $client->request('POST', 'http://www.example.com/files/post', [
'multipart' => [
[
'name' => 'file_name',
'contents' => fopen('/path/to/file', 'r')
],
[
'name' => 'csv_header',
'contents' => 'First Name, Last Name, Username',
'filename' => 'csv_header.csv'
]
]
]);
// PUT
$client->put('http://www.example.com/user/4', [
'body' => [
'email' => '[email protected]',
'name' => 'Test user',
'password' => 'testpassword',
],
'timeout' => 5
]);
// DELETE
$client->delete('http://www.example.com/user');
Usefull for long server operations.
$client = new \GuzzleHttp\Client();
$promise = $client->requestAsync('POST', 'http://www.example.com/user/create', [
'form_params' => [
'email' => '[email protected]',
'name' => 'Test user',
'password' => 'testpassword',
]
]);
$promise->then(
function (ResponseInterface $res) {
echo $res->getStatusCode() . "\n";
},
function (RequestException $e) {
echo $e->getMessage() . "\n";
echo $e->getRequest()->getMethod();
}
);
According to documentation, you can set headers :
// Set various headers on a request
$client->request('GET', '/get', [
'headers' => [
'User-Agent' => 'testing/1.0',
'Accept' => 'application/json',
'X-Foo' => ['Bar', 'Baz']
]
]);
If you want more details information, you can use debug
option like this :
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'http://www.example.com/user/create', [
'form_params' => [
'email' => '[email protected]',
'name' => 'Test user',
'password' => 'testpassword',
],
// If you want more informations during request
'debug' => true
]);
Documentation is more explicits about new possibilities.
You really can't. PHP is generated at the server then sent to the browser, where JS starts to do it's stuff. So, whatever happens in JS on a page, PHP doesn't know because it's already done it's stuff. @manjula is correct, that if you want that to happen, you'd have to use a POST, or an ajax.
As of March 2017, with ggplot2
2.2.1 I think the best solution is explained in Hadley Wickham's R for data science book:
ggplot(mydataf) + stat_count(mapping = aes(x=foo, y=..prop.., group=1))
stat_count
computes two variables: count
is used by default, but you can choose to use prop
which shows proportions.
String user = request.getParameter("uname");
out.println(user);
String pass = request.getParameter("pass");
out.println(pass);
Class.forName( "com.mysql.jdbc.Driver" );
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/rental","root","root" ) ;
out.println("hello");
Statement st = conn.createStatement();
String sql = "insert into login (user,pass) values('" + user + "','" + pass + "')";
st.executeUpdate(sql);
char[] ch = ?
new String(ch).getBytes();
or
new String(ch).getBytes("UTF-8");
to get non-default charset.
Update: Since Java 7: new String(ch).getBytes(StandardCharsets.UTF_8);
You can use JSONPath
Doing something like this:
results = JSONPath(null, TestObj, "$..[?(@.id=='A')]")
Note that JSONPath returns an array of results
(I have not tested the expression "$..[?(@.id=='A')]" btw. Maybe it needs to be fine-tuned with the help of a browser console)
attributes are in your HTML text document/file (== imagine this is the result of your html markup parsed), whereas
properties are in HTML DOM tree (== basically an actual property of some object in JS sense).
Importantly, many of them are synced (if you update class
property, class
attribute in html will also be updated; and otherwise). But some attributes may be synced to unexpected properties - eg, attribute checked
corresponds to property defaultChecked
, so that
.prop('checked')
value, but will not change .attr('checked')
and .prop('defaultChecked')
values$('#input').prop('defaultChecked', true)
will also change .attr('checked')
, but this will not be visible on an element.Rule of thumb is:
.prop()
method should be used for boolean attributes/properties and for properties which do not exist in html (such as window.location). All other attributes (ones you can see in the html) can and should continue to be manipulated with the.attr()
method. (http://blog.jquery.com/2011/05/10/jquery-1-6-1-rc-1-released/)
And here is a table that shows where .prop()
is preferred (even though .attr()
can still be used).
.prop()
can return any type - string, integer, boolean; while .attr()
always returns a string..prop()
is said to be about 2.5 times faster than .attr()
.CSS relates to visual styling and not behaviour, so the answer is no really.
You could however either use javascript to modify the behaviour or change the styling of the span in question so that it doesn't have the pointy finger, underline, etc. Styling it like that will still leave it clickable.
Even better, change your markup so that it reflects what you want it to do.
Here is a query, you can run it in SQL Developer (or SQL*Plus):
SELECT DS.TABLESPACE_NAME, SEGMENT_NAME, ROUND(SUM(DS.BYTES) / (1024 * 1024)) AS MB
FROM DBA_SEGMENTS DS
WHERE SEGMENT_NAME IN (SELECT TABLE_NAME FROM DBA_TABLES)
GROUP BY DS.TABLESPACE_NAME,
SEGMENT_NAME;
I have came across the very-very-same problem.
In short:
I have made a test with ALL possible (sane) combinations of the following:
Resources/public/css
) with the CSS and a "private" directory (as Resources/assets/css
).This gave me a total of 14 combinations on the same twig, and this route was launched from
thus giving 14 x 3 = 42 tests.
Additionally, all this has been tested working in a subdirectory, so there is no way to fool by giving absolute URLs because they would simply not work.
The tests were two unnamed images and then divs named from 'a' to 'f' for the CSS built FROM the public folder and named 'g to 'l' for the ones built from the internal path.
I observed the following:
Only 3 of the 14 tests were shown adequately on the three URLs. And NONE was from the "internal" folder (Resources/assets). It was a pre-requisite to have the spare CSS PUBLIC and then build with assetic FROM there.
These are the results:
Result launched with /app_dev.php/
Result launched with /app.php/
Result launched with /
So... ONLY - The second image - Div B - Div C are the allowed syntaxes.
Here there is the TWIG code:
<html>
<head>
{% stylesheets 'bundles/commondirty/css_original/container.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{# First Row: ABCDEF #}
<link href="{{ '../bundles/commondirty/css_original/a.css' }}" rel="stylesheet" type="text/css" />
<link href="{{ asset( 'bundles/commondirty/css_original/b.css' ) }}" rel="stylesheet" type="text/css" />
{% stylesheets 'bundles/commondirty/css_original/c.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets 'bundles/commondirty/css_original/d.css' %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '@CommonDirtyBundle/Resources/public/css_original/e.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '@CommonDirtyBundle/Resources/public/css_original/f.css' %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{# First Row: GHIJKL #}
<link href="{{ '../../src/Common/DirtyBundle/Resources/assets/css/g.css' }}" rel="stylesheet" type="text/css" />
<link href="{{ asset( '../src/Common/DirtyBundle/Resources/assets/css/h.css' ) }}" rel="stylesheet" type="text/css" />
{% stylesheets '../src/Common/DirtyBundle/Resources/assets/css/i.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '../src/Common/DirtyBundle/Resources/assets/css/j.css' %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '@CommonDirtyBundle/Resources/assets/css/k.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '@CommonDirtyBundle/Resources/assets/css/l.css' %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
</head>
<body>
<div class="container">
<p>
<img alt="Devil" src="../bundles/commondirty/images/devil.png">
<img alt="Devil" src="{{ asset('bundles/commondirty/images/devil.png') }}">
</p>
<p>
<div class="a">
A
</div>
<div class="b">
B
</div>
<div class="c">
C
</div>
<div class="d">
D
</div>
<div class="e">
E
</div>
<div class="f">
F
</div>
</p>
<p>
<div class="g">
G
</div>
<div class="h">
H
</div>
<div class="i">
I
</div>
<div class="j">
J
</div>
<div class="k">
K
</div>
<div class="l">
L
</div>
</p>
</div>
</body>
</html>
The container.css:
div.container
{
border: 1px solid red;
padding: 0px;
}
div.container img, div.container div
{
border: 1px solid green;
padding: 5px;
margin: 5px;
width: 64px;
height: 64px;
display: inline-block;
vertical-align: top;
}
And a.css, b.css, c.css, etc: all identical, just changing the color and the CSS selector.
.a
{
background: red url('../images/devil.png');
}
The "directories" structure is:
Directories
All this came, because I did not want the individual original files exposed to the public, specially if I wanted to play with "less" filter or "sass" or similar... I did not want my "originals" published, only the compiled one.
But there are good news. If you don't want to have the "spare CSS" in the public directories... install them not with --symlink
, but really making a copy. Once "assetic" has built the compound CSS, and you can DELETE the original CSS from the filesystem, and leave the images:
Compilation process
Note I do this for the --env=prod
environment.
Just a few final thoughts:
This desired behaviour can be achieved by having the images in "public" directory in Git or Mercurial and the "css" in the "assets" directory. That is, instead of having them in "public" as shown in the directories, imagine a, b, c... residing in the "assets" instead of "public", than have your installer/deployer (probably a Bash script) to put the CSS temporarily inside the "public" dir before assets:install
is executed, then assets:install
, then assetic:dump
, and then automating the removal of CSS from the public directory after assetic:dump
has been executed. This would achive EXACTLY the behaviour desired in the question.
Another (unknown if possible) solution would be to explore if "assets:install" can only take "public" as the source or could also take "assets" as a source to publish. That would help when installed with the --symlink
option when developing.
Additionally, if we are going to script the removal from the "public" dir, then, the need of storing them in a separate directory ("assets") disappears. They can live inside "public" in our version-control system as there will be dropped upon deploy to the public. This allows also for the --symlink
usage.
BUT ANYWAY, CAUTION NOW: As now the originals are not there anymore (rm -Rf
), there are only two solutions, not three. The working div "B" does not work anymore as it was an asset() call assuming there was the original asset. Only "C" (the compiled one) will work.
So... there is ONLY a FINAL WINNER: Div "C" allows EXACTLY what it was asked in the topic: To be compiled, respect the path to the images and do not expose the original source to the public.
The winner is C
By the use of slice operator with step parameter which would cause evaluation of the queryset and create a list.
list_of_answers = answers[::1]
or initially you could have done:
answers = Answer.objects.filter(id__in=[answer.id for answer in
answer_set.answers.all()])[::1]
Many thanks for the information about using the QueryDefs collection! I have been wondering about this for a while.
I did it a different way, without using VBA, by using a table containing the query parameters.
E.g:
SELECT a_table.a_field
FROM QueryParameters, a_table
WHERE a_table.a_field BETWEEN QueryParameters.a_field_min
AND QueryParameters.a_field_max
Where QueryParameters
is a table with two fields, a_field_min
and a_field_max
It can even be used with GROUP BY
, if you include the query parameter fields in the GROUP BY
clause, and the FIRST
operator on the parameter fields in the HAVING
clause.
This is my Python function:
def add_nulls(num, cnt=2):
cnt = cnt - len(str(num))
nulls = '0' * cnt
return '%s%s' % (nulls, num)
You can also do this:
<center>
<div style="width: 40px; height: 40px;">
<svg class="sqs-svg-icon--social" viewBox="0 0 64 64">
<use class="sqs-use--icon" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#twitter-icon">
<svg id="twitter-icon" viewBox="0 0 64 64" width="100%" height="100%">
<path
d="M48,22.1c-1.2,0.5-2.4,0.9-3.8,1c1.4-0.8,2.4-2.1,2.9-3.6c-1.3,0.8-2.7,1.3-4.2,1.6 C41.7,19.8,40,19,38.2,19c-3.6,0-6.6,2.9-6.6,6.6c0,0.5,0.1,1,0.2,1.5c-5.5-0.3-10.3-2.9-13.5-6.9c-0.6,1-0.9,2.1-0.9,3.3 c0,2.3,1.2,4.3,2.9,5.5c-1.1,0-2.1-0.3-3-0.8c0,0,0,0.1,0,0.1c0,3.2,2.3,5.8,5.3,6.4c-0.6,0.1-1.1,0.2-1.7,0.2c-0.4,0-0.8,0-1.2-0.1 c0.8,2.6,3.3,4.5,6.1,4.6c-2.2,1.8-5.1,2.8-8.2,2.8c-0.5,0-1.1,0-1.6-0.1c2.9,1.9,6.4,2.9,10.1,2.9c12.1,0,18.7-10,18.7-18.7 c0-0.3,0-0.6,0-0.8C46,24.5,47.1,23.4,48,22.1z"
/>
</svg>
</use>
</svg>
</div>
</center>
Variant: I have an icon with id="logo" at the top left of the main page; a spinner gif is then overlaid on top (with transparency) when ajax is working.
jQuery.ajaxSetup({
beforeSend: function() {
$('#logo').css('background', 'url(images/ajax-loader.gif) no-repeat')
},
complete: function(){
$('#logo').css('background', 'none')
},
success: function() {}
});
You can't add them directly, you have to make a new array and then copy each of the arrays into the new one. System.arraycopy is a method you can use to perform this copy.
int[] array1and2 = new int[array1.length + array2.length];
System.arraycopy(array1, 0, array1and2, 0, array1.length);
System.arraycopy(array2, 0, array1and2, array1.length, array2.length);
This will work regardless of the size of array1 and array2.
Yeah, it's pretty simple:
input[type="submit"]{
background: #fff;
border: 1px solid #000;
text-shadow: 1px 1px 1px #000;
}
I recommend giving it an ID or a class so that you can target it more easily.
On Windows when you are using PowerShell you have to enclose all parameters with quotes.
So if you want to create a maven webapp archetype you would do as follows:
Prerequisites:
Howto:
Note: This is tested only on windows 10 powershell
I came up with an alternative that actually hides sections and doesn't delete them. I tried @henning77's approach, but I kept running into problems when I changed the number of sections of the static UITableView. This method has worked really well for me, but I'm primarily trying to hide sections instead of rows. I am removing some rows on the fly successfully, but it is a lot messier, so I've tried to group things into sections that I need to show or hide. Here is an example of how I'm hiding sections:
First I declare a NSMutableArray property
@property (nonatomic, strong) NSMutableArray *hiddenSections;
In the viewDidLoad (or after you have queried your data) you can add sections you want to hide to the array.
- (void)viewDidLoad
{
hiddenSections = [NSMutableArray new];
if(some piece of data is empty){
// Add index of section that should be hidden
[self.hiddenSections addObject:[NSNumber numberWithInt:1]];
}
... add as many sections to the array as needed
[self.tableView reloadData];
}
Then implement the following the TableView delegate methods
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
if([self.hiddenSections containsObject:[NSNumber numberWithInt:section]]){
return nil;
}
return [super tableView:tableView titleForHeaderInSection:section];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if([self.hiddenSections containsObject:[NSNumber numberWithInt:indexPath.section]]){
return 0;
}
return [super tableView:tableView heightForRowAtIndexPath:[self offsetIndexPath:indexPath]];
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if([self.hiddenSections containsObject:[NSNumber numberWithInt:indexPath.section]]){
[cell setHidden:YES];
}
}
Then set the header and footer height to 1 for hidden sections because you can't set the height to 0. This causes an additional 2 pixel space, but we can make up for it by adjusting the height of the next visible header.
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
CGFloat height = [super tableView:tableView heightForHeaderInSection:section];
if([self.hiddenSections containsObject:[NSNumber numberWithInt:section]]){
height = 1; // Can't be zero
}
else if([self tableView:tableView titleForHeaderInSection:section] == nil){ // Only adjust if title is nil
// Adjust height for previous hidden sections
CGFloat adjust = 0;
for(int i = (section - 1); i >= 0; i--){
if([self.hiddenSections containsObject:[NSNumber numberWithInt:i]]){
adjust = adjust + 2;
}
else {
break;
}
}
if(adjust > 0)
{
if(height == -1){
height = self.tableView.sectionHeaderHeight;
}
height = height - adjust;
if(height < 1){
height = 1;
}
}
}
return height;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
if([self.hiddenSections containsObject:[NSNumber numberWithInt:section]]){
return 1;
}
return [super tableView:tableView heightForFooterInSection:section];
}
Then, if you do have specific rows to hide you can adjust the numberOfRowsInSection and which rows are returned in cellForRowAtIndexPath. In this example here I have a section that has three rows where any three could be empty and need to be removed.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger rows = [super tableView:tableView numberOfRowsInSection:section];
if(self.organization != nil){
if(section == 5){ // Contact
if([self.organization objectForKey:@"Phone"] == [NSNull null]){
rows--;
}
if([self.organization objectForKey:@"Email"] == [NSNull null]){
rows--;
}
if([self.organization objectForKey:@"City"] == [NSNull null]){
rows--;
}
}
}
return rows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [super tableView:tableView cellForRowAtIndexPath:[self offsetIndexPath:indexPath]];
}
Use this offsetIndexPath to calculate the indexPath for rows where you are conditionally removing rows. Not needed if you are only hiding sections
- (NSIndexPath *)offsetIndexPath:(NSIndexPath*)indexPath
{
int row = indexPath.row;
if(self.organization != nil){
if(indexPath.section == 5){
// Adjust row to return based on which rows before are hidden
if(indexPath.row == 0 && [self.organization objectForKey:@"Phone"] == [NSNull null] && [self.organization objectForKey:@"Email"] != [NSNull null]){
row++;
}
else if(indexPath.row == 0 && [self.organization objectForKey:@"Phone"] == [NSNull null] && [self.organization objectForKey:@"Address"] != [NSNull null]){
row = row + 2;
}
else if(indexPath.row == 1 && [self.organization objectForKey:@"Phone"] != [NSNull null] && [self.organization objectForKey:@"Email"] == [NSNull null]){
row++;
}
else if(indexPath.row == 1 && [self.organization objectForKey:@"Phone"] == [NSNull null] && [self.organization objectForKey:@"Email"] != [NSNull null]){
row++;
}
}
}
NSIndexPath *offsetPath = [NSIndexPath indexPathForRow:row inSection:indexPath.section];
return offsetPath;
}
There are a lot of methods to override, but what I like about this approach is that it is re-usable. Setup the hiddenSections array, add to it, and it will hide the correct sections. Hiding the rows it a little trickier, but possible. We can't just set the height of the rows we want to hide to 0 if we're using a grouped UITableView because the borders will not get drawn correctly.
As @Lighthart as shown, yes it's possible, although it adds significant fat to the controller and isn't DRY.
You should really define your own query in the entity repository, it's simple and best practice.
use Doctrine\ORM\EntityRepository;
class UserRepository extends EntityRepository
{
public function findAll()
{
return $this->findBy(array(), array('username' => 'ASC'));
}
}
Then you must tell your entity to look for queries in the repository:
/**
* @ORM\Table(name="User")
* @ORM\Entity(repositoryClass="Acme\UserBundle\Entity\Repository\UserRepository")
*/
class User
{
...
}
Finally, in your controller:
$this->getDoctrine()->getRepository('AcmeBundle:User')->findAll();
This should do the trick:
df[- grep("REVERSE", df$Name),]
Or a safer version would be:
df[!grepl("REVERSE", df$Name),]
Why are you sending it through a post if you already have it on the server (PHP) side?
Why not just save the array to s $_SESSION
variable so you can use it when the form gets submitted, that might make it more "secure" since then the client cannot change the variables by editing the source.
It all depends on what you really want to do.
The pg documentation at NOTES say
The path will be interpreted relative to the working directory of the server process (normally the cluster's data directory), not the client's working directory.
So, gerally, using psql
or any client, even in a local server, you have problems ... And, if you're expressing COPY command for other users, eg. at a Github README, the reader will have problems ...
The only way to express relative path with client permissions is using STDIN,
When STDIN or STDOUT is specified, data is transmitted via the connection between the client and the server.
as remembered here:
psql -h remotehost -d remote_mydb -U myuser -c \
"copy mytable (column1, column2) from STDIN with delimiter as ','" \
< ./relative_path/file.csv
You can bind to dom directly
<div dangerouslySetInnerHTML={{__html: '<p>First · Second</p>'}}></div>
var app = angular.module('plunkr', [])
app.controller('UploadController', function($scope, fileReader) {
$scope.imageSrc = "";
$scope.$on("fileProgress", function(e, progress) {
$scope.progress = progress.loaded / progress.total;
});
});
app.directive("ngFileSelect", function(fileReader, $timeout) {
return {
scope: {
ngModel: '='
},
link: function($scope, el) {
function getFile(file) {
fileReader.readAsDataUrl(file, $scope)
.then(function(result) {
$timeout(function() {
$scope.ngModel = result;
});
});
}
el.bind("change", function(e) {
var file = (e.srcElement || e.target).files[0];
getFile(file);
});
}
};
});
app.factory("fileReader", function($q, $log) {
var onLoad = function(reader, deferred, scope) {
return function() {
scope.$apply(function() {
deferred.resolve(reader.result);
});
};
};
var onError = function(reader, deferred, scope) {
return function() {
scope.$apply(function() {
deferred.reject(reader.result);
});
};
};
var onProgress = function(reader, scope) {
return function(event) {
scope.$broadcast("fileProgress", {
total: event.total,
loaded: event.loaded
});
};
};
var getReader = function(deferred, scope) {
var reader = new FileReader();
reader.onload = onLoad(reader, deferred, scope);
reader.onerror = onError(reader, deferred, scope);
reader.onprogress = onProgress(reader, scope);
return reader;
};
var readAsDataURL = function(file, scope) {
var deferred = $q.defer();
var reader = getReader(deferred, scope);
reader.readAsDataURL(file);
return deferred.promise;
};
return {
readAsDataUrl: readAsDataURL
};
});
*************** CSS ****************
img{width:200px; height:200px;}
************** HTML ****************
<div ng-app="app">
<div ng-controller="UploadController ">
<form>
<input type="file" ng-file-select="onFileSelect($files)" ng-model="imageSrc">
<input type="file" ng-file-select="onFileSelect($files)" ng-model="imageSrc2">
<!-- <input type="file" ng-file-select="onFileSelect($files)" multiple> -->
</form>
<img ng-src="{{imageSrc}}" />
<img ng-src="{{imageSrc2}}" />
</div>
</div>
for everything related to Python's style guide: i'd recommend you read PEP8.
To answer your question:
Function names should be lowercase, with words separated by underscores as necessary to improve readability.
Here you'll find your answer:
Using Git how do I find changes between local and remote
For the lazy:
- Use "git log origin..HEAD"
- Use "git fetch" followed by "git log HEAD..origin". You can cherry-pick individual commits using the listed commit ids.
The above assumes, of course, that "origin" is the name of your remote tracking branch (which it is if you've used clone with default options).
You can also use following Node.js module to do it with ease:
https://www.npmjs.com/package/mssql-to-csv
var mssqlExport = require('mssql-to-csv')
// All config options supported by https://www.npmjs.com/package/mssql
var dbconfig = {
user: 'username',
password: 'pass',
server: 'servername',
database: 'dbname',
requestTimeout: 320000,
pool: {
max: 20,
min: 12,
idleTimeoutMillis: 30000
}
};
var options = {
ignoreList: ["sysdiagrams"], // tables to ignore
tables: [], // empty to export all the tables
outputDirectory: 'somedir',
log: true
};
mssqlExport(dbconfig, options).then(function(){
console.log("All done successfully!");
process.exit(0);
}).catch(function(err){
console.log(err.toString());
process.exit(-1);
});
I have wasted a lot of time figuring out what is wrong when I iterate through DOMElements with the code in the accepted answer. This is what worked for me, otherwise every second element disappears from the document:
_getGpxString: function(node) {
clone = node.cloneNode(true);
var tmp = document.createElement("div");
tmp.appendChild(clone);
return tmp.innerHTML;
},
As a workaround which achieves the same purpose, you may use the sprintf-js library and types.
I got it from another SO answer.
Here's some code from Excel 2010 that may work. It has a couple specifics (like filtering bad-encode characters from titles) but it was designed to create multiple multi-series graphs from 4-dimensional data having both absolute and percentage-based data. Modify it how you like:
Sub createAllGraphs()
Const chartWidth As Integer = 260
Const chartHeight As Integer = 200
If Sheets.Count = 1 Then
Sheets.Add , Sheets(1)
Sheets(2).Name = "AllCharts"
ElseIf Sheets("AllCharts").ChartObjects.Count > 0 Then
Sheets("AllCharts").ChartObjects.Delete
End If
Dim c As Variant
Dim c2 As Variant
Dim cs As Object
Set cs = Sheets("AllCharts")
Dim s As Object
Set s = Sheets(1)
Dim i As Integer
Dim chartX As Integer
Dim chartY As Integer
Dim r As Integer
r = 2
Dim curA As String
curA = s.Range("A" & r)
Dim curB As String
Dim curC As String
Dim startR As Integer
startR = 2
Dim lastTime As Boolean
lastTime = False
Do While s.Range("A" & r) <> ""
If curC <> s.Range("C" & r) Then
If r <> 2 Then
seriesAdd:
c.SeriesCollection.Add s.Range("D" & startR & ":E" & (r - 1)), , False, True
c.SeriesCollection(c.SeriesCollection.Count).Name = Replace(s.Range("C" & startR), "Â", "")
c.SeriesCollection(c.SeriesCollection.Count).XValues = "='" & s.Name & "'!$D$" & startR & ":$D$" & (r - 1)
c.SeriesCollection(c.SeriesCollection.Count).Values = "='" & s.Name & "'!$E$" & startR & ":$E$" & (r - 1)
c.SeriesCollection(c.SeriesCollection.Count).HasErrorBars = True
c.SeriesCollection(c.SeriesCollection.Count).ErrorBars.Select
c.SeriesCollection(c.SeriesCollection.Count).ErrorBar Direction:=xlY, Include:=xlBoth, Type:=xlCustom, Amount:="='" & s.Name & "'!$F$" & startR & ":$F$" & (r - 1), minusvalues:="='" & s.Name & "'!$F$" & startR & ":$F$" & (r - 1)
c.SeriesCollection(c.SeriesCollection.Count).ErrorBar Direction:=xlX, Include:=xlBoth, Type:=xlFixedValue, Amount:=0
c2.SeriesCollection.Add s.Range("D" & startR & ":D" & (r - 1) & ",G" & startR & ":G" & (r - 1)), , False, True
c2.SeriesCollection(c2.SeriesCollection.Count).Name = Replace(s.Range("C" & startR), "Â", "")
c2.SeriesCollection(c2.SeriesCollection.Count).XValues = "='" & s.Name & "'!$D$" & startR & ":$D$" & (r - 1)
c2.SeriesCollection(c2.SeriesCollection.Count).Values = "='" & s.Name & "'!$G$" & startR & ":$G$" & (r - 1)
c2.SeriesCollection(c2.SeriesCollection.Count).HasErrorBars = True
c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBars.Select
c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBar Direction:=xlY, Include:=xlBoth, Type:=xlCustom, Amount:="='" & s.Name & "'!$H$" & startR & ":$H$" & (r - 1), minusvalues:="='" & s.Name & "'!$H$" & startR & ":$H$" & (r - 1)
c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBar Direction:=xlX, Include:=xlBoth, Type:=xlFixedValue, Amount:=0
If lastTime = True Then GoTo postLoop
End If
If curB <> s.Range("B" & r).Value Then
If curA <> s.Range("A" & r).Value Then
chartX = chartX + chartWidth * 2
chartY = 0
curA = s.Range("A" & r)
End If
Set c = cs.ChartObjects.Add(chartX, chartY, chartWidth, chartHeight)
Set c = c.Chart
c.ChartWizard , xlXYScatterSmooth, , , , , True, Replace(s.Range("B" & r), "Â", "") & " " & s.Range("A" & r), s.Range("D1"), s.Range("E1")
Set c2 = cs.ChartObjects.Add(chartX + chartWidth, chartY, chartWidth, chartHeight)
Set c2 = c2.Chart
c2.ChartWizard , xlXYScatterSmooth, , , , , True, Replace(s.Range("B" & r), "Â", "") & " " & s.Range("A" & r) & " (%)", s.Range("D1"), s.Range("G1")
chartY = chartY + chartHeight
curB = s.Range("B" & r)
curC = s.Range("C" & r)
End If
curC = s.Range("C" & r)
startR = r
End If
If s.Range("A" & r) <> "" Then oneMoreTime = False ' end the loop for real this time
r = r + 1
Loop
lastTime = True
GoTo seriesAdd
postLoop:
cs.Activate
End Sub
Be careful on datatype. If not match it will throw an error.
var fieldName = dataRow.Field<DataType>("fieldName");
You need an uppercase M
for the month part.
string strDate = DateTime.Now.ToString("MM/dd/yyyy");
Lowercase m
is for outputting (and parsing) a minute (such as h:mm
).
e.g. a full date time string might look like this:
string strDate = DateTime.Now.ToString("MM/dd/yyyy h:mm");
Notice the uppercase/lowercase mM
difference.
Also if you will always deal with the same datetime format string, you can make it easier by writing them as C# extension methods.
public static class DateTimeMyFormatExtensions
{
public static string ToMyFormatString(this DateTime dt)
{
return dt.ToString("MM/dd/yyyy");
}
}
public static class StringMyDateTimeFormatExtension
{
public static DateTime ParseMyFormatDateTime(this string s)
{
var culture = System.Globalization.CultureInfo.CurrentCulture;
return DateTime.ParseExact(s, "MM/dd/yyyy", culture);
}
}
EXAMPLE: Translating between DateTime/string
DateTime now = DateTime.Now;
string strNow = now.ToMyFormatString();
DateTime nowAgain = strNow.ParseMyFormatDateTime();
Note that there is NO way to store a custom DateTime
format information to use as default
as in .NET most string formatting depends on the currently set culture, i.e.
System.Globalization.CultureInfo.CurrentCulture.
The only easy way you can do is to roll a custom extension method.
Also, the other easy way would be to use a different "container" or "wrapper" class for your DateTime, i.e. some special class with explicit operator
defined that automatically translates to and from DateTime/string. But that is dangerous territory.
Type in console as root:
apt-get update && apt-get install php5-curl
or with sudo:
sudo apt-get update && sudo apt-get install php5-curl
Sorry I missread.
1st, check your DNS config and if you can ping any host at all,
ping google.com
ping zm.archive.ubuntu.com
If it does not work, check /etc/resolv.conf
or /etc/network/resolv.conf
, if not, change your apt-source to a different one.
/etc/apt/sources.list
Mirrors: http://www.debian.org/mirror/list
You should not use Ubuntu sources on Debian and vice versa.
For my Samsung S3, I had to go into Developer Options on the phone, untick the "USB debugging" checkbox, then re-tick it.
Then the dialog will appear, asking if you want to allow USB Debugging.
Once I'd done this, the "adb devices
" command no longer showed "unauthorized" as my device name.
(Several months later..)
Actually, the same was true for connecting my Galaxy Tab S device, and the menu options were in slightly different places with Android 4.4.2:
You could try turning off the main Activity's ability to save its state (thus making it forget what control had text and what had focus). You will need to have some other way of remembering what your EditText's have and repopulating them onResume(). Launch your sub-Activities with startActivityForResult() and create an onActivityResult() handler in your main Activity that will update the EditText's correctly. This way you can set the proper button you want focused onResume() at the same time you repopulate the EditText's by using a myButton.post(new Runnable(){ run() { myButton.requestFocus(); } });
The View.post() method is useful for setting focus initially because that runnable will be executed after the window is created and things settle down, allowing the focus mechanism to function properly by that time. Trying to set focus during onCreate/Start/Resume() usually has issues, I've found.
Please note this is pseudo-code and non-tested, but it's a possible direction you could try.
The problem is described (among other) in this article.
#box
is relatively positioned, which makes it part of the "flow" of the page. Your other divs are absolutely positioned, so they are removed from the page's "flow".
Page flow means that the positioning of an element effects other elements in the flow.
In other words, as #box
now sees the dom, .a and .b are no longer "inside" #box
.
To fix this, you would want to make everything relative, or everything absolute.
One way would be:
.a {
position:relative;
margin-top:10px;
margin-left:10px;
background-color:red;
width:210px;
padding: 5px;
}
Make sure that the value of the column is really NULL and not an empty string or 0.
HTML
<mat-form-field>
<mat-select [(ngModel)]="modeSelect" placeholder="Mode">
<mat-option *ngFor="let obj of Array" [value]="obj.value">{{obj.value}}</mat-option>
</mat-select>
Now set your default value to
modeSelect
, where you are getting the values in Array variable.
Open ThisWorkbook.Path & "\template.txt" For Output As #1
Print #1, strContent
Close #1
Open
statement Print #
statementClose
statementPrint
StatementWorkbook.Path
propertyIt's not relative to performance...
You set async to false, when you need that ajax request to be completed before the browser passes to other codes:
<script>
// ...
$.ajax(... async: false ...); // Hey browser! first complete this request,
// then go for other codes
$.ajax(...); // Executed after the completion of the previous async:false request.
</script>
Use the BitArray
class.
int value = 3;
BitArray b = new BitArray(new int[] { value });
If you want to get an array for the bits, you can use the BitArray.CopyTo
method with a bool[]
array.
bool[] bits = new bool[b.Count];
b.CopyTo(bits, 0);
Note that the bits will be stored from least significant to most significant, so you may wish to use Array.Reverse
.
And finally, if you want get 0s and 1s for each bit instead of booleans (I'm using a byte
to store each bit; less wasteful than an int
):
byte[] bitValues = bits.Select(bit => (byte)(bit ? 1 : 0)).ToArray();
CURL client supports FTP protocol and works for passive mode. Get Download WITHOUT SSL version and you don't need any openssl.dll libraries. Just one curl.exe command line application.
http://www.paehl.com/open_source/?CURL_7.35.0
curl.exe -T c:\test\myfile.dat ftp://ftp.server.com/some/folder/myfile.dat --user myuser:mypwd
Another one is Putty psftp.exe but server key verification prompt requires a trick. This command line inputs NO for prompt meaning key is not stored in registry just this time being used. You need an external script file but sometimes its good if you copy multiple files up and down.
http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html
echo n | psftp.exe ftp.server.com -l myuser -pw mypwd -b script.txt
script.txt (any ftp command may be typed)
put "C:\test\myfile.dat" "/some/folder/myfile.dat"
quit
I do recomend doing it in 2 filles (.h .cpp)
But if u lazy just add inline
before the function
So it will look something like this
inline void functionX()
{ }
more about inline functions:
The inline functions are a C++ enhancement feature to increase the execution time of a program. Functions can be instructed to compiler to make them inline so that compiler can replace those function definition wherever those are being called. Compiler replaces the definition of inline functions at compile time instead of referring function definition at runtime. NOTE- This is just a suggestion to compiler to make the function inline, if function is big (in term of executable instruction etc) then, compiler can ignore the “inline” request and treat the function as normal function.
more info here
<table class="table table-striped table-condensed table-hover rsk-tbl vScrollTHead">
<thead>
<tr>
<th>Risk Element</th>
<th>Description</th>
<th>Risk Value</th>
<th> </th>
</tr>
</thead>
</table>
<div class="vScrollTable">
<table class="table table-striped table-condensed table-hover rsk-tbl vScrollTBody">
<tbody>
<tr class="">
<td>JEWELLERY</td>
<td>Jewellery business</td>
</tr><tr class="">
<td>NGO</td>
<td>none-governmental organizations</td>
</tr>
</tbody>
</table>
</div>
.vScrollTBody{
height:15px;
}
.vScrollTHead {
height:15px;
}
.vScrollTable{
height:100px;
overflow-y:scroll;
}
having two tables for head and body worked for me
When using VS2019, MVC5 - look under Migrations folder for file Configuration.cs Edit : AutomaticMigrationsEnabled = true
Sure we can get all HTML source code with this script below in Selenium Python:
elem = driver.find_element_by_xpath("//*")
source_code = elem.get_attribute("outerHTML")
If you you want to save it to file:
with open('c:/html_source_code.html', 'w') as f:
f.write(source_code.encode('utf-8'))
I suggest saving to a file because source code is very very long.
You first have to tell Gnuplot to use a style that uses points, e.g. with points
or with linespoints
. Try for example:
plot sin(x) with points
Output:
Now try:
plot sin(x) with points pointtype 5
Output:
You may also want to look at the output from the test
command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:
I wrote some test code to check JQueryUI drag/drop. The example shows how to drag an element from a container and drop it to another container.
Markup-
<div class="row">
<div class="col-xs-3">
<div class="panel panel-default">
<div class="panel-heading">
<h1 class="panel-title">Panel 1</h1>
</div>
<div id="container1" class="panel-body box-container">
<div itemid="itm-1" class="btn btn-default box-item">Item 1</div>
<div itemid="itm-2" class="btn btn-default box-item">Item 2</div>
<div itemid="itm-3" class="btn btn-default box-item">Item 3</div>
<div itemid="itm-4" class="btn btn-default box-item">Item 4</div>
<div itemid="itm-5" class="btn btn-default box-item">Item 5</div>
</div>
</div>
</div>
<div class="col-xs-3">
<div class="panel panel-default">
<div class="panel-heading">
<h1 class="panel-title">Panel 2</h1>
</div>
<div id="container2" class="panel-body box-container"></div>
</div>
</div>
</div>
JQuery codes-
$(document).ready(function() {
$('.box-item').draggable({
cursor: 'move',
helper: "clone"
});
$("#container1").droppable({
drop: function(event, ui) {
var itemid = $(event.originalEvent.toElement).attr("itemid");
$('.box-item').each(function() {
if ($(this).attr("itemid") === itemid) {
$(this).appendTo("#container1");
}
});
}
});
$("#container2").droppable({
drop: function(event, ui) {
var itemid = $(event.originalEvent.toElement).attr("itemid");
$('.box-item').each(function() {
if ($(this).attr("itemid") === itemid) {
$(this).appendTo("#container2");
}
});
}
});
});
CSS-
.box-container {
height: 200px;
}
.box-item {
width: 100%;
z-index: 1000
}
Check the plunker JQuery Drag Drop
A bad example:
import sun.audio.*; //import the sun.audio package
import java.io.*;
//** add this into your application code as appropriate
// Open an input stream to the audio file.
InputStream in = new FileInputStream(Filename);
// Create an AudioStream object from the input stream.
AudioStream as = new AudioStream(in);
// Use the static class member "player" from class AudioPlayer to play
// clip.
AudioPlayer.player.start(as);
// Similarly, to stop the audio.
AudioPlayer.player.stop(as);
If you are using SQL Server then correct way to get integer is
SELECT Cast(RAND()*(b-a)+a as int);
Where
After posting the question I thought of the following solution:
We need to check if exactly one of the binary digits is one. So we simply shift the number right one digit at a time, and return true
if it equals 1. If at any point we come by an odd number ((number & 1) == 1
), we know the result is false
. This proved (using a benchmark) slightly faster than the original method for (large) true values and much faster for false or small values.
private static bool IsPowerOfTwo(ulong number)
{
while (number != 0)
{
if (number == 1)
return true;
if ((number & 1) == 1)
// number is an odd number and not 1 - so it's not a power of two.
return false;
number = number >> 1;
}
return false;
}
Of course, Greg's solution is much better.
bash doesn't know boolean variables, nor does test
(which is what gets called when you use [
).
A solution would be:
if $myVar ; then ... ; fi
because true
and false
are commands that return 0
or 1
respectively which is what if
expects.
Note that the values are "swapped". The command after if
must return 0
on success while 0
means "false" in most programming languages.
SECURITY WARNING: This works because BASH expands the variable, then tries to execute the result as a command! Make sure the variable can't contain malicious code like rm -rf /
<% form_for(@message) do |f| %>
<%= f.radio_button :contactmethod, 'email', :checked => true %>
<%= label :contactmethod_email, 'Email' %>
<%= f.radio_button :contactmethod, 'sms' %>
<%= label :contactmethod_sms, 'SMS' %>
<% end %>
No. But can you give an example what you have in mind? What condition do you want to check?
Maybe Sass or Compass are interesting for you.
Quote from Sass:
Sass makes CSS fun again. Sass is CSS, plus nested rules, variables, mixins, and more, all in a concise, readable syntax.
i use these commands in a batch file to empty recycle bin:
del /q /s %systemdrive%\$Recycle.bin\*
for /d %%x in (%systemdrive%\$Recycle.bin\*) do @rd /s /q "%%x"
install urllib3
!pip3 install urllib3
import urllib3
than install it
!pip3 install selenium
import selenium
Same problem with the 'script' plugin in the Atom editor, which is an old version of node, not having btoa(), nor atob(), nor does it support the Buffer datatype. Following code does the trick:
var Base64 = new function() {_x000D_
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="_x000D_
this.encode = function(input) {_x000D_
var output = "";_x000D_
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;_x000D_
var i = 0;_x000D_
input = Base64._utf8_encode(input);_x000D_
while (i < input.length) {_x000D_
chr1 = input.charCodeAt(i++);_x000D_
chr2 = input.charCodeAt(i++);_x000D_
chr3 = input.charCodeAt(i++);_x000D_
enc1 = chr1 >> 2;_x000D_
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);_x000D_
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);_x000D_
enc4 = chr3 & 63;_x000D_
if (isNaN(chr2)) {_x000D_
enc3 = enc4 = 64;_x000D_
} else if (isNaN(chr3)) {_x000D_
enc4 = 64;_x000D_
}_x000D_
output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);_x000D_
}_x000D_
return output;_x000D_
}_x000D_
_x000D_
this.decode = function(input) {_x000D_
var output = "";_x000D_
var chr1, chr2, chr3;_x000D_
var enc1, enc2, enc3, enc4;_x000D_
var i = 0;_x000D_
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");_x000D_
while (i < input.length) {_x000D_
enc1 = keyStr.indexOf(input.charAt(i++));_x000D_
enc2 = keyStr.indexOf(input.charAt(i++));_x000D_
enc3 = keyStr.indexOf(input.charAt(i++));_x000D_
enc4 = keyStr.indexOf(input.charAt(i++));_x000D_
chr1 = (enc1 << 2) | (enc2 >> 4);_x000D_
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);_x000D_
chr3 = ((enc3 & 3) << 6) | enc4;_x000D_
output = output + String.fromCharCode(chr1);_x000D_
if (enc3 != 64) {_x000D_
output = output + String.fromCharCode(chr2);_x000D_
}_x000D_
if (enc4 != 64) {_x000D_
output = output + String.fromCharCode(chr3);_x000D_
}_x000D_
}_x000D_
output = Base64._utf8_decode(output);_x000D_
return output;_x000D_
}_x000D_
_x000D_
this._utf8_encode = function(string) {_x000D_
string = string.replace(/\r\n/g, "\n");_x000D_
var utftext = "";_x000D_
for (var n = 0; n < string.length; n++) {_x000D_
var c = string.charCodeAt(n);_x000D_
if (c < 128) {_x000D_
utftext += String.fromCharCode(c);_x000D_
} else if ((c > 127) && (c < 2048)) {_x000D_
utftext += String.fromCharCode((c >> 6) | 192);_x000D_
utftext += String.fromCharCode((c & 63) | 128);_x000D_
} else {_x000D_
utftext += String.fromCharCode((c >> 12) | 224);_x000D_
utftext += String.fromCharCode(((c >> 6) & 63) | 128);_x000D_
utftext += String.fromCharCode((c & 63) | 128);_x000D_
}_x000D_
}_x000D_
return utftext;_x000D_
}_x000D_
_x000D_
this._utf8_decode = function(utftext) {_x000D_
var string = "";_x000D_
var i = 0;_x000D_
var c = 0,_x000D_
c1 = 0,_x000D_
c2 = 0,_x000D_
c3 = 0;_x000D_
while (i < utftext.length) {_x000D_
c = utftext.charCodeAt(i);_x000D_
if (c < 128) {_x000D_
string += String.fromCharCode(c);_x000D_
i++;_x000D_
} else if ((c > 191) && (c < 224)) {_x000D_
c2 = utftext.charCodeAt(i + 1);_x000D_
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));_x000D_
i += 2;_x000D_
} else {_x000D_
c2 = utftext.charCodeAt(i + 1);_x000D_
c3 = utftext.charCodeAt(i + 2);_x000D_
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));_x000D_
i += 3;_x000D_
}_x000D_
}_x000D_
return string;_x000D_
}_x000D_
}()_x000D_
_x000D_
var btoa = Base64.encode;_x000D_
var atob = Base64.decode;_x000D_
_x000D_
console.log("btoa('A') = " + btoa('A'));_x000D_
console.log("btoa('QQ==') = " + atob('QQ=='));_x000D_
console.log("btoa('B') = " + btoa('B'));_x000D_
console.log("btoa('Qg==') = " + atob('Qg=='));
_x000D_
validChars can be any construct, but I decided to select based on ascii code ranges removing control chars. In this example, it is a 12 character string.
string validChars = String.Join("", Enumerable.Range(33, (126 - 33)).Where(i => !(new int[] { 34, 38, 39, 44, 60, 62, 96 }).Contains(i)).Select(i => { return (char)i; }));
string.Join("", Enumerable.Range(1, 12).Select(i => { return validChars[(new Random(Guid.NewGuid().GetHashCode())).Next(0, validChars.Length - 1)]; }))
parentFragmentManager.apply {
val f = this@MyFragment
beginTransaction().hide(f).remove(f).commit()
}
in fact. use the methods of vector and index. we can also achieve the same result, and more easier to understand:
rawdata <- data.frame('time' = 1:3,
'x1' = 4:6,
'x2' = 7:9,
'x3' = 10:12)
rawdata[rep(1, time=2), ] %>% remove_rownames()
# time x1 x2 x3
# 1 1 4 7 10
# 2 1 4 7 10
Use value(cellref)
on the side to evaluate the cells. Strings will produce the "#Value" error, but dates resolve to a number (e.g. 43173
).
To create a "drop down menu" you can use OptionMenu
in tkinter
Example of a basic OptionMenu
:
from Tkinter import *
master = Tk()
variable = StringVar(master)
variable.set("one") # default value
w = OptionMenu(master, variable, "one", "two", "three")
w.pack()
mainloop()
More information (including the script above) can be found here.
Creating an OptionMenu
of the months from a list would be as simple as:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
mainloop()
In order to retrieve the value the user has selected you can simply use a .get()
on the variable that we assigned to the widget, in the below case this is variable
:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
def ok():
print ("value is:" + variable.get())
button = Button(master, text="OK", command=ok)
button.pack()
mainloop()
I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.
What I normally do is e .
(e-space-dot) which gives me a browsable current directory - then I can /
- search for name fragments, just like finding a word in a text file. I find that generally good enough, simple and quick.
so as things have changed with GIT since alot of these answers were posted here is the correct instructions to get symlinks working correctly in windows as of
AUGUST 2018
1. Make sure git is installed with symlink support
2. Tell Bash to create hardlinks instead of symlinks
EDIT -- (git folder)/etc/bash.bashrc
ADD TO BOTTOM - MSYS=winsymlinks:nativestrict
3. Set git config to use symlinks
git config core.symlinks true
or
git clone -c core.symlinks=true <URL>
NOTE: I have tried adding this to the global git config and at the moment it is not working for me so I recommend adding this to each repo...
4. pull the repo
NOTE: Unless you have enabled developer mode in the latest version of Windows 10, you need to run bash as administrator to create symlinks
5. Reset all Symlinks (optional) If you have an existing repo, or are using submodules you may find that the symlinks are not being created correctly so to refresh all the symlinks in the repo you can run these commands.
find -type l -delete
git reset --hard
NOTE: this will reset any changes since last commit so make sure you have committed first
I've got this error when I ran composer install
inside my PHP DOCKER container,
It's a memory issue.
Solved by increasing SWAP memory in DOCKER PREFERENCES from 512MB to 1.5GB
To do that:
Docker -> Preferences -> Rousources
You can parse the pom file with JDOM (http://www.jdom.org/).
You can use jQuery load method to get the contents and insert into an element.
Try this:
$(document).ready(function() {
$("#lesen").click(function() {
$(".text").load("helloworld.txt");
});
});
You, can also add a call back to execute something once the load process is complete
e.g:
$(document).ready(function() {
$("#lesen").click(function() {
$(".text").load("helloworld.txt", function(){
alert("Done Loading");
});
});
});
New and neat in Python 3.5:
[*map(chr, [66, 53, 0, 94])]
Thanks to Additional Unpacking Generalizations
UPDATE
Always seeking for shorter ways, I discovered this one also works:
*map(chr, [66, 53, 0, 94]),
Unpacking works in tuples too. Note the comma at the end. This makes it a tuple of 1 element. That is, it's equivalent to (*map(chr, [66, 53, 0, 94]),)
It's shorter by only one char from the version with the list-brackets, but, in my opinion, better to write, because you start right ahead with the asterisk - the expansion syntax, so I feel it's softer on the mind. :)
HashMap
is an implementation of Map
. Map is just an interface for any type of map.
If you make a file called Makefile and add a variable like this $(unittest) then you will be able to use this variable inside the Makefile even with wildcards
example :
make unittest=*
I use BOOST_TEST and by giving a wildcard to parameter --run_test=$(unittest) then I will be able to use regular expression to filter out the test I want my Makefile to run
public class SortedMapExample {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("Cde", "C");
map.put("Abc", "A");
map.put("Cbc", "Z");
map.put("Dbc", "D");
map.put("Bcd", "B");
map.put("sfd", "Bqw");
map.put("DDD", "Bas");
map.put("BGG", "Basd");
System.out.println(sort(map, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}}));
}
@SuppressWarnings("unchecked")
public static <K, V> Map<K,V> sort(Map<K, V> in, Comparator<? super V> compare) {
Map<K, V> result = new LinkedHashMap<K, V>();
V[] array = (V[])in.values().toArray();
for(int i=0;i<array.length;i++)
{
}
Arrays.sort(array, compare);
for (V item : array) {
K key= (K) getKey(in, item);
result.put(key, item);
}
return result;
}
public static <K, V> Object getKey(Map<K, V> in,V value)
{
Set<K> key= in.keySet();
Iterator<K> keyIterator=key.iterator();
while (keyIterator.hasNext()) {
K valueObject = (K) keyIterator.next();
if(in.get(valueObject).equals(value))
{
return valueObject;
}
}
return null;
}
}
// Please try here. I am modifing the code for value sort.
It is important to note that object files are assembled to binary code in a format that is relocatable. This is a form which allows the assembled code to be loaded anywhere into memory for use with other programs by a linker.
Instructions that refer to labels will not yet have an address assigned for these labels in the .o file.
These labels will be written as '0' and the assembler creates a relocation record for these unknown addresses. When the file is linked and output to an executable the unknown addresses are resolved and the program can be executed.
You can use the nm tool on an object file to list the symbols defined in a .o file.
I had this problem with chrome when I was working on a WordPress site. I added this code
$_SERVER['HTTPS'] = false;
into the theme's functions.php file - it asks you to log in again when you save the file but once it's logged in it works straight away.
Also have a look at everyauth if you want third party/social network login integration.
$?
is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep
command succeeded.
The grep
manpage states:
The exit status is 0 if selected lines are found, and 1 if not found. If an error occurred the exit status is 2. (Note: POSIX error handling code should check for '2' or greater.)
So in this case it's checking whether any ERROR lines were found.
You have to fetch that one record, it will contain the result of Count()
$result = $db->query("SELECT COUNT(*) FROM `table`");
$row = $result->fetch_row();
echo '#: ', $row[0];
The above did not work for me but this did
<%= link_to "text_to_show_in_url", action_controller_path(:gender => "male", :param2=> "something_else") %>
It is completely acceptable to use a DIV inside a <form>
tag.
If you look at the default CSS 2.1 stylesheet, div
and p
are both in the display: block
category. Then looking at the HTML 4.01 specification for the form element, they include not only <p>
tags, but <table>
tags, so of course <div>
would meet the same criteria. There is also a <legend>
tag inside the form in the documentation.
For instance, the following passes HTML4 validation in strict mode:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test</title>
</head>
<body>
<form id="test" action="test.php">
<div>
Test: <input name="blah" value="test" type="text">
</div>
</form>
</body>
</html>
Handy way: Using Browser Printing/Preview
Maybe better to make an anchor with DeleteJob url instead of button?
<a href="<%=Url.Action("DeleteJob", "YourController", new {selectedObject="someObject"})%>" onclick="return DeleteJob()">Löschen</a>
and use your javascript you wrote already:
function DeleteJob() {
if (confirm("Do you really want to delete selected job/s?"))
return true;
else
return false;
}
So if function return true - you will be redirected. If function return false - you still stay on the page.
You can use it in a more compact way as:
var tifs = {1: 'Joe', 2: 'Jane'};
...
return (
<select id="tif" name="tif" onChange={this.handleChange}>
{ Object.entries(tifs).map((t,k) => <option key={k} value={t[0]}>{t[1]}</option>) }
</select>
)
And another slightly different flavour:
Object.entries(tifs).map(([key,value],i) => <option key={i} value={key}>{value}</option>)
[x for x in L if 'ab' in x]
If using flexbox is a valid option for you (don't need to suport old browsers), check my other answer here (which is possibly a duplicate of this one):
Basically you'd need to wrap your img tag in a div and your css would look like this:
.img__container {
display: flex;
padding: 15px 12px;
box-sizing: border-box;
width: 400px; height: 200px;
img {
margin: auto;
max-width: 100%;
max-height: 100%;
}
}
I was using the command prompt to manually install the .apk file on my device (Nexus 7) but the following should work in theory on any android device (after enabling the device for developer mode). This method was becoming cumbersome so I created a simple batch file so now all I have to do is double-click it and it installs for me (device must be plugged in to my development machine). Just create a text file and save it as .BAT with the following text (customize to accommodate your file paths):
cd C:\{**path to your install location**}\sdk\platform-tools
adb install C:\{**path to your .apk file**}\{**project/apk file name**}.apk
With the recent update to melt.data.table
, we can now melt multiple columns. With that, we can do:
require(data.table) ## 1.9.5
melt(setDT(df), id=1:2, measure=patterns("^Q3.2", "^Q3.3"),
value.name=c("Q3.2", "Q3.3"), variable.name="loop_number")
# id time loop_number Q3.2 Q3.3
# 1: 1 2009-01-01 1 -0.433978480 0.41227209
# 2: 2 2009-01-02 1 -0.567995351 0.30701144
# 3: 3 2009-01-03 1 -0.092041353 -0.96024077
# 4: 4 2009-01-04 1 1.137433487 0.60603396
# 5: 5 2009-01-05 1 -1.071498263 -0.01655584
# 6: 6 2009-01-06 1 -0.048376809 0.55889996
# 7: 7 2009-01-07 1 -0.007312176 0.69872938
You can get the development version from here.
You're not including the C file that contains main()
when compiling, so the linker isn't seeing it.
You need to add it:
$ gcc -o runexp runexp.c scd.o data_proc.o -lm -fopenmp
By default the docker daemon always runs as the root user, therefore you need to prepend sudo
to your Docker command(s).
If you don’t want to use sudo when you use the docker command, create a Unix group called docker and add users to it. When the docker daemon starts, it makes the ownership of the Unix socket read/writable by the docker group.
Create the docker group.
$ sudo groupadd docker
Add your user to the docker group.
$ sudo usermod -aG docker $USER
Log out and log back in so that your group membership is re-evaluated.
Verify that you can docker commands without sudo.
$ docker run hello-world
This command downloads a test image and runs it in a container. When the container runs, it prints an informational message and exits.
The steps outlined above comes from the official Docker documentation.
Try clearFocus() instead of setSelected(false)
. Every view in Android has both focusability and selectability, and I think that you want to just clear the focus.
Here's what I use:
NSString * timestamp = [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970] * 1000];
(times 1000 for milliseconds, otherwise, take that out)
If You're using it all the time, it might be nice to declare a macro
#define TimeStamp [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970] * 1000]
Then Call it like this:
NSString * timestamp = TimeStamp;
Or as a method:
- (NSString *) timeStamp {
return [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970] * 1000];
}
As TimeInterval
- (NSTimeInterval) timeStamp {
return [[NSDate date] timeIntervalSince1970] * 1000;
}
NOTE:
The 1000 is to convert the timestamp to milliseconds. You can remove this if you prefer your timeInterval in seconds.
Swift
If you'd like a global variable in Swift, you could use this:
var Timestamp: String {
return "\(NSDate().timeIntervalSince1970 * 1000)"
}
Then, you can call it
println("Timestamp: \(Timestamp)")
Again, the *1000
is for miliseconds, if you'd prefer, you can remove that. If you want to keep it as an NSTimeInterval
var Timestamp: NSTimeInterval {
return NSDate().timeIntervalSince1970 * 1000
}
Declare these outside of the context of any class and they'll be accessible anywhere.
If you are working on kitkat and above, you can use the chrome remote debugging tools to find all the requests and responses going in and out of your webview and also the the html source code of the page viewed.
The essential difference between /*
and /
is that a servlet with mapping /*
will be selected before any servlet with an extension mapping (like *.html
), while a servlet with mapping /
will be selected only after extension mappings are considered (and will be used for any request which doesn't match anything else---it is the "default servlet").
In particular, a /*
mapping will always be selected before a /
mapping. Having either prevents any requests from reaching the container's own default servlet.
Either will be selected only after servlet mappings which are exact matches (like /foo/bar
) and those which are path mappings longer than /*
(like /foo/*
). Note that the empty string mapping is an exact match for the context root (http://host:port/context/
).
See Chapter 12 of the Java Servlet Specification, available in version 3.1 at http://download.oracle.com/otndocs/jcp/servlet-3_1-fr-eval-spec/index.html.
char[] characters;
...
string s = new string(characters);
If you already know the item is a String
, I prefer:
String itemText = (String) mySpinner.getSelectedItem();
Calling toString()
on an Object
that you know is a String
seems like a more roundabout path than just casting the Object
to String
.
Gem::Specification.map {|a| a.name}
However, if your app uses Bundler it will return only list of dependent local gems. To get all installed:
def all_installed_gems
Gem::Specification.all = nil
all = Gem::Specification.map{|a| a.name}
Gem::Specification.reset
all
end
There is no need to use :checkbox
, also replace #activelist
with #inactivelist
:
$('#inactivelist').change(function () {
alert('changed');
});
The request methods GET, PUT and DELETE are CRUD (create, read, update and delete) operations—that is data management operations—on the state of a target resource (the one identified by the request URI):
The request method POST is a different beast. It should not create the state of the target resource like PUT because it is a process operation with a higher-level goal than CRUD (cf. RFC 7231, § 4.3.3). The process may create a resource but different from the target resource, otherwise the lower-level goal request method PUT should be used, so even in this case that does not make it a CRUD operation.
The difference between CRUD operations (GET, PUT and DELETE in HTTP) and non-CRUD operations (POST in HTTP) is the difference between abstract data types and objects that Alan Kay was stressing in most of his talks and his ACM paper The Early History of Smalltalk:
What I got from Simula was that you could now replace bindings and assignments with goals. The last thing you wanted any programmer to do is mess with internal state even if presented figuratively. Instead, the objects should be presented as sites of higher level behaviors more appropriate for use as dynamic components.
[…] It is unfortunate that much of what is called "object-oriented programming" today is simply old style programming with fancier constructs. Many programs are loaded with "assignment-style" operations now done by more expensive attached procedures.
[…] Assignment statements—even abstract ones—express very low-level goals, and more of them will be needed to get anything done. […] Another way to think of all this is: though the late-binding of automatic storage allocations doesn’t do anything a programmer can’t do, its presence leads both to simpler and more powerful code. OOP is a late binding strategy for many things and all of them together hold off fragility and size explosion much longer than the older methodologies.
I would go with
i = np.min(np.where(V >= x))
where V
is vector (1d array), x
is the value and i
is the resulting index.
Edit: Whoops, didn't check your question tags before answering.
Check that you can actually connect to DB (have the driver placed? tested the conn when creating it?).
If so, try runnung those queries with F5
What if the first character is not a letter (but a tab, a space, and a escaped double quote)? We'd better test it until we find a letter! So:
S=' \"ó foo bar\"'
N=0
until [[ ${S:$N:1} =~ [[:alpha:]] ]]; do N=$[$N+1]; done
#F=`echo ${S:$N:1} | tr [:lower:] [:upper:]`
#F=`echo ${S:$N:1} | sed -E -e 's/./\u&/'` #other option
F=`echo ${S:$N:1}
F=`echo ${F} #pure Bash solution to "upper"
echo "$F"${S:(($N+1))} #without garbage
echo '='${S:0:(($N))}"$F"${S:(($N+1))}'=' #garbage preserved
Foo bar
= \"Foo bar=