What is com.sun.proxy.$Proxy
Proxies are classes that are created and loaded at runtime. There is no source code for these classes. I know that you are wondering how you can make them do something if there is no code for them. The answer is that when you create them, you specify an object that implements InvocationHandler
, which defines a method that is invoked when a proxy method is invoked.
You create them by using the call
Proxy.newProxyInstance(classLoader, interfaces, invocationHandler)
The arguments are:
classLoader
. Once the class is generated, it is loaded with this class loader.
interfaces
. An array of class objects that must all be interfaces. The resulting proxy implements all of these interfaces.
invocationHandler
. This is how your proxy knows what to do when a method is invoked. It is an object that implements InvocationHandler
. When a method from any of the supported interfaces, or hashCode
, equals
, or toString
, is invoked, the method invoke
is invoked on the handler, passing the Method
object for the method to be invoked and the arguments passed.
For more on this, see the documentation for the Proxy
class.
Every implementation of a JVM after version 1.3 must support these. They are loaded into the internal data structures of the JVM in an implementation-specific way, but it is guaranteed to work.
Get a list of all threads currently running in Java
To get a list of threads and their full states using the terminal, you can use the command below:
jstack -l <PID>
Which <PID>
is the id of process running on your computer. To get the process id of your java process you can simply run the jps
command.
Also, you can analyze your thread dump that produced by jstack in TDAs (Thread Dump Analyzer) such fastthread or spotify thread analyzer tool.
Java stack overflow error - how to increase the stack size in Eclipse?
Open the Run Configuration for your application (Run/Run Configurations..., then look for the applications entry in 'Java application').
The arguments tab has a text box Vm arguments, enter -Xss1m
(or a bigger parameter for the maximum stack size). The default value is 512 kByte (SUN JDK 1.5 - don't know if it varies between vendors and versions).
JFrame.dispose() vs System.exit()
System.exit();
causes the Java VM to terminate completely.
JFrame.dispose();
causes the JFrame
window to be destroyed and cleaned up by the operating system. According to the documentation, this can cause the Java VM to terminate if there are no other Windows available, but this should really just be seen as a side effect rather than the norm.
The one you choose really depends on your situation. If you want to terminate everything in the current Java VM, you should use System.exit()
and everything will be cleaned up. If you only want to destroy the current window, with the side effect that it will close the Java VM if this is the only window, then use JFrame.dispose()
.
Java 32-bit vs 64-bit compatibility
yo where wrong! To this theme i wrote an question to oracle. The answer was.
"If you compile your code on an 32 Bit Machine, your code should only run on an 32 Bit Processor. If you want to run your code on an 64 Bit JVM you have to compile your class Files on an 64 Bit Machine using an 64-Bit JDK."
What is the largest possible heap size with a 64-bit JVM?
If you want to use 32-bit references, your heap is limited to 32 GB.
However, if you are willing to use 64-bit references, the size is likely to be limited by your OS, just as it is with 32-bit JVM. e.g. on Windows 32-bit this is 1.2 to 1.5 GB.
Note: you will want your JVM heap to fit into main memory, ideally inside one NUMA region. That's about 1 TB on the bigger machines. If your JVM spans NUMA regions the memory access and the GC in particular will take much longer. If your JVM heap start swapping it might take hours to GC, or even make your machine unusable as it thrashes the swap drive.
Note: You can access large direct memory and memory mapped sizes even if you use 32-bit references in your heap. i.e. use well above 32 GB.
Compressed oops in the Hotspot JVM
Compressed oops represent managed pointers (in many but not all places in the JVM) as 32-bit values which must be scaled by a factor of 8 and added to a 64-bit base address to find the object they refer to. This allows applications to address up to four billion objects (not bytes), or a heap size of up to about 32Gb. At the same time, data structure compactness is competitive with ILP32 mode.
How can I specify the default JVM arguments for programs I run from eclipse?
Go to Window → Preferences → Java → Installed JREs. Select the JRE you're using, click Edit, and there will be a line for Default VM Arguments which will apply to every execution. For instance, I use this on OS X to hide the icon from the dock, increase max memory and turn on assertions:
-Xmx512m -ea -Djava.awt.headless=true
Getting Java version at runtime
Example for Apache Commons Lang:
import org.apache.commons.lang.SystemUtils;
Float version = SystemUtils.JAVA_VERSION_FLOAT;
if (version < 1.4f) {
// legacy
} else if (SystemUtils.IS_JAVA_1_5) {
// 1.5 specific code
} else if (SystemUtils.isJavaVersionAtLeast(1.6f)) {
// 1.6 compatible code
} else {
// dodgy clause to catch 1.4 :)
}
Android Studio - No JVM Installation found
- For me this turns out to be Environment Variables not being inherited.
- Quick answer: reboot, than click on studio.bat, not studio.exe or studio64.exe
================ Details =================
"Right Click"-"Run as Administrator" works for me if:
** JDK_HOME or JAVA_HOME was set. (PATH didn't need to be changed for me)
** I run studio.bat, not studio.exe
** Note: By Default I am an administrator on a Microsoft Account (That Microsoft part may be affecting things), and I seldom reboot. I'm running Win8.1 64bit. I installed both JDKv1.8.0.0_25 32bit and 64 bit, and had JRE 32bit and 64 bit already installed (used by other software).
I found there was a difference in clicking on studio.bat, studio.exe, and running studio.bat from a command prompt. There is also a difference if I rebooted or not.
The difference: The System Environment Variables aren't all there depending on how I start the program.
To test:
In start menu drag a copy of "command prompt" to your desktop, then change properties so "Start In" is location of studio.bat
- copy studio.bat to studio_debug.bat (one we can mess with)
- drag a shortcut of studio_debug.bat to desktop for convenience.
- edit studio_debug.bat (right click --> edit)
== Change:
@echo off
== to
@echo on
echo Set===================
set
echo ======================
pause
- This may also help in debugging studio.bat:
== change:
"%JAVA_EXE%" %ALL_JVM_ARGS% -cp "%CLASS_PATH%" %MAIN_CLASS_NAME% %*
== to
echo =================
echo Starting: "%JAVA_EXE%" %ALL_JVM_ARGS% -cp "%CLASS_PATH%" %MAIN_CLASS_NAME% %*
pause
"%JAVA_EXE%" %ALL_JVM_ARGS% -cp "%CLASS_PATH%" %MAIN_CLASS_NAME% %*
echo =================
Now when you run studio.bat from command prompt versus double clicking you may see difference in environment variables including JAVA_HOME and PATH. If you do you have same problem as me.
The problem seems to depend on:
- did you reboot since changing environment variables?
- didn't seem to matter if I was local or microsoft account
- may depend whether you are an administrator or other account type
- whether you start using studio.bat, studio.exe, or studio64.exe
.
FYI: The actual successful startup command executed by studio.bat on my system was as follows (includes studio64.exe):
"C:\Program Files\Java\jdk1.8.0_25\bin\java.exe" "-Xms128m" "-Xmx750m" "-XX:MaxPermSize=350m" "-XX:ReservedCodeCacheSize=96m" "-ea" "-Dsun.io.useCanonCaches=false" "-Djava.net.preferIPv4Stack=true" "-Djsse.enableSNIExtension=false" "-XX:+UseCodeCacheFlushing" "-XX:+UseConcMarkSweepGC" "-XX:SoftRefLRUPolicyMSPerMB=50" "-XX:+HeapDumpOnOutOfMemoryError" "-Didea.platform.prefix=AndroidStudio" "-Didea.paths.selector=AndroidStudioBeta" -Djb.vmOptionsFile="C:\android-studio\bin\studio64.exe.vmoptions" "-Xbootclasspath/a:C:\android-studio\bin\../lib/boot.jar" -Didea.paths.selector=AndroidStudioBeta -Didea.platform.prefix=AndroidStudio -cp "C:\android-studio\bin\..\lib\bootstrap.jar;C:\android-studio\bin\..\lib\extensions.jar;C:\android-studio\bin\..\lib\util.jar;C:\android-studio\bin\..\lib\jdom.jar;C:\android-studio\bin\..\lib\log4j.jar;C:\android-studio\bin\..\lib\trove4j.jar;C:\android-studio\bin\..\lib\jna.jar;C:\Program Files\Java\jdk1.8.0_25\lib\tools.jar" com.intellij.idea.Main
Hope that helps someone else.
How to set JVM parameters for Junit Unit Tests?
In IntelliJ you can specify default settings for each run configuration. In Run/Debug configuration dialog (the one you use to configure heap per test) click on Defaults and JUnit. These settings will be automatically applied to each new JUnit test configuration. I guess similar setting exists for Eclipse.
However there is no simple option to transfer such settings (at least in IntelliJ) across environments. You can commit IntelliJ project files to your repository: it might work, but I do not recommend it.
You know how to set these for maven-surefire-plugin
. Good. This is the most portable way (see Ptomli's answer for an example).
For the rest - you must remember that JUnit test cases are just a bunch of Java classes, not a standalone program. It is up to the runner (let it be a standalone JUnit runner, your IDE, maven-surefire-plugin
to set those options. That being said there is no "portable" way to set them, so that memory settings are applied irrespective to the runner.
To give you an example: you cannot define Xmx
parameter when developing a servlet - it is up to the container to define that. You can't say: "this servlet should always be run with Xmx=1G
.
Android Gradle Could not reserve enough space for object heap
Solution for Android Studio 2.3.3 on MacOS 10.12.6
Start Android Studios with more heap memory:
export JAVA_OPTS="-Xms6144m -Xmx6144m -XX:NewSize=256m -XX:MaxNewSize=356m -XX:PermSize=256m -XX:MaxPermSize=356m"
open -a /Applications/Android\ Studio.app
how to increase java heap memory permanently?
You also use this below to expand the memory
export _JAVA_OPTIONS="-Xms512m -Xmx1024m -Xss512m -XX:MaxPermSize=1024m"
Xmx
specifies the maximum memory allocation pool for a Java virtual machine (JVM)
Xms
specifies the initial memory allocation pool.
Xss
setting memory size of thread stack
XX:MaxPermSize
: the maximum permanent generation size
What are the -Xms and -Xmx parameters when starting JVM?
Run the command java -X
and you will get a list of all -X
options:
C:\Users\Admin>java -X
-Xmixed mixed mode execution (default)
-Xint interpreted mode execution only
-Xbootclasspath:<directories and zip/jar files separated by ;>
set search path for bootstrap classes and resources
-Xbootclasspath/a:<directories and zip/jar files separated by ;>
append to end of bootstrap class path
-Xbootclasspath/p:<directories and zip/jar files separated by ;>
prepend in front of bootstrap class path
-Xdiag show additional diagnostic messages
-Xnoclassgc disable class garbage collection
-Xincgc enable incremental garbage collection
-Xloggc:<file> log GC status to a file with time stamps
-Xbatch disable background compilation
-Xms<size> set initial Java heap size.........................
-Xmx<size> set maximum Java heap size.........................
-Xss<size> set java thread stack size
-Xprof output cpu profiling data
-Xfuture enable strictest checks, anticipating future default
-Xrs reduce use of OS signals by Java/VM (see documentation)
-Xcheck:jni perform additional checks for JNI functions
-Xshare:off do not attempt to use shared class data
-Xshare:auto use shared class data if possible (default)
-Xshare:on require using shared class data, otherwise fail.
-XshowSettings show all settings and continue
-XshowSettings:all show all settings and continue
-XshowSettings:vm show all vm related settings and continue
-XshowSettings:properties show all property settings and continue
-XshowSettings:locale show all locale related settings and continue
The -X options are non-standard and subject to change without notice.
I hope this will help you understand Xms
, Xmx
as well as many other things that matters the most. :)
Can anybody tell me details about hs_err_pid.log file generated when Tomcat crashes?
A very very good document regarding this topic is Troubleshooting Guide for Java from (originally) Sun. See the chapter "Troubleshooting System Crashes" for information about hs_err_pid*
Files.
See Appendix C - Fatal Error Log
Per the guide, by default the file will be created in the working directory of the process if possible, or in the system temporary directory otherwise. A specific location can be chosen by passing in the -XX:ErrorFile product flag. It says:
If the -XX:ErrorFile= file flag is not specified, the system attempts to create the file in the working directory of the process. In the event that the file cannot be created in the working directory (insufficient space, permission problem, or other issue), the file is created in the temporary directory for the operating system.
Cannot load 64-bit SWT libraries on 32-bit JVM ( replacing SWT file )
Eclipse is launching your application with whatever JRE you defined in your launch configuration. Since you're running the 32-bit Eclipse, you're running/debugging against its 32-bit SWT libraries, and you'll need to run a 32-bit JRE.
Your 64-bit JRE is, for whatever reason, your default Installed JRE.
To change this, first make sure you have a 32-bit JRE configured in the Installed JREs preference. Go to Window -> Preferences and navigate to Java -> Installed JREs:
You can click Add and navigate to your 32-bit JVM's JAVA_HOME
to add it.
Then in your Run Configuration, find your Eclipse Application and make sure the Runtime JRE is set to the 32-bit JRE you just configured:
(Note the combobox that is poorly highlighted.)
Don't try replacing SWT jars, that will likely end poorly.
Could not reserve enough space for object heap
Above answers are correct, but I will explain this problem with best solution.
When you have assigned org.gradle.jvmargs=-Xmx512m and still facing the sa,=me problem then here is the solution..
Mostly this error occurs because your pc using 100% of its power, and your project is using so many resources, whenever you face this problem you can open task manager and you will see your disk is being used 100%, and your pc is too slow, then you can just disable startup apps which are high in processing and restart your pc.
After restart, when you open your project first clean it and then try to run it.
I have tried all above the solution but still couldn't solve the problem then I tried to free the memory usages and background processes and my problem has been solved.
What is the default maximum heap size for Sun's JVM from Java SE 6?
one way is if you have a jdk installed , in bin folder there is a utility called jconsole(even visualvm can be used).
Launch it and connect to the relevant java process and you can see what are the heap size settings set and many other details
When running headless or cli only, jConsole can be used over lan, if you specify a port to connect on when starting the service in question.
How do I find out what keystore my JVM is using?
Your keystore will be in your JAVA_HOME---> JRE -->lib---> security--> cacerts
. You need to check where your JAVA_HOME is configured, possibly one of these places,
Computer--->Advanced --> Environment variables---> JAVA_HOME
Your server startup batch files.
In your import command -keystore cacerts (give full path to the above JRE here instead of just saying cacerts).
JVM option -Xss - What does it do exactly?
It indeed sets the stack size on a JVM.
You should touch it in either of these two situations:
- StackOverflowError (the stack size is greater than the limit), increase the value
- OutOfMemoryError: unable to create new native thread (too many threads, each thread has a large stack), decrease it.
The latter usually comes when your Xss is set too large - then you need to balance it (testing!)
Maximum Java heap size of a 32-bit JVM on a 64-bit OS
Should be a lot better
For a 32-bit JVM running on a 64-bit host, I imagine what's left over for the heap will be whatever unfragmented virtual space is available after the JVM, it's own DLL's, and any OS 32-bit compatibility stuff has been loaded. As a wild guess I would think 3GB should be possible, but how much better that is depends on how well you are doing in 32-bit-host-land.
Also, even if you could make a giant 3GB heap, you might not want to, as this will cause GC pauses to become potentially troublesome. Some people just run more JVM's to use the extra memory rather than one giant one. I imagine they are tuning the JVM's right now to work better with giant heaps.
It's a little hard to know exactly how much better you can do. I guess your 32-bit situation can be easily determined by experiment. It's certainly hard to predict abstractly, as a lot of things factor into it, particularly because the virtual space available on 32-bit hosts is rather constrained.. The heap does need to exist in contiguous virtual memory, so fragmentation of the address space for dll's and internal use of the address space by the OS kernel will determine the range of possible allocations.
The OS will be using some of the address space for mapping HW devices and it's own dynamic allocations. While this memory is not mapped into the java process address space, the OS kernel can't access it and your address space at the same time, so it will limit the size of any program's virtual space.
Loading DLL's depends on the implementation and the release of the JVM. Loading the OS kernel depends on a huge number of things, the release, the HW, how many things it has mapped so far since the last reboot, who knows...
In summary
I bet you get 1-2 GB in 32-bit-land, and about 3 in 64-bit, so an overall improvement of about 2x.
How do I set the proxy to be used by the JVM
From the Java documentation (not the javadoc API):
http://download.oracle.com/javase/6/docs/technotes/guides/net/proxies.html
Set the JVM flags http.proxyHost
and http.proxyPort
when starting your JVM on the command line.
This is usually done in a shell script (in Unix) or bat file (in Windows). Here's the example with the Unix shell script:
JAVA_FLAGS=-Dhttp.proxyHost=10.0.0.100 -Dhttp.proxyPort=8800
java ${JAVA_FLAGS} ...
When using containers such as JBoss or WebLogic, my solution is to edit the start-up scripts supplied by the vendor.
Many developers are familiar with the Java API (javadocs), but many times the rest of the documentation is overlooked. It contains a lot of interesting information: http://download.oracle.com/javase/6/docs/technotes/guides/
Update : If you do not want to use proxy to resolve some local/intranet hosts, check out the comment from @Tomalak:
Also don't forget the http.nonProxyHosts property!
-Dhttp.nonProxyHosts="localhost|127.0.0.1|10.*.*.*|*.foo.com??|etc"
What does -XX:MaxPermSize do?
-XX:PermSize -XX:MaxPermSize
are used to set size for Permanent Generation.
Permanent Generation: The Permanent Generation is where class files are kept. These are the result of compiled classes and JSP pages. If this space is full, it triggers a Full Garbage Collection. If the Full Garbage Collection cannot clean out old unreferenced classes and there is no room left to expand the Permanent Space, an Out-of- Memory error (OOME) is thrown and the JVM will crash.
How can I get a random number in Kotlin?
Generate a random integer between from
(inclusive) and to
(exclusive)
import java.util.Random
val random = Random()
fun rand(from: Int, to: Int) : Int {
return random.nextInt(to - from) + from
}
Increase JVM max heap size for Eclipse
You can use this configuration:
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.200.v20120913-144807
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Xms512m
-Xmx1024m
-XX:+UseParallelGC
-XX:PermSize=256M
-XX:MaxPermSize=512M
Differences between "java -cp" and "java -jar"?
java -cp CLASSPATH is necesssary if you wish to specify all code in the classpath. This is useful for debugging code.
The jarred executable format: java -jar JarFile
can be used if you wish to start the app with a single short command. You can specify additional dependent jar files in your MANIFEST using space separated jars in a Class-Path entry, e.g.:
Class-Path: mysql.jar infobus.jar acme/beans.jar
Both are comparable in terms of performance.
Cannot assign requested address using ServerSocket.socketBind
As other people have pointed out, it is most likely related to another process using port 9999
. On Windows, run the command:
netstat -a -n | grep "LIST"
And it should list anything there that's hogging the port. Of course you'll then have to go and manually kill those programs in Task Manager. If this still doesn't work, replace the line:
serverSocket = new ServerSocket(9999);
With:
InetAddress locIP = InetAddress.getByName("192.168.1.20");
serverSocket = new ServerSocket(9999, 0, locIP);
Of course replace 192.168.1.20
with your actual IP address, or use 127.0.0.1
.
Where are static methods and static variables stored in Java?
Prior to Java 8:
The static variables were stored in the permgen space(also called the method area).
PermGen Space is also known as Method Area
PermGen Space used to store 3 things
- Class level data (meta-data)
- interned strings
- static variables
From Java 8 onwards
The static variables are stored in the Heap itself.From Java 8 onwards the PermGen Space have been removed and new space named as MetaSpace is introduced which is not the part of Heap any more unlike the previous Permgen Space. Meta-Space is present on the native memory (memory provided by the OS to a particular Application for its own usage) and it now only stores the class meta-data.
The interned strings and static variables are moved into the heap itself.
For official information refer : JEP 122:Remove the Permanent Gen Space
What is the difference between JVM, JDK, JRE & OpenJDK?
JVM
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms.
JRE
JRE is an acronym for Java Runtime Environment.It is used to provide runtime environment.It is the implementation of JVM.It physically exists.It contains set of libraries + other files that JVM uses at runtime.
JDK
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE + development tools.
Link :- http://www.javatpoint.com/difference-between-jdk-jre-and-jvm
Font is not available to the JVM with Jasper Reports
You can do it by installing fonts, that means everywhere you want to run that particular application. Simplest way is just add this bl line to your jrxml file:
<property name="net.sf.jasperreports.awt.ignore.missing.font" value="true"/>
Hope it helps.
How to increase application heap size in Eclipse?
- Go to Eclipse Folder
- Find Eclipse Icon in Eclipse Folder
- Right Click on it you will get option "Show Package Content"
- Contents folder will open on screen
- If you are on Mac then you'll find "MacOS"
- Open MacOS folder you'll find eclipse.ini file
Open it in word or any file editor for edit
...
-XX:MaxPermSize=256m
-Xms40m
-Xmx512m
...
Replace -Xmx512m to -Xmx1024m
- Save the file and restart your Eclipse
- Have a Nice time :)
Increasing the JVM maximum heap size for memory intensive applications
32-bit Java is limited to approximately 1.4 to 1.6 GB.
Oracle 32 bit heap FAQ
Quote
The maximum theoretical heap limit for the 32-bit JVM is 4G. Due to various additional constraints such as available swap, kernel address space usage, memory fragmentation, and VM overhead, in practice the limit can be much lower. On most modern 32-bit Windows systems the maximum heap size will range from 1.4G to 1.6G. On 32-bit Solaris kernels the address space is limited to 2G. On 64-bit operating systems running the 32-bit VM, the max heap size can be higher, approaching 4G on many Solaris systems.
Java - Get a list of all Classes loaded in the JVM
One way if you already know the package top level path is to use OpenPojo
final List<PojoClass> pojoClasses = PojoClassFactory.getPojoClassesRecursively("my.package.path", null);
Then you can go over the list and perform any functionality you desire.
Missing `server' JVM (Java\jre7\bin\server\jvm.dll.)
To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm.dll
, please install or use the JRE or JDK that contains these missing components.
Follow these steps:
Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)
After that, go to C:/Program files/java/jre7/bin
Here, create an folder called Server
Now go into the C:/Program files/java/jre7/bin/client
folder
Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server
folder
How to tune Tomcat 5.5 JVM Memory settings without using the configuration program
I like the idea of seting tomcat6 memory based on available server memory (it is cool because I don't have to change the setup after hardware upgrade). Here is my (a bit extended memory setup):
export CATALINA_OPTS="-Xmx`cat /proc/meminfo | grep MemTotal | awk '{
print $2*0.75 } '`
k -Xms`cat /proc/meminfo | grep MemTotal | awk '{
print $2*0.75 } '`
k -XX:NewSize=`cat /proc/meminfo | grep MemTotal |
awk '{ print $2*0.15 } '`
k -XX:MaxNewSize=`cat /proc/meminfo | grep
MemTotal | awk '{ print $2*0.15 } '`
k -XX:PermSize=`cat /proc/meminfo
| grep MemTotal | awk '{ print $2*0.15 } '`
k -XX:MaxPermSize=`cat
/proc/meminfo | grep MemTotal | awk '{ print $2*0.15 } '`
k"
Put it to: "{tomcat}/bin/startup.sh" (e.g. "/usr/share/tomcat6/bin" for Ubuntu 10.10)
Difference between thread's context class loader and normal classloader
This does not answer the original question, but as the question is highly ranked and linked for any ContextClassLoader
query, I think it is important to answer the related question of when the context class loader should be used. Short answer: never use the context class loader! But set it to getClass().getClassLoader()
when you have to call a method that is missing a ClassLoader
parameter.
When code from one class asks to load another class, the correct class loader to use is the same class loader as the caller class (i.e., getClass().getClassLoader()
). This is the way things work 99.9% of the time because this is what the JVM does itself the first time you construct an instance of a new class, invoke a static method, or access a static field.
When you want to create a class using reflection (such as when deserializing or loading a configurable named class), the library that does the reflection should always ask the application which class loader to use, by receiving the ClassLoader
as a parameter from the application. The application (which knows all the classes that need constructing) should pass it getClass().getClassLoader()
.
Any other way to obtain a class loader is incorrect. If a library uses hacks such as Thread.getContextClassLoader()
, sun.misc.VM.latestUserDefinedLoader()
, or sun.reflect.Reflection.getCallerClass()
it is a bug caused by a deficiency in the API. Basically, Thread.getContextClassLoader()
exists only because whoever designed the ObjectInputStream
API forgot to accept the ClassLoader
as a parameter, and this mistake has haunted the Java community to this day.
That said, many many JDK classes use one of a few hacks to guess some class loader to use. Some use the ContextClassLoader
(which fails when you run different apps on a shared thread pool, or when you leave the ContextClassLoader null
), some walk the stack (which fails when the direct caller of the class is itself a library), some use the system class loader (which is fine, as long as it is documented to only use classes in the CLASSPATH
) or bootstrap class loader, and some use an unpredictable combination of the above techniques (which only makes things more confusing). This has resulted in much weeping and gnashing of teeth.
When using such an API, first, try to find an overload of the method that accepts the class loader as a parameter. If there is no sensible method, then try setting the ContextClassLoader
before the API call (and resetting it afterwards):
ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
// call some API that uses reflection without taking ClassLoader param
} finally {
Thread.currentThread().setContextClassLoader(originalClassLoader);
}
JVM property -Dfile.encoding=UTF8 or UTF-8?
If, running an Oracle HotSpot JDK 1.7.x, on a Linux platform where your locale suggests UTF-8 (e.g. LANG=en_US.utf8
), if you don't set it on the command-line with -Dfile.encoding
, the JDK will default file.encoding
and the default Charset
like this:
System.out.println(String.format("file.encoding: %s", System.getProperty("file.encoding")));
System.out.println(String.format("defaultCharset: %s", Charset.defaultCharset().name()));
... yields:
file.encoding: UTF-8
defaultCharset: UTF-8
... suggesting the default is UTF-8
on such a platform.
Additionally, if java.nio.charset.Charset.defaultCharset()
finds file.encoding
not-set, it looks for java.nio.charset.Charset.forName("UTF-8")
, suggesting it prefers that string, although it is well-aliased, so "UTF8" will also work fine.
If you run the same program on the same platform with java -Dfile.encoding=UTF8
, without the hypen, it yields:
file.encoding: UTF8
defaultCharset: UTF-8
... noting that the default charset has been canonicalized from UTF8
to UTF-8
.
Could not reserve enough space for object heap to start JVM
According to this post this error message means:
Heap size is larger than your computer's physical memory.
Edit: Heap is not the only memory that is reserved, I suppose. At least there are other JVM settings like PermGenSpace that ask for the memory. With heap size 128M and a PermGenSpace of 64M you already fill the space available.
Why not downsize other memory settings to free up space for the heap?
How can I tell if I'm running in 64-bit JVM or 32-bit JVM (from within a program)?
On Linux, you can get ELF header information by using either of the following two commands:
file {YOUR_JRE_LOCATION_HERE}/bin/java
o/p:
ELF 64-bit LSB executable, AMD x86-64, version 1 (SYSV), for GNU/Linux 2.4.0, dynamically linked (uses shared libs), for GNU/Linux 2.4.0, not stripped
or
readelf -h {YOUR_JRE_LOCATION_HERE}/bin/java | grep 'Class'
o/p:
Class: ELF64
Where does Java's String constant pool live, the heap or the stack?
As explained by this answer, the exact location of the string pool is not specified and can vary from one JVM implementation to another.
It is interesting to note that until Java 7, the pool was in the permgen space of the heap on hotspot JVM but it has been moved to the main part of the heap since Java 7:
Area: HotSpot
Synopsis: In JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application. This change will result in more data residing in the main Java heap, and less data in the permanent generation, and thus may require heap sizes to be adjusted. Most applications will see only relatively small differences in heap usage due to this change, but larger applications that load many classes or make heavy use of the String.intern() method will see more significant differences.
RFE: 6962931
And in Java 8 Hotspot, Permanent Generation has been completely removed.
How to deal with "java.lang.OutOfMemoryError: Java heap space" error?
Ultimately you always have a finite max of heap to use no matter what platform you are running on. In Windows 32 bit this is around 2GB
(not specifically heap but total amount of memory per process). It just happens that Java chooses to make the default smaller (presumably so that the programmer can't create programs that have runaway memory allocation without running into this problem and having to examine exactly what they are doing).
So this given there are several approaches you could take to either determine what amount of memory you need or to reduce the amount of memory you are using. One common mistake with garbage collected languages such as Java or C# is to keep around references to objects that you no longer are using, or allocating many objects when you could reuse them instead. As long as objects have a reference to them they will continue to use heap space as the garbage collector will not delete them.
In this case you can use a Java memory profiler to determine what methods in your program are allocating large number of objects and then determine if there is a way to make sure they are no longer referenced, or to not allocate them in the first place. One option which I have used in the past is "JMP" http://www.khelekore.org/jmp/.
If you determine that you are allocating these objects for a reason and you need to keep around references (depending on what you are doing this might be the case), you will just need to increase the max heap size when you start the program. However, once you do the memory profiling and understand how your objects are getting allocated you should have a better idea about how much memory you need.
In general if you can't guarantee that your program will run in some finite amount of memory (perhaps depending on input size) you will always run into this problem. Only after exhausting all of this will you need to look into caching objects out to disk etc. At this point you should have a very good reason to say "I need Xgb of memory" for something and you can't work around it by improving your algorithms or memory allocation patterns. Generally this will only usually be the case for algorithms operating on large datasets (like a database or some scientific analysis program) and then techniques like caching and memory mapped IO become useful.
How to see tomcat is running or not
Go to the start menu. Open up cmd (command prompt) and type in the following.
wmic process list brief | find /i "tomcat"
This would tell you if the tomcat is running or not.
Eclipse gives “Java was started but returned exit code 13”
I got this fixed by doing the below steps,
The eclipse finds the JAVA executables from
'C:\ProgramData\Oracle\Java\javapath'
2.The folder structure will contain shortcuts to the below executables,
i. java.exe
ii. javaw.exe
iii. javaws.exe
3.For me the executable paths were pointing to my (ProgramFiles(x84)) folder location
I corrected it to Program Files path(64 bit) and the issue got resolved
Please find the screenshot for the same.
Add JVM options in Tomcat
For this you need to run the "tomcat6w" application that is part of the standard Tomcat distribution in the "bin" directory. E.g. for windows the default is "C:\Program Files\Apache Software Foundation\Tomcat 6.0\bin\tomcat6w.exe". The "tomcat6w" application starts a GUI. If you select the "Java" tab you can enter all Java options.
It is also possible to pass JVM options via the command line to tomcat. For this you need to use the command:
<tomcatexecutable> //US//<tomcatservicename> ++JvmOptions="<JVMoptions>"
where "tomcatexecutable" refers to your tomcat application, "tomcatservicename" is the tomcat service name you are using and "JVMoptions" are your JVM options. For instance:
"tomcat6.exe" //US//tomcat6 ++JvmOptions="-XX:MaxPermSize=128m"
Max value of Xmx and Xms in Eclipse?
I am guessing you are using a 32 bit eclipse with 32 bit JVM. It wont allow heapsize above what you have specified.
Using a 64-bit Eclipse with a 64-bit JVM helps you to start up eclipse with much larger memory. (I am starting with -Xms1024m -Xmx4000m)
GC overhead limit exceeded
From Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning
the following
Excessive GC Time and OutOfMemoryError
The concurrent collector will throw an OutOfMemoryError if too much
time is being spent in garbage collection: if more than 98% of the
total time is spent in garbage collection and less than 2% of the
heap is recovered, an OutOfMemoryError will be thrown. This feature
is designed to prevent applications from running for an extended
period of time while making little or no progress because the heap is
too small. If necessary, this feature can be disabled by adding the
option
-XX:-UseGCOverheadLimit to the command line.
The policy is the same as that in the parallel collector, except that
time spent performing concurrent collections is not counted toward the
98% time limit. In other words, only collections performed while the
application is stopped count toward excessive GC time. Such
collections are typically due to a concurrent mode failure or an
explicit collection request (e.g., a call to System.gc()).
in conjunction with a passage further down
One of the most commonly encountered uses of explicit garbage
collection occurs with RMIs distributed garbage collection (DGC).
Applications using RMI refer to objects in other virtual machines.
Garbage cannot be collected in these distributed applications without
occasionally collection the local heap, so RMI forces full collections
periodically. The frequency of these collections can be controlled
with properties. For example,
java -Dsun.rmi.dgc.client.gcInterval=3600000
-Dsun.rmi.dgc.server.gcInterval=3600000
specifies explicit collection once per hour instead of the default rate of once per
minute. However, this may also cause some objects to take much longer
to be reclaimed. These properties can be set as high as Long.MAX_VALUE
to make the time between explicit collections effectively infinite, if
there is no desire for an upper bound on the timeliness of DGC
activity.
Seems to imply that the evaluation period for determining the 98% is one minute long, but it might be configurable on Sun's JVM with the correct define.
Of course, other interpretations are possible.
How to set a JVM TimeZone Properly
You can pass the JVM this param
-Duser.timezone
For example
-Duser.timezone=Europe/Sofia
and this should do the trick.
Setting the environment variable TZ also does the trick on Linux.
Is it bad practice to use break to exit a loop in Java?
Using break
, just as practically any other language feature, can be a bad practice, within a specific context, where you are clearly misusing it. But some very important idioms cannot be coded without it, or at least would result in far less readable code. In those cases, break
is the way to go.
In other words, don't listen to any blanket, unqualified advice—about break
or anything else. It is not once that I've seen code totally emaciated just to literally enforce a "good practice".
Regarding your concern about performance overhead, there is absolutely none. At the bytecode level there are no explicit loop constructs anyway: all flow control is implemented in terms of conditional jumps.
Java Refuses to Start - Could not reserve enough space for object heap
You need to look at upgrading your OS and Java. Java 5.0 is EOL but if you cannot update to Java 6, you could use the latest patch level 22!
32-bit Windows is limited to ~ 1.3 GB so you are doing well to se the maximum to 1.8. Note: this is a problem with continous memory, and as your system runs its memory space can get fragmented so it does not suprise me you have this problem.
A 64-bit OS, doesn't have this problem as it has much more virtual space, you don't even have to upgrade to a 64-bit version of java to take advantage of this.
BTW, in my experience, 32-bit Java 5.0 can be faster than 64-bit Java 5.0. It wasn't until many years later that Java 6 update 10 was faster for 64-bit.
Setting the JVM via the command line on Windows
You should be able to do this via the command line arguments, assuming these are Sun VMs installed using the usual Windows InstallShield mechanisms with the JVM finder EXE in system32.
Type java -help for the options. In particular, see:
-version:<value>
require the specified version to run
-jre-restrict-search | -jre-no-restrict-search
include/exclude user private JREs in the version search
Java heap terminology: young, old and permanent generations?
The Heap is divided into young and old generations as follows :
Young Generation : It is place where lived for short period and divided into two spaces:
- Eden Space : When object created using new keyword memory allocated
on this space.
- Survivor Space : This is the pool which contains objects which have
survived after java garbage collection from Eden space.
Old Generation : This pool basically contains tenured and virtual
(reserved) space and will be holding those objects which survived
after garbage collection from Young Generation.
- Tenured Space: This memory pool contains objects which survived after multiple garbage collection means object which survived after garbage collection from Survivor space.
Permanent Generation : This memory pool as name also says contain permanent class metadata and descriptors information so PermGen space always reserved for classes and those that is tied to the classes for example static members.
Java8 Update: PermGen is replaced with Metaspace which is very similar.
Main difference is that Metaspace re-sizes dynamically i.e., It can expand at runtime.
Java Metaspace space: unbounded (default)
Code Cache (Virtual or reserved) : If you are using HotSpot Java VM this includes code cache area that containing memory which will be used for compilation and storage of native code.
Courtesy
How to activate JMX on my JVM for access with jconsole?
Run your java application with the following command line parameters:
-Dcom.sun.management.jmxremote.port=8855
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
It is important to use the -Dcom.sun.management.jmxremote.ssl=false parameter if you don't want to setup digital certificates on the jmx host.
If you started your application on a machine having IP address 192.168.0.1, open jconsole, put 192.168.0.1:8855 in the Remote Process field, and click Connect.
Is JVM ARGS '-Xms1024m -Xmx2048m' still useful in Java 8?
Due to PermGen removal some options were removed (like -XX:MaxPermSize
), but options -Xms
and -Xmx
work in Java 8. It's possible that under Java 8 your application simply needs somewhat more memory. Try to increase -Xmx
value. Alternatively you can try to switch to G1 garbage collector using -XX:+UseG1GC
.
Note that if you use any option which was removed in Java 8, you will see a warning upon application start:
$ java -XX:MaxPermSize=128M -version
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=128M; support was removed in 8.0
java version "1.8.0_25"
Java(TM) SE Runtime Environment (build 1.8.0_25-b18)
Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)
How do I write a correct micro-benchmark in Java?
Tips about writing micro benchmarks from the creators of Java HotSpot:
Rule 0: Read a reputable paper on JVMs and micro-benchmarking. A good one is Brian Goetz, 2005. Do not expect too much from micro-benchmarks; they measure only a limited range of JVM performance characteristics.
Rule 1: Always include a warmup phase which runs your test kernel all the way through, enough to trigger all initializations and compilations before timing phase(s). (Fewer iterations is OK on the warmup phase. The rule of thumb is several tens of thousands of inner loop iterations.)
Rule 2: Always run with -XX:+PrintCompilation
, -verbose:gc
, etc., so you can verify that the compiler and other parts of the JVM are not doing unexpected work during your timing phase.
Rule 2.1: Print messages at the beginning and end of timing and warmup phases, so you can verify that there is no output from Rule 2 during the timing phase.
Rule 3: Be aware of the difference between -client
and -server
, and OSR and regular compilations. The -XX:+PrintCompilation
flag reports OSR compilations with an at-sign to denote the non-initial entry point, for example: Trouble$1::run @ 2 (41 bytes)
. Prefer server to client, and regular to OSR, if you are after best performance.
Rule 4: Be aware of initialization effects. Do not print for the first time during your timing phase, since printing loads and initializes classes. Do not load new classes outside of the warmup phase (or final reporting phase), unless you are testing class loading specifically (and in that case load only the test classes). Rule 2 is your first line of defense against such effects.
Rule 5: Be aware of deoptimization and recompilation effects. Do not take any code path for the first time in the timing phase, because the compiler may junk and recompile the code, based on an earlier optimistic assumption that the path was not going to be used at all. Rule 2 is your first line of defense against such effects.
Rule 6: Use appropriate tools to read the compiler's mind, and expect to be surprised by the code it produces. Inspect the code yourself before forming theories about what makes something faster or slower.
Rule 7: Reduce noise in your measurements. Run your benchmark on a quiet machine, and run it several times, discarding outliers. Use -Xbatch
to serialize the compiler with the application, and consider setting -XX:CICompilerCount=1
to prevent the compiler from running in parallel with itself. Try your best to reduce GC overhead, set Xmx
(large enough) equals Xms
and use UseEpsilonGC
if it is available.
Rule 8: Use a library for your benchmark as it is probably more efficient and was already debugged for this sole purpose. Such as JMH, Caliper or Bill and Paul's Excellent UCSD Benchmarks for Java.
Entry point for Java applications: main(), init(), or run()?
Java has a special static method:
public static void main(String[] args) { ... }
which is executed in a class when the class is started with a java command line:
$ java Class
would execute said method in the class "Class" if it existed.
public void run() { ... }
is required by the Runnable interface, or inherited from the Thread class when creating new threads.
how does Request.QueryString work?
The HttpRequest
class represents the request made to the server and has various properties associated with it, such as QueryString
.
The ASP.NET run-time parses a request to the server and populates this information for you.
Read HttpRequest Properties for a list of all the potential properties that get populated on you behalf by ASP.NET.
Note: not all properties will be populated, for instance if your request has no query string, then the QueryString
will be null/empty. So you should check to see if what you expect to be in the query string is actually there before using it like this:
if (!String.IsNullOrEmpty(Request.QueryString["pID"]))
{
// Query string value is there so now use it
int thePID = Convert.ToInt32(Request.QueryString["pID"]);
}
How can I add a table of contents to a Jupyter / JupyterLab notebook?
There are now two packages that can be used to handle Jupyter extensions:
jupyter_contrib_nbextensions that installs extensions, including table of contents;
jupyter_nbextensions_configurator that provides graphical user interfaces for configuring which nbextensions are enabled (load automatically for every notebook) and provides controls to configure the nbextensions' options.
UPDATE:
Starting from recent versions of jupyter_contrib_nbextensions
, at least with conda
you don't need to install jupyter_nbextensions_configurator
because it gets installed together with those extensions.
Is it possible to set transparency in CSS3 box-shadow?
I suppose rgba()
would work here. After all, browser support for both box-shadow
and rgba()
is roughly the same.
/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);
_x000D_
_x000D_
div {_x000D_
width: 200px;_x000D_
height: 50px;_x000D_
line-height: 50px;_x000D_
text-align: center;_x000D_
color: white;_x000D_
background-color: red;_x000D_
margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
_x000D_
_x000D_
Show all tables inside a MySQL database using PHP?
How to get tables
1. SHOW TABLES
mysql> USE test;
Database changed
mysql> SHOW TABLES;
+----------------+
| Tables_in_test |
+----------------+
| t1 |
| t2 |
| t3 |
+----------------+
3 rows in set (0.00 sec)
2. SHOW TABLES IN db_name
mysql> SHOW TABLES IN another_db;
+----------------------+
| Tables_in_another_db |
+----------------------+
| t3 |
| t4 |
| t5 |
+----------------------+
3 rows in set (0.00 sec)
3. Using information schema
mysql> SELECT TABLE_NAME
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'another_db';
+------------+
| TABLE_NAME |
+------------+
| t3 |
| t4 |
| t5 |
+------------+
3 rows in set (0.02 sec)
to OP
you have fetched just 1 row. fix like this:
while ( $tables = $result->fetch_array())
{
echo $tmp[0]."<br>";
}
and I think, information_schema would be better than SHOW TABLES
SELECT TABLE_NAME
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'your database name'
while ( $tables = $result->fetch_assoc())
{
echo $tables['TABLE_NAME']."<br>";
}
Does Arduino use C or C++?
Arduino sketches are written in C++.
Here is a typical construct you'll encounter:
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
...
lcd.begin(16, 2);
lcd.print("Hello, World!");
That's C++, not C.
Hence do yourself a favor and learn C++. There are plenty of books and online resources available.
Comparing date part only without comparing time in JavaScript
You can use some arithmetic with the total of ms.
var date = new Date(date1);
date.setHours(0, 0, 0, 0);
var diff = date2.getTime() - date.getTime();
return diff >= 0 && diff < 86400000;
I like this because no updates to the original dates are made and perfom faster than string split and compare.
Hope this help!
Returning a stream from File.OpenRead()
Try changing your code to this:
private void Test()
{
System.IO.MemoryStream data = new System.IO.MemoryStream(TestStream());
byte[] buf = new byte[data.Length];
data.Read(buf, 0, buf.Length);
}
In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?
That's the non-null assertion operator. It is a way to tell the compiler "this expression cannot be null
or undefined
here, so don't complain about the possibility of it being null
or undefined
." Sometimes the type checker is unable to make that determination itself.
It is explained here:
A new !
post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operation x!
produces a value of the type of x
with null
and undefined
excluded. Similar to type assertions of the forms <T>x
and x as T
, the !
non-null assertion operator is simply removed in the emitted JavaScript code.
I find the use of the term "assert" a bit misleading in that explanation. It is "assert" in the sense that the developer is asserting it, not in the sense that a test is going to be performed. The last line indeed indicates that it results in no JavaScript code being emitted.
How to get current working directory using vba?
Your code: path = ActiveWorkbook.Path
returns blank because you haven't saved your workbook yet.
To overcome your problem, go back to the Excel sheet, save your sheet, and run your code again.
This time it will not show blank, but will show you the path where it is located (current folder)
I hope that helped.
Correct way to remove plugin from Eclipse
Inspired by sergionni's answer, I ended up doing the following steps:
Help --> Installation Details --> Installation History tab
In the Previous configurations
table, you can select a configuration
and see in the Configuration contents
exactly which plugins were installed and are included in it.
It's easy to find the configuration that contains the plugin you want to remove, using the Compare
button. This button is enabled when two configurations are selected.
After tracking the configuration that's responsible for that plugin, select the previous configuration and press the Revert
button.
Note that if you revert to a configuration that isn't the one just right before the Current Installation
, it causes any other plugins that were installed since, to be uninstalled as well.
Multiple Updates in MySQL
You may also be interested in using joins on updates, which is possible as well.
Update someTable Set someValue = 4 From someTable s Inner Join anotherTable a on s.id = a.id Where a.id = 4
-- Only updates someValue in someTable who has a foreign key on anotherTable with a value of 4.
Edit: If the values you are updating aren't coming from somewhere else in the database, you'll need to issue multiple update queries.
docker cannot start on windows
Try running the following from an elevated command prompt:
SET DOCKER_CERT_PATH=C:\Users\[YourName]\.docker\machine\machines\default
SET DOCKER_HOST=tcp://[yourDockerDeamonIp]:2376
SET DOCKER_MACHINE_NAME=default
SET DOCKER_TLS_VERIFY=1
SET DOCKER_TOOLBOX_INSTALL_PATH=C:\Program Files\Docker Toolbox
You might also find that even without setting those env variables, running commands from the docker quick start terminal works no problem.
Adding to a vector of pair
revenue.pushback("string",map[i].second);
But that says cannot take two arguments. So how can I add to this vector pair?
You're on the right path, but think about it; what does your vector hold? It certainly doesn't hold a string and an int in one position, it holds a Pair
. So...
revenue.push_back( std::make_pair( "string", map[i].second ) );
How can I update npm on Windows?
For what it's worth, I had to combine several answers...
- Uninstall Node.js in control panel Add/remove programs.
- Delete directories, both
C:\Program Files (x86)\nodejs\
and C:\Program Files\nodejs\
if they exist.
- Install the latest version, http://nodejs.org/download/
Sorting Characters Of A C++ String
You have to include sort
function which is in algorithm
header file which is a standard template library in c++.
Usage: std::sort(str.begin(), str.end());
#include <iostream>
#include <algorithm> // this header is required for std::sort to work
int main()
{
std::string s = "dacb";
std::sort(s.begin(), s.end());
std::cout << s << std::endl;
return 0;
}
OUTPUT:
abcd
Passing a Bundle on startActivity()?
Passing data from one Activity to Activity in android
An intent contains the action and optionally additional data. The data can be passed to other activity using intent putExtra()
method. Data is passed as extras and are key/value pairs
. The key is always a String. As value you can use the primitive data types int, float, chars, etc. We can also pass Parceable and Serializable
objects from one activity to other.
Intent intent = new Intent(context, YourActivity.class);
intent.putExtra(KEY, <your value here>);
startActivity(intent);
Retrieving bundle data from android activity
You can retrieve the information using getData()
methods on the Intent object. The Intent object can be retrieved via the getIntent()
method.
Intent intent = getIntent();
if (null != intent) { //Null Checking
String StrData= intent.getStringExtra(KEY);
int NoOfData = intent.getIntExtra(KEY, defaultValue);
boolean booleanData = intent.getBooleanExtra(KEY, defaultValue);
char charData = intent.getCharExtra(KEY, defaultValue);
}
Kill detached screen session
It's easier to kill a session, when some meaningful name is given:
//Creation:
screen -S some_name proc
// Kill detached session
screen -S some_name -X quit
Validate date in dd/mm/yyyy format using JQuery Validate
You don't need the date
validator. It doesn't support dd/mm/yyyy format, and that's why you are getting "Please enter a valid date" message for input like 13/01/2014. You already have the dateITA
validator, which uses dd/mm/yyyy format as you need.
Just like the date
validator, your code for dateGreaterThan
and dateLessThan
calls new Date
for input string and has the same issue parsing dates. You can use a function like this to parse the date:
function parseDMY(value) {
var date = value.split("/");
var d = parseInt(date[0], 10),
m = parseInt(date[1], 10),
y = parseInt(date[2], 10);
return new Date(y, m - 1, d);
}
Can scripts be inserted with innerHTML?
I do this every time I wanna insert a script tag dynamically !
const html =
`<script>
alert(' there ! Wanna grab a ');
</script>`;
const scriptEl = document.createRange().createContextualFragment(html);
parent.append(scriptEl);
NOTE: ES6 used
EDIT 1:
Clarification for you guys - I've seen a lot of answers use appendChild
and wanted to let you guys know that it works exactly as append
Error - "UNION operator must have an equal number of expressions" when using CTE for recursive selection
You could use a recursive scalar function:-
set nocount on
create table location (
id int,
name varchar(50),
parent int
)
insert into location values
(1,'france',null),
(2,'paris',1),
(3,'belleville',2),
(4,'lyon',1),
(5,'vaise',4),
(6,'united kingdom',null),
(7,'england',6),
(8,'manchester',7),
(9,'fallowfield',8),
(10,'withington',8)
go
create function dbo.breadcrumb(@child int)
returns varchar(1024)
as begin
declare @returnValue varchar(1024)=''
declare @parent int
select @returnValue+=' > '+name,@parent=parent
from location
where id=@child
if @parent is not null
set @returnValue=dbo.breadcrumb(@parent)+@returnValue
return @returnValue
end
go
declare @location int=1
while @location<=10 begin
print dbo.breadcrumb(@location)+' >'
set @location+=1
end
produces:-
> france >
> france > paris >
> france > paris > belleville >
> france > lyon >
> france > lyon > vaise >
> united kingdom >
> united kingdom > england >
> united kingdom > england > manchester >
> united kingdom > england > manchester > fallowfield >
> united kingdom > england > manchester > withington >
Batch file to delete files older than N days
Have a look at my answer to a similar question:
REM del_old.bat
REM usage: del_old MM-DD-YYY
for /f "tokens=*" %%a IN ('xcopy *.* /d:%1 /L /I null') do if exist %%~nxa echo %%~nxa >> FILES_TO_KEEP.TXT
for /f "tokens=*" %%a IN ('xcopy *.* /L /I /EXCLUDE:FILES_TO_KEEP.TXT null') do if exist "%%~nxa" del "%%~nxa"
This deletes files older than a given date. I'm sure it can be modified to go back seven days from the current date.
update: I notice that HerbCSO has improved on the above script. I recommend using his version instead.
How do I return a string from a regex match in python?
You should use re.MatchObject.group(0)
. Like
imtag = re.match(r'<img.*?>', line).group(0)
Edit:
You also might be better off doing something like
imgtag = re.match(r'<img.*?>',line)
if imtag:
print("yo it's a {}".format(imgtag.group(0)))
to eliminate all the None
s.
Check if element is clickable in Selenium Java
elementToBeClickable
is used for checking an element is visible and enabled such that you can click it.
ExpectedConditions.elementToBeClickable
returns WebElement
if expected condition is true otherwise it will throw TimeoutException
, It never returns null
.
So if your using ExpectedConditions.elementToBeClickable
to find an element which will always gives you the clickable element, so no need to check for null
condition, you should try as below :-
WebDriverWait wait = new WebDriverWait(Scenario1Test.driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("(//div[@id='brandSlider']/div[1]/div/div/div/img)[50]")));
element.click();
As you are saying element.click()
passes both on link
and label
that's doesn't mean element is not clickable, it means returned element clicked
but may be there is no event performs on element by click action.
Note:- I'm suggesting you always try first to find elements by id
, name
, className
and other locator. if you faced some difficulty to find then use cssSelector
and always give last priority to xpath
locator because it is slower than other locator to locate an element.
Hope it helps you..:)
SQL Query with Join, Count and Where
You have to use GROUP BY
so you will have multiple records returned,
SELECT COUNT(*) TotalCount,
b.category_id,
b.category_name
FROM table1 a
INNER JOIN table2 b
ON a.category_id = b.category_id
WHERE a.colour <> 'red'
GROUP BY b.category_id, b.category_name
How to remove list elements in a for loop in Python?
As other answers have said, the best way to do this involves making a new list - either iterate over a copy, or construct a list with only the elements you want and assign it back to the same variable. The difference between these depends on your use case, since they affect other variables for the original list differently (or, rather, the first affects them, the second doesn't).
If a copy isn't an option for some reason, you do have one other option that relies on an understanding of why modifying a list you're iterating breaks. List iteration works by keeping track of an index, incrementing it each time around the loop until it falls off the end of the list. So, if you remove at (or before) the current index, everything from that point until the end shifts one spot to the left. But the iterator doesn't know about this, and effectively skips the next element since it is now at the current index rather than the next one. However, removing things that are after the current index doesn't affect things.
This implies that if you iterate the list back to front, if you remove an item at the current index, everything to it's right shifts left - but that doesn't matter, since you've already dealt with all the elements to the right of the current position, and you're moving left - the next element to the left is unaffected by the change, and so the iterator gives you the element you expect.
TL;DR:
>>> a = list(range(5))
>>> for b in reversed(a):
if b == 3:
a.remove(b)
>>> a
[0, 1, 2, 4]
However, making a copy is usually better in terms of making your code easy to read. I only mention this possibility for sake of completeness.
How to filter files when using scp to copy dir recursively?
I'd probably recommend using something like rsync
for this due to its include
and exclude
flags, e.g:-
rsync -rav -e ssh --include '*/' --include='*.class' --exclude='*' \
server:/usr/some/unknown/number/of/sub/folders/ \
/usr/project/backup/some/unknown/number/of/sub/folders/
Some other useful flags:
-r
for recursive
-a
for archive (mostly all files)
-v
for verbose output
-e
to specify ssh instead of the default (which should be ssh, actually)
Alternate output format for psql
pspg
is a simple tool that offers advanced table formatting, horizontal scrolling, search and many more features.
git clone https://github.com/okbob/pspg.git
cd pspg
./configure
make
make install
then make sure to update PAGER
variable e.g. in your ~/.bashrc
export PAGER="pspg -s 6"
where -s
stands for color scheme (1-14
). If you're using pgdg repositories simply install a package (on Debian-like distribution):
sudo apt install pspg
Python class inherits object
Yes, it's historical. Without it, it creates an old-style class.
If you use type()
on an old-style object, you just get "instance". On a new-style object you get its class.
ConnectivityManager getNetworkInfo(int) deprecated
Many answers still use getNetworkType below 23 which is deprecated; use below code to check if the device has an internet connection.
public static boolean isNetworkConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
return capabilities != null && (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR));
} else {
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnected();
}
}
return false;
}
..
And, do not forget to add this line in Manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Is there a <meta> tag to turn off caching in all browsers?
I noticed some caching issues with service calls when repeating the same service call (long polling). Adding metadata didn't help. One solution is to pass a timestamp
to ensure ie
thinks it's a different http
service request. That worked for me, so adding a server side scripting code snippet to automatically update this tag wouldn't hurt:
<meta http-equiv="expires" content="timestamp">
Can you control how an SVG's stroke-width is drawn?
As people above have noted you'll either have to recalculate an offset to the stroke's path coordinates or double its width and then mask one side or the other, because not only does SVG not natively support Illustrator's stroke alignment, but PostScript doesn't either.
The specification for strokes in Adobe's PostScript Manual 2nd edition states:
"4.5.1 Stroking:
The stroke operator draws a line of some thickness along the current path. For each straight or curved segment in the path, stroke draws a line that is centered on the segment with sides parallel to the segment." (emphasis theirs)
The rest of the specification has no attributes for offsetting the line's position. When Illustrator lets you align inside or outside, it's recalculating the actual path's offset (because it's still computationally cheaper than overprinting then masking). The path coordinates in the .ai document are reference, not what gets rastered or exported to a final format.
Because Inkscape's native format is spec SVG, it can't offer a feature the spec lacks.
Is there a difference between using a dict literal and a dict constructor?
These two approaches produce identical dictionaries, except, as you've noted, where the lexical rules of Python interfere.
Dictionary literals are a little more obviously dictionaries, and you can create any kind of key, but you need to quote the key names. On the other hand, you can use variables for keys if you need to for some reason:
a = "hello"
d = {
a: 'hi'
}
The dict()
constructor gives you more flexibility because of the variety of forms of input it takes. For example, you can provide it with an iterator of pairs, and it will treat them as key/value pairs.
I have no idea why PyCharm would offer to convert one form to the other.
CSS selector for "foo that contains bar"?
No, what you are looking for would be called a parent selector. CSS has none; they have been proposed multiple times but I know of no existing or forthcoming standard including them. You are correct that you would need to use something like jQuery or use additional class annotations to achieve the effect you want.
Here are some similar questions with similar results:
java.lang.IllegalStateException: Fragment not attached to Activity
So the base idea is that you are running a UI operation on a fragment that is getting in the onDetach lifecycle.
When this is happening the fragment is getting off the stack and losing the context of the Activity.
So when you call UI related functions for example calling the progress spinner and you want to leave the fragment check if the Fragment is added to the stack, like this:
if(isAdded){ progressBar.visibility=View.VISIBLE }
Determine function name from within that function (without using traceback)
Here's a future-proof approach.
Combining @CamHart's and @Yuval's suggestions with @RoshOxymoron's accepted answer has the benefit of avoiding:
_hidden
and potentially deprecated methods
- indexing into the stack (which could be reordered in future pythons)
So I think this plays nice with future python versions (tested on 2.7.3 and 3.3.2):
from __future__ import print_function
import inspect
def bar():
print("my name is '{}'".format(inspect.currentframe().f_code.co_name))
Draw horizontal rule in React Native
This is how i solved divider with horizontal lines and text in the midddle:
<View style={styles.divider}>
<View style={styles.hrLine} />
<Text style={styles.dividerText}>OR</Text>
<View style={styles.hrLine} />
</View>
And styles for this:
import { Dimensions, StyleSheet } from 'react-native'
const { width } = Dimensions.get('window')
const styles = StyleSheet.create({
divider: {
flexDirection: 'row',
alignItems: 'center',
marginTop: 10,
},
hrLine: {
width: width / 3.5,
backgroundColor: 'white',
height: 1,
},
dividerText: {
color: 'white',
textAlign: 'center',
width: width / 8,
},
})
JSON.NET Error Self referencing loop detected for type
To ignore loop references and not to serialize them globally in MVC 6 use the following in startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().Configure<MvcOptions>(options =>
{
options.OutputFormatters.RemoveTypesOf<JsonOutputFormatter>();
var jsonOutputFormatter = new JsonOutputFormatter();
jsonOutputFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
options.OutputFormatters.Insert(0, jsonOutputFormatter);
});
}
How do I make a MySQL database run completely in memory?
Assuming you understand the consequences of using the MEMORY engine as mentioned in comments, and here, as well as some others you'll find by searching about (no transaction safety, locking issues, etc) - you can proceed as follows:
MEMORY tables are stored differently than InnoDB, so you'll need to use an export/import strategy. First dump each table separately to a file using SELECT * FROM tablename INTO OUTFILE 'table_filename'
. Create the MEMORY database and recreate the tables you'll be using with this syntax: CREATE TABLE tablename (...) ENGINE = MEMORY;
. You can then import your data using LOAD DATA INFILE 'table_filename' INTO TABLE tablename
for each table.
Mutex lock threads
What you need to do is to call pthread_mutex_lock to secure a mutex, like this:
pthread_mutex_lock(&mutex);
Once you do this, any other calls to pthread_mutex_lock(mutex)
will not return until you call pthread_mutex_unlock
in this thread. So if you try to call pthread_create, you will be able to create a new thread, and that thread will be able to (incorrectly) use the shared resource. You should call pthread_mutex_lock
from within your fooAPI
function, and that will cause the function to wait until the shared resource is available.
So you would have something like this:
#include <pthread.h>
#include <stdio.h>
int sharedResource = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* fooAPI(void* param)
{
pthread_mutex_lock(&mutex);
printf("Changing the shared resource now.\n");
sharedResource = 42;
pthread_mutex_unlock(&mutex);
return 0;
}
int main()
{
pthread_t thread;
// Really not locking for any reason other than to make the point.
pthread_mutex_lock(&mutex);
pthread_create(&thread, NULL, fooAPI, NULL);
sleep(1);
pthread_mutex_unlock(&mutex);
// Now we need to lock to use the shared resource.
pthread_mutex_lock(&mutex);
printf("%d\n", sharedResource);
pthread_mutex_unlock(&mutex);
}
Edit: Using resources across processes follows this same basic approach, but you need to map the memory into your other process. Here's an example using shmem:
#include <stdio.h>
#include <unistd.h>
#include <sys/file.h>
#include <sys/mman.h>
#include <sys/wait.h>
struct shared {
pthread_mutex_t mutex;
int sharedResource;
};
int main()
{
int fd = shm_open("/foo", O_CREAT | O_TRUNC | O_RDWR, 0600);
ftruncate(fd, sizeof(struct shared));
struct shared *p = (struct shared*)mmap(0, sizeof(struct shared),
PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
p->sharedResource = 0;
// Make sure it can be shared across processes
pthread_mutexattr_t shared;
pthread_mutexattr_init(&shared);
pthread_mutexattr_setpshared(&shared, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&(p->mutex), &shared);
int i;
for (i = 0; i < 100; i++) {
pthread_mutex_lock(&(p->mutex));
printf("%d\n", p->sharedResource);
pthread_mutex_unlock(&(p->mutex));
sleep(1);
}
munmap(p, sizeof(struct shared*));
shm_unlink("/foo");
}
Writing the program to make changes to p->sharedResource is left as an exercise for the reader. :-)
Forgot to note, by the way, that the mutex has to have the PTHREAD_PROCESS_SHARED attribute set, so that pthreads will work across processes.
python and sys.argv
BTW you can pass the error message directly to sys.exit:
if len(sys.argv) < 2:
sys.exit('Usage: %s database-name' % sys.argv[0])
if not os.path.exists(sys.argv[1]):
sys.exit('ERROR: Database %s was not found!' % sys.argv[1])
What exactly is \r in C language?
' \r ' means carriage return.
The \r means nothing special as a consequence.For character-mode terminals (typically emulating even-older printing ones as above), in raw mode, \r and \n act similarly (except both in terms of the cursor, as there is no carriage or roller . Historically a \n was used to move the carriage down, while the \r was used to move the carriage back to the left side of the screen.
WCF error - There was no endpoint listening at
I was getting the same error with a service access. It was working in browser, but wasnt working when I try to access it in my asp.net/c# application. I changed application pool from appPoolIdentity to NetworkService, and it start working. Seems like a permission issue to me.
.gitignore exclude folder but include specific subfolder
If you exclude application/
, then everything under it will always be excluded (even if some later negative exclusion pattern (“unignore”) might match something under application/
).
To do what you want, you have to “unignore” every parent directory of anything that you want to “unignore”. Usually you end up writing rules for this situation in pairs: ignore everything in a directory, but not some certain subdirectory.
# you can skip this first one if it is not already excluded by prior patterns
!application/
application/*
!application/language/
application/language/*
!application/language/gr/
Note
The trailing /*
is significant:
- The pattern
dir/
excludes a directory named dir
and (implicitly) everything under it.
With dir/
, Git will never look at anything under dir
, and thus will never apply any of the “un-exclude” patterns to anything under dir
.
- The pattern
dir/*
says nothing about dir
itself; it just excludes everything under dir
.
With dir/*
, Git will process the direct contents of dir
, giving other patterns a chance to “un-exclude” some bit of the content (!dir/sub/
).
Pandas aggregate count distinct
Just adding to the answers already given, the solution using the string "nunique"
seems much faster, tested here on ~21M rows dataframe, then grouped to ~2M
%time _=g.agg({"id": lambda x: x.nunique()})
CPU times: user 3min 3s, sys: 2.94 s, total: 3min 6s
Wall time: 3min 20s
%time _=g.agg({"id": pd.Series.nunique})
CPU times: user 3min 2s, sys: 2.44 s, total: 3min 4s
Wall time: 3min 18s
%time _=g.agg({"id": "nunique"})
CPU times: user 14 s, sys: 4.76 s, total: 18.8 s
Wall time: 24.4 s
Any way of using frames in HTML5?
I know your class is over, but in professional coding, let this be a lesson:
- "Deprecated" means "avoid use; it's going to be removed in the future"
- Deprecated things still work - just don't expect support or future-proofing
- If the requirement requires it, and you can't negotiate it away, just use the deprecated construct.
- If you're really concerned, develop the alternative implementation on the side and keep it ready for the inevitable failure
- Charge for the extra work now. By requesting a deprecated feature, they are asking you to double the work. You're going to see it again anyway, so might as well front-load it.
- When the failure happens, let the interested party know that this was what you feared; that you prepared for it, but it'll take some time
- Deploy your solution as quickly as you can (there will be bugs)
- Gain rep for preventing excessive downtime.
Undefined function mysql_connect()
(Windows mysql config)
Step 1 : Go To Apache Control Panel > Apache > Config > PHP.ini
Step 2 : Search in Notepad (Ctrl+F) For: ;extension_dir = ""
(could be commented with a ;
). Replace this line with: extension_dir = "C:\php\ext"
(please do not you need to remove the ;
on the beginning of the sentence).
Step 3 : Search For: extension=php_mysql.dll
and remove the ;
in the beginning.
Step 4 : Save and Restart You Apache HTTP Server. (On Windows this usually done via a UI)
That's it :)
If you get errors about missing php_mysql.dll
you'll probably need to download this file from either the php.net site or the pecl.php.net. (Please be causius about where you get it from)
More info on PHP: Installation of extensions on Windows - Manual
What's wrong with using == to compare floats in Java?
Just to give the reason behind what everyone else is saying.
The binary representation of a float is kind of annoying.
In binary, most programmers know the correlation between 1b=1d, 10b=2d, 100b=4d, 1000b=8d
Well it works the other way too.
.1b=.5d, .01b=.25d, .001b=.125, ...
The problem is that there is no exact way to represent most decimal numbers like .1, .2, .3, etc. All you can do is approximate in binary. The system does a little fudge-rounding when the numbers print so that it displays .1 instead of .10000000000001 or .999999999999 (which are probably just as close to the stored representation as .1 is)
Edit from comment: The reason this is a problem is our expectations. We fully expect 2/3 to be fudged at some point when we convert it to decimal, either .7 or .67 or .666667.. But we don't automatically expect .1 to be rounded in the same way as 2/3--and that's exactly what's happening.
By the way, if you are curious the number it stores internally is a pure binary representation using a binary "Scientific Notation". So if you told it to store the decimal number 10.75d, it would store 1010b for the 10, and .11b for the decimal. So it would store .101011 then it saves a few bits at the end to say: Move the decimal point four places right.
(Although technically it's no longer a decimal point, it's now a binary point, but that terminology wouldn't have made things more understandable for most people who would find this answer of any use.)
Grep regex NOT containing string
patterns[1]="1\.2\.3\.4.*Has exploded"
patterns[2]="5\.6\.7\.8.*Has died"
patterns[3]="\!9\.10\.11\.12.*Has exploded"
for i in {1..3}
do
grep "${patterns[$i]}" logfile.log
done
should be the the same as
egrep "(1\.2\.3\.4.*Has exploded|5\.6\.7\.8.*Has died)" logfile.log | egrep -v "9\.10\.11\.12.*Has exploded"
Summarizing count and conditional aggregate functions on the same factor
Assuming that your original dataset is similar to the one you created (i.e. with NA
as character
. You could specify na.strings
while reading the data using read.table
. But, I guess NAs would be detected automatically.
The price
column is factor
which needs to be converted to numeric
class. When you use as.numeric
, all the non-numeric elements (i.e. "NA"
, FALSE) gets coerced to NA
) with a warning.
library(dplyr)
df %>%
mutate(price=as.numeric(as.character(price))) %>%
group_by(company, year, product) %>%
summarise(total.count=n(),
count=sum(is.na(price)),
avg.price=mean(price,na.rm=TRUE),
max.price=max(price, na.rm=TRUE))
data
I am using the same dataset
(except the ...
row) that was showed.
df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
"Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
"7.12", "12.99", "10.99", "NA",FALSE)))
Accessing post variables using Java Servlets
The previous answers are correct but remember to use the name attribute in the input fields (html form) or you won't get anything. Example:
<input type="text" id="username" /> <!-- won't work -->
<input type="text" name="username" /> <!-- will work -->
<input type="text" name="username" id="username" /> <!-- will work too -->
All this code is HTML valid, but using getParameter(java.lang.String) you will need the name attribute been set in all parameters you want to receive.
Java program to get the current date without timestamp
The accepted answer by Jesper is correct but now outdated. The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them.
java.time
Instead use the java.time framework, built into Java 8 and later, back-ported to Java 6 & 7 and further adapted to Android.
If you truly do not care about time-of-day and time zones, use LocalDate
in the java.time framework ().
LocalDate localDate = LocalDate.of( 2014 , 5 , 6 );
Today
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. If you want to use the JVM’s current default time zone, make your intention clear by calling ZoneId.systemDefault()
. If critical, confirm the zone with your user.
Specify a proper time zone name in the format of Continent/Region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 2-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
LocalDate today = LocalDate.now( z ) ;
Moment
If you care about specific moments, specific points on the timeline, do not use LocalDate
. If you care about the date as seen through the wall-clock time used by the people of a certain region, do not use LocalDate
.
Be aware that if you have any chance of needing to deal with other time zones or UTC, this is the wrong way to go. Naïve programmers tend to think they do not need time zones when in fact they do.
Strings
Call toString
to generate a string in standard ISO 8601 format.
String output = localDate.toString();
2014-05-06
For other formats, search Stack Overflow for DateTimeFormatter
class.
Joda-Time
Though now supplanted by java.time, you can use the similar LocalDate
class in the Joda-Time library (the inspiration for java.time).
LocalDate localDate = new LocalDate( 2014, 5, 6 );
Prevent flex items from overflowing a container
It's not suitable for every situation, because not all items can have a non-proportional maximum, but slapping a good ol' max-width
on the offending element/container can put it back in line.
Using custom fonts using CSS?
there's also an interesting tool called CUFON. There's a demonstration of how to use it in this blog
It's really simple and interesting. Also, it doesn't allow people to ctrl+c/ctrl+v the generated content.
Python/Json:Expecting property name enclosed in double quotes
This:
{
'http://example.org/about': {
'http://purl.org/dc/terms/title': [
{'type': 'literal', 'value': "Anna's Homepage"}
]
}
}
is not JSON.
This:
{
"http://example.org/about": {
"http://purl.org/dc/terms/title": [
{"type": "literal", "value": "Anna's Homepage"}
]
}
}
is JSON.
EDIT:
Some commenters suggested that the above is not enough.
JSON specification - RFC7159 states that a string begins and ends with quotation mark. That is "
.
Single quoute '
has no semantic meaning in JSON and is allowed only inside a string.
Trying to detect browser close event
Following script will give message on Chrome and IE:
<script>
window.onbeforeunload = function (e) {
// Your logic to prepare for 'Stay on this Page' goes here
return "Please click 'Stay on this Page' and we will give you candy";
};
</script>
Chrome
IE
on Firefox you will get generic message
Mechanism is synchronous so no server calls to delay will work, you still can prepare a mechanism like modal window that is shown if user decides to stay on page, but no way to prevent him from leaving.
Response to question in comment
F5 will fire event again, so will Atl+F4.
Using number as "index" (JSON)
JSON only allows key names to be strings. Those strings can consist of numerical values.
You aren't using JSON though. You have a JavaScript object literal. You can use identifiers for keys, but an identifier can't start with a number. You can still use strings though.
var Game={
"status": [
{
"0": "val",
"1": "val",
"2": "val"
},
{
"0": "val",
"1": "val",
"2": "val"
}
]
}
If you access the properties with dot-notation, then you have to use identifiers. Use square bracket notation instead: Game.status[0][0]
.
But given that data, an array would seem to make more sense.
var Game={
"status": [
[
"val",
"val",
"val"
],
[
"val",
"val",
"val"
]
]
}
PHP create key => value pairs within a foreach
Create key-value pairs within a foreach like this:
function createOfferUrlArray($Offer) {
$offerArray = array();
foreach ($Offer as $key => $value) {
$offerArray[$key] = $value[4];
}
return $offerArray;
}
Using unset vs. setting a variable to empty
So, by unset'ting the array index 2, you essentially remove that element in the array and decrement the array size (?).
I made my own test..
foo=(5 6 8)
echo ${#foo[*]}
unset foo
echo ${#foo[*]}
Which results in..
3
0
So just to clarify that unset'ting the entire array will in fact remove it entirely.
Programmatically obtain the phone number of the Android phone
First of all getting users mobile number is against the Ethical policy, earlier it was possible but now as per my research there no solid solution available for this, By using some code it is possible to get mobile number but no guarantee may be it will work only in few device. After lot of research i found only three solution but they are not working in all device.
There is the following reason why we are not getting.
1.Android device and new Sim Card not storing mobile number if mobile number is not available in device and in sim then how it is possible to get number, if any old sim card having mobile number then using Telephony manager we can get the number other wise it will return the “null” or “” or “??????”
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
TelephonyManager tel= (TelephonyManager)this.getSystemService(Context.
TELEPHONY_SERVICE);
String PhoneNumber = tel.getLine1Number();
Note:- I have tested this solution in following device Moto x, Samsung Tab 4, Samsung S4, Nexus 5 and Redmi 2 prime but it doesn’t work every
time it return empty string so conclusion is it's useless
- This method is working only in Redmi 2 prime, but for this need to add
read contact permission in manifest.
Note:- This is also not the guaranteed and efficient solution, I have tested this solution in many device but it worked only in Redmi 2 prime
which is dual sim device it gives me two mobile number first one is
correct but the second one is not belong to my second sim it belong to
my some old sim card which i am not using.
String main_data[] = {"data1", "is_primary", "data3", "data2", "data1",
"is_primary", "photo_uri", "mimetype"};
Object object = getContentResolver().
query(Uri.withAppendedPath(android.provider.ContactsContract.Profile.CONTENT_URI, "data"),
main_data, "mimetype=?",
new String[]{"vnd.android.cursor.item/phone_v2"},
"is_primary DESC");
String s1="";
if (object != null) {
do {
if (!((Cursor) (object)).moveToNext())
break;
// This is the phoneNumber
s1 =s1+"---"+ ((Cursor) (object)).getString(4);
} while (true);
((Cursor) (object)).close();
}
- In my research i have found earlier it was possible to get mobile number using WhatsApp account but now new Whatsapp version doesn’t storing user's mobile number.
Conclusion:- Android doesn’t have any guaranteed solution to get
user's mobile number programmatically.
Suggestion:- 1. If you want to verify user’s mobile number then ask to
user to provide his number, using otp you can can verify that.
- If you want to identify the user’s device, for this you can easily get device IMEI number.
Reference - What does this regex mean?
The Stack Overflow Regular Expressions FAQ
See also a lot of general hints and useful links at the regex tag details page.
Online tutorials
Quantifiers
- Zero-or-more:
*
:greedy, *?
:reluctant, *+
:possessive
- One-or-more:
+
:greedy, +?
:reluctant, ++
:possessive
?
:optional (zero-or-one)
- Min/max ranges (all inclusive):
{n,m}
:between n & m, {n,}
:n-or-more, {n}
:exactly n
- Differences between greedy, reluctant (a.k.a. "lazy", "ungreedy") and possessive quantifier:
Character Classes
Escape Sequences
Anchors
^
:start of line/input, \b
:word boundary, and \B
:non-word boundary, $
:end of line/input
\A
:start of input, \Z
:end of input php, perl, ruby
\z
:the very end of input (\Z
in Python) .net, php, pcre, java, ruby, icu, swift, objective-c
\G
:start of match php, perl, ruby
(Also see "Flavor-Specific Information ? Java ? The functions in Matcher
")
Groups
Lookarounds
Modifiers
Other:
Common Tasks
Advanced Regex-Fu
- Strings and numbers:
- Other:
Flavor-Specific Information
(Except for those marked with *
, this section contains non-Stack Overflow links.)
- Java
- .NET
- Official documentation:
- Boost regex engine: General syntax, Perl syntax (used by TextPad, Sublime Text, UltraEdit, ...???)
- JavaScript 1.5 general info and RegExp object
- .NET MySQL Oracle Perl5 version 18.2
- PHP: pattern syntax,
preg_match
- Python: Regular expression operations,
search
vs match
, how-to
- Rust: crate
regex
, struct regex::Regex
- Splunk: regex terminology and syntax and regex command
- Tcl: regex syntax, manpage,
regexp
command
- Visual Studio Find and Replace
General information
(Links marked with *
are non-Stack Overflow links.)
Examples of regex that can cause regex engine to fail
Tools: Testers and Explainers
(This section contains non-Stack Overflow links.)
Hashing a string with Sha256
I also had this problem with another style of implementation but I forgot where I got it since it was 2 years ago.
static string sha256(string randomString)
{
var crypt = new SHA256Managed();
string hash = String.Empty;
byte[] crypto = crypt.ComputeHash(Encoding.ASCII.GetBytes(randomString));
foreach (byte theByte in crypto)
{
hash += theByte.ToString("x2");
}
return hash;
}
When I input something like abcdefghi2013
for some reason it gives different results and results in errors in my login module.
Then I tried modifying the code the same way as suggested by Quuxplusone and changed the encoding from ASCII
to UTF8
then it finally worked!
static string sha256(string randomString)
{
var crypt = new System.Security.Cryptography.SHA256Managed();
var hash = new System.Text.StringBuilder();
byte[] crypto = crypt.ComputeHash(Encoding.UTF8.GetBytes(randomString));
foreach (byte theByte in crypto)
{
hash.Append(theByte.ToString("x2"));
}
return hash.ToString();
}
Thanks again Quuxplusone for the wonderful and detailed answer! :)
Why am I getting "Unable to find manifest signing certificate in the certificate store" in my Excel Addin?
The issue of erroneous leftover entries in the .csproj file still occurs with VS2015update3 and can also occur if you try to change the signing certificate for a different one (even if that is one generated using the 'new' option in the certificate selection dropdown).
The advice in the accepted answer (mark as not signed, save, unload project, edit .csproj, remove the properties relating to the old certificates/thumbprints/keys & reload project, set certificate) is reliable.
Implement specialization in ER diagram
So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]
Conversion failed when converting the varchar value to data type int in sql
Try this one -
CREATE PROC [dbo].[getVoucherNo]
AS BEGIN
DECLARE
@Prefix VARCHAR(10) = 'J'
, @startFrom INT = 1
, @maxCode VARCHAR(100)
, @sCode INT
IF EXISTS(
SELECT 1
FROM dbo.Journal_Entry
) BEGIN
SELECT @maxCode = CAST(MAX(CAST(SUBSTRING(Voucher_No,LEN(@startFrom)+1,ABS(LEN(Voucher_No)- LEN(@Prefix))) AS INT)) AS varchar(100))
FROM dbo.Journal_Entry;
SELECT @Prefix +
CAST(LEN(LEFT(@maxCode, 10) + 1) AS VARCHAR(10)) + -- !!! possible problem here
CAST(@maxCode AS VARCHAR(100))
END
ELSE BEGIN
SELECT (@Prefix + CAST(@startFrom AS VARCHAR))
END
END
How to use python numpy.savetxt to write strings and float number to an ASCII file?
The currently accepted answer does not actually address the question, which asks how to save lists that contain both strings and float numbers. For completeness I provide a fully working example, which is based, with some modifications, on the link given in @joris comment.
import numpy as np
names = np.array(['NAME_1', 'NAME_2', 'NAME_3'])
floats = np.array([ 0.1234 , 0.5678 , 0.9123 ])
ab = np.zeros(names.size, dtype=[('var1', 'U6'), ('var2', float)])
ab['var1'] = names
ab['var2'] = floats
np.savetxt('test.txt', ab, fmt="%10s %10.3f")
Update: This example also works properly in Python 3 by using the 'U6'
Unicode string dtype, when creating the ab
structured array, instead of the 'S6'
byte string. The latter dtype would work in Python 2.7, but would write strings like b'NAME_1'
in Python 3.
Websocket connections with Postman
It's not possible in Postman yet; But there is a new alternative for Postman, named Postwoman. it's open source and supports realtime Websocket and SSE requests.
Update
It seems they have rebranded Postwoman to Hoppscotch and have improved the Websocket support.
The most efficient way to implement an integer based power function pow(int, int)
Just as a follow up to comments on the efficiency of exponentiation by squaring.
The advantage of that approach is that it runs in log(n) time. For example, if you were going to calculate something huge, such as x^1048575 (2^20 - 1), you only have to go thru the loop 20 times, not 1 million+ using the naive approach.
Also, in terms of code complexity, it is simpler than trying to find the most optimal sequence of multiplications, a la Pramod's suggestion.
Edit:
I guess I should clarify before someone tags me for the potential for overflow. This approach assumes that you have some sort of hugeint library.
How do I execute external program within C code in linux with arguments?
Here's the way to extend to variable args when you don't have the args hard coded (although they are still technically hard coded in this example, but should be easy to figure out how to extend...):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int argcount = 3;
const char* args[] = {"1", "2", "3"};
const char* binary_name = "mybinaryname";
char myoutput_array[5000];
sprintf(myoutput_array, "%s", binary_name);
for(int i = 0; i < argcount; ++i)
{
strcat(myoutput_array, " ");
strcat(myoutput_array, args[i]);
}
system(myoutput_array);
How can I force gradle to redownload dependencies?
For Windows...in order to make gradle re-download specific dependencies:
delete the dependencies you want to re-download from the directory below:
C:\Users\%USERNAME%\.gradle\caches\modules-2\files-2.1
delete all metadata directories at the path:
C:\Users\%USERNAME%\.gradle\caches\modules-2\metadata-*
run gradle build
(or gradlew build
if using gradle wrapper) in the project's root directory.
note: the numbers in the file paths above might be different for you.
If strings starts with in PowerShell
$Group
is an object, but you will actually need to check if $Group.samaccountname.StartsWith("string")
.
Change $Group.StartsWith("S_G_")
to $Group.samaccountname.StartsWith("S_G_")
.
How to copy folders to docker image from Dockerfile?
Like @Vonc said, there is no possibility to add a command like as of now. The only workaround is to mention the folder, to create it and add contents to it.
# add contents to folder
ADD src $HOME/src
Would create a folder called src in your directory and add contents of your folder src into this.
How can I pass a parameter to a t-sql script?
Two options
save vijay.sql
declare
begin
execute immediate
'CREATE TABLE DMS_POP_WKLY_REFRESH_'||to_char(sysdate,'YYYYMMDD')||' NOLOGGING PARALLEL AS
SELECT wk.*,bbc.distance_km ,NVL(bbc.tactical_broadband_offer,0) tactical_broadband_offer ,
sel.tactical_select_executive_flag,
sel.agent_name,
res.DMS_RESIGN_CAMPAIGN_CODE,
pclub.tactical_select_flag
FROM spineowner.pop_wkly_refresh_20100201 wk,
dms_bb_coverage_102009 bbc,
dms_select_executive_group sel,
DMS_RESIGN_CAMPAIGN_26052009 res,
DMS_PRIORITY_CLUB pclub
WHERE wk.mpn = bbc.mpn(+)
AND wk.mpn = sel.mpn (+)
AND wk.mpn = res.mpn (+)
AND wk.mpn = pclub.mpn (+)'
end;
/
The above will generate table names automatically based on sysdate. If you still need to pass as variable, then save vijay.sql as
declare
begin
execute immediate
'CREATE TABLE DMS_POP_WKLY_REFRESH_'||&1||' NOLOGGING PARALLEL AS
SELECT wk.*,bbc.distance_km ,NVL(bbc.tactical_broadband_offer,0) tactical_broadband_offer ,
sel.tactical_select_executive_flag,
sel.agent_name,
res.DMS_RESIGN_CAMPAIGN_CODE,
pclub.tactical_select_flag
FROM spineowner.pop_wkly_refresh_20100201 wk,
dms_bb_coverage_102009 bbc,
dms_select_executive_group sel,
DMS_RESIGN_CAMPAIGN_26052009 res,
DMS_PRIORITY_CLUB pclub
WHERE wk.mpn = bbc.mpn(+)
AND wk.mpn = sel.mpn (+)
AND wk.mpn = res.mpn (+)
AND wk.mpn = pclub.mpn (+)'
end;
/
and then run as
sqlplus -s username/password @vijay.sql '20100101'
How can I generate a unique ID in Python?
import time
import random
import socket
import hashlib
def guid( *args ):
"""
Generates a universally unique ID.
Any arguments only create more randomness.
"""
t = long( time.time() * 1000 )
r = long( random.random()*100000000000000000L )
try:
a = socket.gethostbyname( socket.gethostname() )
except:
# if we can't get a network address, just imagine one
a = random.random()*100000000000000000L
data = str(t)+' '+str(r)+' '+str(a)+' '+str(args)
data = hashlib.md5(data).hexdigest()
return data
character count using jquery
For length including white-space:
$("#id").val().length
For length without white-space:
$("#id").val().replace(/ /g,'').length
For removing only beginning and trailing white-space:
$.trim($("#test").val()).length
For example, the string " t e s t "
would evaluate as:
//" t e s t "
$("#id").val();
//Example 1
$("#id").val().length; //Returns 9
//Example 2
$("#id").val().replace(/ /g,'').length; //Returns 4
//Example 3
$.trim($("#test").val()).length; //Returns 7
Here is a demo using all of them.
Get folder name of the file in Python
You can use dirname
:
os.path.dirname(path)
Return the directory name of pathname path. This is the first element
of the pair returned by passing path to the function split().
And given the full path, then you can split normally to get the last portion of the path. For example, by using basename
:
os.path.basename(path)
Return the base name of pathname path. This is the second element of
the pair returned by passing path to the function split(). Note that
the result of this function is different from the Unix basename
program; where basename for '/foo/bar/' returns 'bar', the basename()
function returns an empty string ('').
All together:
>>> import os
>>> path=os.path.dirname("C:/folder1/folder2/filename.xml")
>>> path
'C:/folder1/folder2'
>>> os.path.basename(path)
'folder2'
'import' and 'export' may only appear at the top level
I got this error after upgrading to webpack 4.29.x. It turned out that webpack 4.29.x triggered npm's peerDependency bug. And according to them, the bug is not going to get fixed soon. Here's the workaround from sokra
- add
"acorn": "^6.0.5"
to your application package.json.
- Switch to
yarn
. It doesn't have this bug.
npm update acorn --depth 20
npm dedupe
(works only in some cases)
rm package-lock.json
npm i
(works only in some cases)
- update all other packages that depend on an older version for acorn (works only in some cases)
- lock webpack at
4.28.4
in your package.json
Update
According to comment below, this bug doesn't exist anymore after 4.36.0
Which is the best IDE for Python For Windows
Python is dynamic language so the IDE can do only so much in terms of code intelligence and syntax checking but I personally recommend Komode IDE, it's pretty slick on OS/X and Windows. I've experienced high cpu use with Linux but not sure if it's caused by my VirtualBox environment.
You can also try Eclipse with PyDev plugin. It's heavier so performance might become a problem though.
batch file to list folders within a folder to one level
I tried this command to display the list of files in the directory.
dir /s /b > List.txt
In the file it displays the list below.
C:\Program Files (x86)\Cisco Systems\Cisco Jabber\XmppMgr.dll
C:\Program Files (x86)\Cisco Systems\Cisco Jabber\XmppSDK.dll
C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Plantronics
C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\SennheiserJabberPlugin.dll
C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Logitech\LogiUCPluginForCisco
C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Logitech\LogiUCPluginForCisco\lucpcisco.dll
What is want to do is only to display sub-directory not the full directory path.
Just like this:
Cisco Jabber\XmppMgr.dll Cisco Jabber\XmppSDK.dll
Cisco Jabber\accessories\JabraJabberPlugin.dll
Cisco Jabber\accessories\Logitech
Cisco Jabber\accessories\Plantronics
Cisco Jabber\accessories\SennheiserJabberPlugin.dll
How can I reorder my divs using only CSS?
Negative top margins can achieve this effect, but they would need to be customized for each page. For instance, this markup...
<div class="product">
<h2>Greatest Product Ever</h2>
<p class="desc">This paragraph appears in the source code directly after the heading and will appear in the search results.</p>
<p class="sidenote">Note: This information appears in HTML after the product description appearing below.</p>
</div>
...and this CSS...
.product { width: 400px; }
.desc { margin-top: 5em; }
.sidenote { margin-top: -7em; }
...would allow you to pull the second paragraph above the first.
Of course, you'll have to manually tweak your CSS for different description lengths so that the intro paragraph jumps up the appropriate amount, but if you have limited control over the other parts and full control over markup and CSS then this might be an option.
Find a pair of elements from an array whose sum equals a given number
Solution in java. You can add all the String elements to an ArrayList of strings and return the list. Here I am just printing it out.
void numberPairsForSum(int[] array, int sum) {
HashSet<Integer> set = new HashSet<Integer>();
for (int num : array) {
if (set.contains(sum - num)) {
String s = num + ", " + (sum - num) + " add up to " + sum;
System.out.println(s);
}
set.add(num);
}
}
difference between variables inside and outside of __init__()
In Python, a class comes with member functions (methods), class variables, attributes/instance variables (and probably class methods too):
class Employee:
# Class Variable
company = "mycompany.com"
def __init__(self, first_name, last_name, position):
# Instance Variables
self._first_name = first_name
self._last_name = last_name
self._position = position
# Member function
def get_full_name(self):
return f"{self._first_name} {self._last_name}"
By creating an instance of the object
my_employee = Employee("John", "Wood", "Software Engineer")
we essentially trigger __init__
that is going to initialise the instance variables of the newly created Employee
. This means that _first_name
, _last_name
and _position
are explicit parameters of the specific my_employee
instance.
Likewise, member functions return information or change the state of a specific instance.
Now any variable defined outside the constructor __init__
are considered to be class variables. Those variables are shared amongst all the instances of the class.
john = Employee("John", "Wood", "Software Engineer")
bob = Employee("Bob", "Smith", "DevOps Engineer0")
print(john.get_full_name())
print(bob.get_full_name())
print(john.company)
print(bob.company)
>>> John Wood
>>> Bob Smith
>>> mycompany.com
>>> mycompany.com
You can also use class methods in order to change the class variable for all the instances of the class. For example:
@classmethod
def change_my_companys_name(cls, name):
cls.company = name
and now change_my_companys_name()
bob.change_my_companys_name("mynewcompany.com")
will have effect on all the instances of class Employee
:
print(bob.company)
print(john.company)
>>> mynewcompany.com
>>> mynewcompany.com
Error: " 'dict' object has no attribute 'iteritems' "
I had a similar problem (using 3.5) and lost 1/2 a day to it but here is a something that works - I am retired and just learning Python so I can help my grandson (12) with it.
mydict2={'Atlanta':78,'Macon':85,'Savannah':72}
maxval=(max(mydict2.values()))
print(maxval)
mykey=[key for key,value in mydict2.items()if value==maxval][0]
print(mykey)
YEILDS;
85
Macon
Internal Error 500 Apache, but nothing in the logs?
Please check if you are disable error reporting somewhere in your code.
There was a place in my code where I have disabled it, so I added the debug code after it:
require_once("inc/req.php"); <-- Error reporting is disabled here
// overwrite it
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
How to use fetch in typescript
A few examples follow, going from basic through to adding transformations after the request and/or error handling:
Basic:
// Implementation code where T is the returned data shape
function api<T>(url: string): Promise<T> {
return fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json<T>()
})
}
// Consumer
api<{ title: string; message: string }>('v1/posts/1')
.then(({ title, message }) => {
console.log(title, message)
})
.catch(error => {
/* show error message */
})
Data transformations:
Often you may need to do some tweaks to the data before its passed to the consumer, for example, unwrapping a top level data attribute. This is straight forward:
function api<T>(url: string): Promise<T> {
return fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json<{ data: T }>()
})
.then(data => { /* <-- data inferred as { data: T }*/
return data.data
})
}
// Consumer - consumer remains the same
api<{ title: string; message: string }>('v1/posts/1')
.then(({ title, message }) => {
console.log(title, message)
})
.catch(error => {
/* show error message */
})
Error handling:
I'd argue that you shouldn't be directly error catching directly within this service, instead, just allowing it to bubble, but if you need to, you can do the following:
function api<T>(url: string): Promise<T> {
return fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json<{ data: T }>()
})
.then(data => {
return data.data
})
.catch((error: Error) => {
externalErrorLogging.error(error) /* <-- made up logging service */
throw error /* <-- rethrow the error so consumer can still catch it */
})
}
// Consumer - consumer remains the same
api<{ title: string; message: string }>('v1/posts/1')
.then(({ title, message }) => {
console.log(title, message)
})
.catch(error => {
/* show error message */
})
Edit
There has been some changes since writing this answer a while ago. As mentioned in the comments, response.json<T>
is no longer valid. Not sure, couldn't find where it was removed.
For later releases, you can do:
// Standard variation
function api<T>(url: string): Promise<T> {
return fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json() as Promise<T>
})
}
// For the "unwrapping" variation
function api<T>(url: string): Promise<T> {
return fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json() as Promise<{ data: T }>
})
.then(data => {
return data.data
})
}
How do I read / convert an InputStream into a String in Java?
Here's a way using only the standard Java library (note that the stream is not closed, your mileage may vary).
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
I learned this trick from "Stupid Scanner tricks" article. The reason it works is because Scanner iterates over tokens in the stream, and in this case we separate tokens using "beginning of the input boundary" (\A), thus giving us only one token for the entire contents of the stream.
Note, if you need to be specific about the input stream's encoding, you can provide the second argument to Scanner
constructor that indicates what character set to use (e.g. "UTF-8").
Hat tip goes also to Jacob, who once pointed me to the said article.
How to delete Tkinter widgets from a window?
I found that when the widget is part of a function and the grid_remove
is part of another function it does not remove the label. In this example...
def somefunction(self):
Label(self, text=" ").grid(row = 0, column = 0)
self.text_ent = Entry(self)
self.text_ent.grid(row = 1, column = 0)
def someotherfunction(self):
somefunction.text_ent.grid_remove()
...there is no valid way of removing the Label.
The only solution I could find is to give the label a name and make it global:
def somefunction(self):
global label
label = Label(self, text=" ")
label.grid(row = 0, column = 0)
self.text_ent = Entry(self)
self.text_ent.grid(row = 1, column = 0)
def someotherfunction(self):
global label
somefunction.text_ent.grid_remove()
label.grid_remove()
When I ran into this problem there was a class involved, one function being in the class and one not, so I'm not sure the global label
lines are really needed in the above.
PHP - SSL certificate error: unable to get local issuer certificate
Finally got this to work!
Download the certificate bundle.
Put it somewhere. In my case, that was c:\wamp\
directory (if you are using Wamp 64 bit then it's c:\wamp64\
).
Enable mod_ssl
in Apache and php_openssl.dll
in php.ini
(uncomment them by removing ;
at the beginning). But be careful, my problem was that I had two php.ini
files and I need to do this in both of them. One is the one you get from your WAMP taskbar icon, and another one is, in my case, in C:\wamp\bin\php\php5.5.12\
Add these lines to your cert in both php.ini
files:
curl.cainfo="C:/wamp/cacert.pem"
openssl.cafile="C:/wamp/cacert.pem"
Restart Wamp services.
Linq select objects in list where exists IN (A,B,C)
Your status-codes are also a collection, so use Contains
:
var allowedStatus = new[]{ "A", "B", "C" };
var filteredOrders = orders.Order.Where(o => allowedStatus.Contains(o.StatusCode));
or in query syntax:
var filteredOrders = from order in orders.Order
where allowedStatus.Contains(order.StatusCode)
select order;
Adding a parameter to the URL with JavaScript
Here's a vastly simplified version, making tradeoffs for legibility and fewer lines of code instead of micro-optimized performance (and we're talking about a few miliseconds difference, realistically... due to the nature of this (operating on the current document's location), this will most likely be ran once on a page).
/**
* Add a URL parameter (or changing it if it already exists)
* @param {search} string this is typically document.location.search
* @param {key} string the key to set
* @param {val} string value
*/
var addUrlParam = function(search, key, val){
var newParam = key + '=' + val,
params = '?' + newParam;
// If the "search" string exists, then build params from it
if (search) {
// Try to replace an existance instance
params = search.replace(new RegExp('([?&])' + key + '[^&]*'), '$1' + newParam);
// If nothing was replaced, then add the new param to the end
if (params === search) {
params += '&' + newParam;
}
}
return params;
};
You would then use this like so:
document.location.pathname + addUrlParam(document.location.search, 'foo', 'bar');
Initialize a string variable in Python: "" or None?
If not having a value has a meaning in your program (e.g. an optional value), you should use None. That's its purpose anyway.
If the value must be provided by the caller of __init__, I would recommend not to initialize it.
If "" makes sense as a default value, use it.
In Python the type is deduced from the usage. Hence, you can change the type by just assigning a value of another type.
>>> x = None
>>> print type(x)
<type 'NoneType'>
>>> x = "text"
>>> print type(x)
<type 'str'>
>>> x = 42
>>> print type(x)
<type 'int'>
Setting the height of a DIV dynamically
With minor corrections:
function rearrange()
{
var windowHeight;
if (typeof window.innerWidth != 'undefined')
{
windowHeight = window.innerHeight;
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first
// line in the document)
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth != 'undefined'
&& document.documentElement.clientWidth != 0)
{
windowHeight = document.documentElement.clientHeight;
}
// older versions of IE
else
{
windowHeight = document.getElementsByTagName('body')[0].clientHeight;
}
document.getElementById("foobar").style.height = (windowHeight - document.getElementById("foobar").offsetTop - 6)+ "px";
}
jQuery How do you get an image to fade in on load?
Using the examples from Sohnee and karim79. I tested this and it worked in both FF3.6 and IE6.
<script type="text/javascript">
$(document).ready(function(){
$("#logo").bind("load", function () { $(this).fadeIn('slow'); });
});
</script>
<img src="http://www.gimp.org/tutorials/Lite_Quickies/quintet_hst_big.jpg" id="logo" style="display:none"/>
Export and Import all MySQL databases at one time
Other solution:
It backs up each database into a different file
#!/bin/bash
USER="zend"
PASSWORD=""
#OUTPUT="/Users/rabino/DBs"
#rm "$OUTPUTDIR/*gz" > /dev/null 2>&1
databases=`mysql -u $USER -p$PASSWORD -e "SHOW DATABASES;" | tr -d "| " | grep -v Database`
for db in $databases; do
if [[ "$db" != "information_schema" ]] && [[ "$db" != "performance_schema" ]] && [[ "$db" != "mysql" ]] && [[ "$db" != _* ]] ; then
echo "Dumping database: $db"
mysqldump -u $USER -p$PASSWORD --databases $db > `date +%Y%m%d`.$db.sql
# gzip $OUTPUT/`date +%Y%m%d`.$db.sql
fi
done
How to store a datetime in MySQL with timezone info
You said:
I want them to always come out as Tanzanian time and not in the local times that various collaborator are in.
If this is the case, then you should not use UTC. All you need to do is to use a DATETIME
type in MySQL instead of a TIMESTAMP
type.
From the MySQL documentation:
MySQL converts TIMESTAMP
values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATETIME
.)
If you are already using a DATETIME
type, then you must be not setting it by the local time to begin with. You'll need to focus less on the database, and more on your application code - which you didn't show here. The problem, and the solution, will vary drastically depending on language, so be sure to tag the question with the appropriate language of your application code.
Tooltip with HTML content without JavaScript
Similar to koningdavid's, but works on display:none and block, and adds additional styling.
_x000D_
_x000D_
div.tooltip {_x000D_
position: relative;_x000D_
/* DO NOT include below two lines, as they were added so that the text that_x000D_
is hovered over is offset from top of page*/_x000D_
top: 10em;_x000D_
left: 10em;_x000D_
/* if want hover over icon instead of text based, uncomment below */_x000D_
/* background-image: url("../images/info_tooltip.svg");_x000D_
/!* width and height of svg *!/_x000D_
width: 16px;_x000D_
height: 16px;*/_x000D_
}_x000D_
_x000D_
_x000D_
/* hide tooltip */_x000D_
_x000D_
div.tooltip span {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
_x000D_
/* show and style tooltip */_x000D_
_x000D_
div.tooltip:hover span {_x000D_
/* show tooltip */_x000D_
display: block;_x000D_
/* position relative to container div.tooltip */_x000D_
position: absolute;_x000D_
bottom: 1em;_x000D_
/* prettify */_x000D_
padding: 0.5em;_x000D_
color: #000000;_x000D_
background: #ebf4fb;_x000D_
border: 0.1em solid #b7ddf2;_x000D_
/* round the corners */_x000D_
border-radius: 0.5em;_x000D_
/* prevent too wide tooltip */_x000D_
max-width: 10em;_x000D_
}
_x000D_
<div class="tooltip">_x000D_
hover_over_me_x000D_
<span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis purus dui. Sed at orci. </span>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Java 11 package javax.xml.bind does not exist
According to the release-notes, Java 11 removed the Java EE modules:
java.xml.bind (JAXB) - REMOVED
- Java 8 - OK
- Java 9 - DEPRECATED
- Java 10 - DEPRECATED
- Java 11 -
REMOVED
See JEP 320 for more info.
You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
Jakarta EE 8 update (Mar 2020)
Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.3</version>
<scope>runtime</scope>
</dependency>
Jakarta EE 9 update (Nov 2020)
Use latest release of Eclipse Implementation of JAXB 3.0.0:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>3.0.0</version>
<scope>runtime</scope>
</dependency>
Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*
, so update import statements:
javax.xml.bind -> jakarta.xml.bind
Importing from a relative path in Python
EDIT Nov 2014 (3 years later):
Python 2.6 and 3.x supports proper relative imports, where you can avoid doing anything hacky. With this method, you know you are getting a relative import rather than an absolute import. The '..' means, go to the directory above me:
from ..Common import Common
As a caveat, this will only work if you run your python as a module, from outside of the package. For example:
python -m Proj
Original hacky way
This method is still commonly used in some situations, where you aren't actually ever 'installing' your package. For example, it's popular with Django users.
You can add Common/ to your sys.path (the list of paths python looks at to import things):
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'Common'))
import Common
os.path.dirname(__file__)
just gives you the directory that your current python file is in, and then we navigate to 'Common/' the directory and import 'Common' the module.
Get Last Part of URL PHP
The absolute simplest way to accomplish this, is with basename()
echo basename('http://domain.com/artist/song/music-videos/song-title/9393903');
Which will print
9393903
Of course, if there is a query string at the end it will be included in the returned value, in which case the accepted answer is a better solution.
Purpose of returning by const value?
It's pretty pointless to return a const
value from a function.
It's difficult to get it to have any effect on your code:
const int foo() {
return 3;
}
int main() {
int x = foo(); // copies happily
x = 4;
}
and:
const int foo() {
return 3;
}
int main() {
foo() = 4; // not valid anyway for built-in types
}
// error: lvalue required as left operand of assignment
Though you can notice if the return type is a user-defined type:
struct T {};
const T foo() {
return T();
}
int main() {
foo() = T();
}
// error: passing ‘const T’ as ‘this’ argument of ‘T& T::operator=(const T&)’ discards qualifiers
it's questionable whether this is of any benefit to anyone.
Returning a reference is different, but unless Object
is some template parameter, you're not doing that.
Can we use JSch for SSH key-based communication?
It is possible. Have a look at JSch.addIdentity(...)
This allows you to use key either as byte array or to read it from file.
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class UserAuthPubKey {
public static void main(String[] arg) {
try {
JSch jsch = new JSch();
String user = "tjill";
String host = "192.18.0.246";
int port = 10022;
String privateKey = ".ssh/id_rsa";
jsch.addIdentity(privateKey);
System.out.println("identity added ");
Session session = jsch.getSession(user, host, port);
System.out.println("session created.");
// disabling StrictHostKeyChecking may help to make connection but makes it insecure
// see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
//
// java.util.Properties config = new java.util.Properties();
// config.put("StrictHostKeyChecking", "no");
// session.setConfig(config);
session.connect();
System.out.println("session connected.....");
Channel channel = session.openChannel("sftp");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
System.out.println("shell channel connected....");
ChannelSftp c = (ChannelSftp) channel;
String fileName = "test.txt";
c.put(fileName, "./in/");
c.exit();
System.out.println("done");
} catch (Exception e) {
System.err.println(e);
}
}
}
Adjust UILabel height depending on the text
Since sizeWithFont is deprecated I use this one instead.
this one get label specific attributes.
-(CGFloat)heightForLabel:(UILabel *)label withText:(NSString *)text{
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName:label.font}];
CGRect rect = [attributedText boundingRectWithSize:(CGSize){label.frame.size.width, CGFLOAT_MAX}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
return ceil(rect.size.height);
}
npm ERR cb() never called
sudo npm cache clean
didn't work out for me. Update to the latest version of node helps.
I had node v.5.91 and updated to v6.9.1
How do I make an HTML text box show a hint when empty?
You want to assign something like this to onfocus:
if (this.value == this.defaultValue)
this.value = ''
this.className = ''
and this to onblur:
if (this.value == '')
this.value = this.defaultValue
this.className = 'placeholder'
(You can use something a bit cleverer, like a framework function, to do the classname switching if you want.)
With some CSS like this:
input.placeholder{
color: gray;
font-style: italic;
}
Jenkins CI: How to trigger builds on SVN commit
You need to require only one plugin which is the Subversion plugin.
Then simply, go into Jenkins ? job_name ? Build Trigger section ?
(i) Trigger build remotely (i.e., from scripts)
Authentication token: Token_name
Go to the SVN server's hooks directory, and then after fire the below commands:
cp post-commit.tmpl post-commit
chmod 777 post-commit
chown -R www-data:www-data post-commit
vi post-commit
Note: All lines should be commented
Add the below line at last
Syntax (for Linux users):
/usr/bin/curl http://username:API_token@localhost:8081/job/job_name/build?token=Token_name
Syntax (for Windows user):
C:/curl_for_win/curl http://username:API_token@localhost:8081/job/job_name/build?token=Token_name
Multiple files upload in Codeigniter
I change upload method with images[]
according to @Denmark.
private function upload_files($path, $title, $files)
{
$config = array(
'upload_path' => $path,
'allowed_types' => 'jpg|gif|png',
'overwrite' => 1,
);
$this->load->library('upload', $config);
$images = array();
foreach ($files['name'] as $key => $image) {
$_FILES['images[]']['name']= $files['name'][$key];
$_FILES['images[]']['type']= $files['type'][$key];
$_FILES['images[]']['tmp_name']= $files['tmp_name'][$key];
$_FILES['images[]']['error']= $files['error'][$key];
$_FILES['images[]']['size']= $files['size'][$key];
$fileName = $title .'_'. $image;
$images[] = $fileName;
$config['file_name'] = $fileName;
$this->upload->initialize($config);
if ($this->upload->do_upload('images[]')) {
$this->upload->data();
} else {
return false;
}
}
return $images;
}
How can I get a specific field of a csv file?
Finaly I got it!!!
import csv
def select_index(index):
csv_file = open('oscar_age_female.csv', 'r')
csv_reader = csv.DictReader(csv_file)
for line in csv_reader:
l = line['Index']
if l == index:
print(line[' "Name"'])
select_index('11')
"Bette Davis"
Android Overriding onBackPressed()
Just use the following code with initializing a field
private int count = 0;
@Override
public void onBackPressed() {
count++;
if (count >=1) {
/* If count is greater than 1 ,you can either move to the next
activity or just quit. */
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
finish();
overridePendingTransition
(R.anim.push_left_in, R.anim.push_left_out);
/* Quitting */
finishAffinity();
} else {
Toast.makeText(this, "Press back again to Leave!", Toast.LENGTH_SHORT).show();
// resetting the counter in 2s
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
count = 0;
}
}, 2000);
}
super.onBackPressed();
}
How to find my php-fpm.sock?
I faced this same issue on CentOS 7 years later
Posting hoping that it may help others...
Steps:
FIRST, configure the php-fpm settings:
-> systemctl stop php-fpm.service
-> cd /etc/php-fpm.d
-> ls -hal
(should see a www.conf file)
-> cp www.conf www.conf.backup
(back file up just in case)
-> vi www.conf
-> :/listen =
(to get to the line we need to change)
-> i
(to enter VI's text insertion mode)
-> change from listen = 127.0.0.1:9000
TO listen = /var/run/php-fpm/php-fpm.sock
-> Esc
then :/listen.owner
(to find it) then i
(to change)
-> UNCOMMENT the listen.owner = nobody
AND listen.group = nobody
lines
-> Hit Esc
then type :/user =
then i
-> change user = apache
TO user = nginx
-> AND change group = apache
TO group = nginx
-> Hit Esc
then :wq
(to save and quit)
-> systemctl start php-fpm.service
(now you will have a php-fpm.sock file)
SECOND, you configure your server {}
block in your /etc/nginx/nginx.conf
file. Then run:systemctl restart nginx.service
FINALLY, create a new .php file in your /usr/share/nginx/html directory for your Nginx server to serve up via the internet browser as a test.
-> vi /usr/share/nginx/html/mytest.php
-> type o
-> <?php echo date("Y/m/d-l"); ?>
(PHP page will print date and day in browser)
-> Hit Esc
-> type :wq
(to save and quite VI editor)
-> open up a browser and go to: http://yourDomainOrIPAddress/mytest.php
(you should see the date and day printed)
How to set up fixed width for <td>?
For Bootstrap 4, you can simply use the class helper:
<table class="table">
<thead>
<tr>
<td class="w-25">Col 1</td>
<td class="w-25">Col 2</td>
<td class="w-25">Col 3</td>
<td class="w-25">Col 4</td>
</tr>
</thead>
<tbody>
<tr>
...
SQL Server: Extract Table Meta-Data (description, fields and their data types)
I liked @Andomar's answer best, but I needed the column descriptions also. Here is his query modified to include those also. (Uncomment the last part of the WHERE clause to return only rows where either description is non-null).
SELECT
TableName = tbl.table_schema + '.' + tbl.table_name,
TableDescription = tableProp.value,
ColumnName = col.column_name,
ColumnDataType = col.data_type,
ColumnDescription = colDesc.ColumnDescription
FROM information_schema.tables tbl
INNER JOIN information_schema.columns col
ON col.table_name = tbl.table_name
LEFT JOIN sys.extended_properties tableProp
ON tableProp.major_id = object_id(tbl.table_schema + '.' + tbl.table_name)
AND tableProp.minor_id = 0
AND tableProp.name = 'MS_Description'
LEFT JOIN (
SELECT sc.object_id, sc.column_id, sc.name, colProp.[value] AS ColumnDescription
FROM sys.columns sc
INNER JOIN sys.extended_properties colProp
ON colProp.major_id = sc.object_id
AND colProp.minor_id = sc.column_id
AND colProp.name = 'MS_Description'
) colDesc
ON colDesc.object_id = object_id(tbl.table_schema + '.' + tbl.table_name)
AND colDesc.name = col.COLUMN_NAME
WHERE tbl.table_type = 'base table'
--AND tableProp.[value] IS NOT NULL OR colDesc.ColumnDescription IS NOT null
Logging best practices
I have to join the chorus recommending log4net, in my case coming from a platform flexibility (desktop .Net/Compact Framework, 32/64-bit) point of view.
However, wrapping it in a private-label API is a major anti-pattern. log4net.ILogger
is the .Net counterpart of the Commons Logging wrapper API already, so coupling is already minimized for you, and since it is also an Apache library, that's usually not even a concern because you're not giving up any control: fork it if you must.
Most house wrapper libraries I've seen also commit one or more of a litany of faults:
- Using a global singleton logger (or equivalently a static entry point) which loses the fine resolution of the recommended logger-per-class pattern for no other selectivity gain.
- Failing to expose the optional
Exception
argument, leading to multiple problems:
- It makes an exception logging policy even more difficult to maintain, so nothing is done consistently with exceptions.
- Even with a consistent policy, formatting the exception away into a string loses data prematurely. I've written a custom
ILayout
decorator that performs detailed drill-down on an exception to determine the chain of events.
- Failing to expose the
IsLevelEnabled
properties, which discards the ability to skip formatting code when areas or levels of logging are turned off.
Jquery asp.net Button Click Event via ajax
This is where jQuery really shines for ASP.Net developers. Lets say you have this ASP button:
When that renders, you can look at the source of the page and the id on it won't be btnAwesome, but $ctr001_btnAwesome or something like that. This makes it a pain in the butt to find in javascript. Enter jQuery.
$(document).ready(function() {
$("input[id$='btnAwesome']").click(function() {
// Do client side button click stuff here.
});
});
The id$= is doing a regex match for an id ENDING with btnAwesome.
Edit:
Did you want the ajax call being called from the button click event on the client side? What did you want to call? There are a lot of really good articles on using jQuery to make ajax calls to ASP.Net code behind methods.
The gist of it is you create a static method marked with the WebMethod attribute. You then can make a call to it using jQuery by using $.ajax.
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
I learned my WebMethod stuff from: http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/
A lot of really good ASP.Net/jQuery stuff there. Make sure you read up about why you have to use msg.d in the return on .Net 3.5 (maybe since 3.0) stuff.
Is it possible to validate the size and type of input=file in html5
I could do this (demo):
<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
</head>
<body>
<form >
<input type="file" id="f" data-max-size="32154" />
<input type="submit" />
</form>
<script>
$(function(){
$('form').submit(function(){
var isOk = true;
$('input[type=file][data-max-size]').each(function(){
if(typeof this.files[0] !== 'undefined'){
var maxSize = parseInt($(this).attr('max-size'),10),
size = this.files[0].size;
isOk = maxSize > size;
return isOk;
}
});
return isOk;
});
});
</script>
</body>
</html>
Uncaught TypeError: Cannot read property 'length' of undefined
You are not passing the variable correctly. One fast solution is to make a global variable like this:
var global_json_data;
$(document).ready(function() {
var json_source = "https://spreadsheets.google.com/feeds/list/0ApL1zT2P00q5dG1wOUMzSlNVV3VRV2pwQ2Fnbmt3M0E/od7/public/basic?alt=json";
var string_data ="";
var json_data = $.ajax({
dataType: 'json', // Return JSON
url: json_source,
success: function(data){
var data_obj = [];
for (i=0; i<data.feed.entry.length; i++){
var el = {'key': data.feed.entry[i].title['$t'], 'value': '<p><a href="'+data.feed.entry[i].content['$t']+'>'+data.feed.entry[i].title['$t']+'</a></p>'};
data_obj.push(el)};
console.log("data grabbed");
global_json_data = data_obj;
return data_obj;
},
error: function(jqXHR, textStatus, errorThrown){
$('#results_box').html('<h2>Something went wrong!</h2><p><b>' + textStatus + '</b> ' + errorThrown + '</p>');
}
});
$(':submit').click(function(event){
var json_data = global_json_data;
event.preventDefault();
console.log(json_data.length);
//function
if ($('#place').val() !=''){
var copy_string = $('#place').val();
var converted_string = copy_string;
for (i=0; i<json_data.length; i++){
//console_log(data.feed.entry[i].title['$t']);
converted_string = converted_string.replace(json_data.feed.entry[i].title['$t'],
'<a href="'+json_data.feed.entry[i].content['$t']+'>'+json_data.feed.entry[i].title['$t']+'</a>');
}
$('#results_box').text(converted_string).html();
}
});
});//document ready end
Java Constructor Inheritance
I don't know any language where subclasses inherit constructors (but then, I am not much of a programming polyglott).
Here's a discussion about the same question concerning C#. The general consensus seems to be that it would complicate the language, introduce the potential for nasty side effects to changes in a base class, and generally shouldn't be necessary in a good design.
Change Tomcat Server's timeout in Eclipse
This problem can occur if you have altogether too much stuff being started when the server is started -- or if you are in debug mode and stepping through the initialization sequence. In eclipse, changing the start-timeout by 'opening' the tomcat server entry 'Servers view' tab of the Debug Perspective is convenient. In some situations it is useful to know where this setting is 'really' stored.
Tomcat reads this setting from the element in the element in the servers.xml file. This file is stored in the .metatdata/.plugins/org.eclipse.wst.server.core
directory of your eclipse workspace, ie:
//.metadata/.plugins/org.eclipse.wst.server.core/servers.xml
There are other juicy configuration files for Eclipse plugins in other directories under .metadata/.plugins as well.
Here's an example of the servers.xml file, which is what is changed when you edit the tomcat server configuration through the Eclipse GUI:
Note the 'start-timeout' property that is set to a good long 1200 seconds above.
How to fix a locale setting warning from Perl
Setting the LC_TYPE environment variable to the default locale language "C" will help to suppress this warning.
Run export LC_CTYPE="C"
and try to run the perl
command.
P.S: You need to set this variable in one of file /etc/environment or file /etc/default/locale for a permanent solution.
How to apply a CSS filter to a background image
Now this become even simpler and more flexible by using CSS GRID.You just have to overlap the blured background(imgbg) with the text(h2)
<div class="container">
<div class="imgbg"></div>
<h2>
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Facilis enim
aut rerum mollitia quas voluptas delectus facere magni cum unde?:)
</h2>
</div>
and the css:
.container {
display: grid;
width: 30em;
}
.imgbg {
background: url(bg3.jpg) no-repeat center;
background-size: cover;
grid-column: 1/-1;
grid-row: 1/-1;
filter: blur(4px);
}
.container h2 {
text-transform: uppercase;
grid-column: 1/-1;
grid-row: 1/-1;
z-index: 2;
}
How to disable spring security for particular url
I faced the same problem here's the solution:(Explained)
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(HttpMethod.POST,"/form").hasRole("ADMIN") // Specific api method request based on role.
.antMatchers("/home","/basic").permitAll() // permited urls to guest users(without login).
.anyRequest().authenticated()
.and()
.formLogin() // not specified form page to use default login page of spring security.
.permitAll()
.and()
.logout().deleteCookies("JSESSIONID") // delete memory of browser after logout.
.and()
.rememberMe().key("uniqueAndSecret"); // remember me check box enabled.
http.csrf().disable(); **// ADD THIS CODE TO DISABLE CSRF IN PROJECT.**
}
Waiting until the task finishes
Swift 4
You can use Async Function for these situations. When you use DispatchGroup()
,Sometimes deadlock may be occures.
var a: Int?
@objc func myFunction(completion:@escaping (Bool) -> () ) {
DispatchQueue.main.async {
let b: Int = 3
a = b
completion(true)
}
}
override func viewDidLoad() {
super.viewDidLoad()
myFunction { (status) in
if status {
print(self.a!)
}
}
}
Javascript switch vs. if...else if...else
Is there a preformance difference in
Javascript between a switch statement
and an if...else if....else?
I don't think so, switch
is useful/short if you want prevent multiple if-else
conditions.
Is the behavior of switch and
if...else if...else different across
browsers? (FireFox, IE, Chrome, Opera,
Safari)
Behavior is same across all browsers :)
Prompt Dialog in Windows Forms
Unfortunately C# still doesn't offer this capability in the built in libs. The best solution at present is to create a custom class with a method that pops up a small form.
If you're working in Visual Studio you can do this by clicking on Project >Add class
Visual C# items >code >class
Name the class PopUpBox (you can rename it later if you like) and paste in the following code:
using System.Drawing;
using System.Windows.Forms;
namespace yourNameSpaceHere
{
public class PopUpBox
{
private static Form prompt { get; set; }
public static string GetUserInput(string instructions, string caption)
{
string sUserInput = "";
prompt = new Form() //create a new form at run time
{
Width = 500, Height = 150, FormBorderStyle = FormBorderStyle.FixedDialog, Text = caption,
StartPosition = FormStartPosition.CenterScreen, TopMost = true
};
//create a label for the form which will have instructions for user input
Label lblTitle = new Label() { Left = 50, Top = 20, Text = instructions, Dock = DockStyle.Top, TextAlign = ContentAlignment.TopCenter };
TextBox txtTextInput = new TextBox() { Left = 50, Top = 50, Width = 400 };
////////////////////////////OK button
Button btnOK = new Button() { Text = "OK", Left = 250, Width = 100, Top = 70, DialogResult = DialogResult.OK };
btnOK.Click += (sender, e) =>
{
sUserInput = txtTextInput.Text;
prompt.Close();
};
prompt.Controls.Add(txtTextInput);
prompt.Controls.Add(btnOK);
prompt.Controls.Add(lblTitle);
prompt.AcceptButton = btnOK;
///////////////////////////////////////
//////////////////////////Cancel button
Button btnCancel = new Button() { Text = "Cancel", Left = 350, Width = 100, Top = 70, DialogResult = DialogResult.Cancel };
btnCancel.Click += (sender, e) =>
{
sUserInput = "cancel";
prompt.Close();
};
prompt.Controls.Add(btnCancel);
prompt.CancelButton = btnCancel;
///////////////////////////////////////
prompt.ShowDialog();
return sUserInput;
}
public void Dispose()
{prompt.Dispose();}
}
}
You will need to change the namespace to whatever you're using. The method returns a string, so here's an example of how to implement it in your calling method:
bool boolTryAgain = false;
do
{
string sTextFromUser = PopUpBox.GetUserInput("Enter your text below:", "Dialog box title");
if (sTextFromUser == "")
{
DialogResult dialogResult = MessageBox.Show("You did not enter anything. Try again?", "Error", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
boolTryAgain = true; //will reopen the dialog for user to input text again
}
else if (dialogResult == DialogResult.No)
{
//exit/cancel
MessageBox.Show("operation cancelled");
boolTryAgain = false;
}//end if
}
else
{
if (sTextFromUser == "cancel")
{
MessageBox.Show("operation cancelled");
}
else
{
MessageBox.Show("Here is the text you entered: '" + sTextFromUser + "'");
//do something here with the user input
}
}
} while (boolTryAgain == true);
This method checks the returned string for a text value, empty string, or "cancel" (the getUserInput method returns "cancel" if the cancel button is clicked) and acts accordingly. If the user didn't enter anything and clicked OK it will tell the user and ask them if they want to cancel or re-enter their text.
Post notes:
In my own implementation I found that all of the other answers were missing 1 or more of the following:
- A cancel button
- The ability to contain symbols in the string sent to the method
- How to access the method and handle the returned value.
Thus, I have posted my own solution. I hope someone finds it useful. Credit to Bas and Gideon + commenters for your contributions, you helped me to come up with a workable solution!
Copy/duplicate database without using mysqldump
an SQL that shows SQL commands, need to run to duplicate a database from one database to another. for each table there is create a table statement and an insert statement. it assumes both databases are on the same server:
select @fromdb:="crm";
select @todb:="crmen";
SET group_concat_max_len=100000000;
SELECT GROUP_CONCAT( concat("CREATE TABLE `",@todb,"`.`",table_name,"` LIKE `",@fromdb,"`.`",table_name,"`;\n",
"INSERT INTO `",@todb,"`.`",table_name,"` SELECT * FROM `",@fromdb,"`.`",table_name,"`;")
SEPARATOR '\n\n')
as sqlstatement
FROM information_schema.tables where table_schema=@fromdb and TABLE_TYPE='BASE TABLE';
How to send data with angularjs $http.delete() request?
$http.delete
method doesn't accept request body.
You can try this workaround :
$http( angular.merge({}, config || {}, {
method : 'delete',
url : _url,
data : _data
}));
where in config
you can pass config data like headers etc.
How do I round to the nearest 0.5?
Sounds like you need to round to the nearest 0.5. I see no version of round
in the C# API that does this (one version takes a number of decimal digits to round to, which isn't the same thing).
Assuming you only have to deal with integer numbers of tenths, it's sufficient to calculate round (num * 2) / 2
. If you're using arbitrarily precise decimals, it gets trickier. Let's hope you don't.
Comparison of Android Web Service and Networking libraries: OKHTTP, Retrofit and Volley
Retrofit 1.9.0 vs. RoboSpice
I am using both in my app.
Robospice works faster than Retrofit whenever I parse the nested JSON class. Because Spice Manger will do everything for you. In Retrofit you need to create GsonConverter and deserialize it.
I created two fragments in the same activity and called the same time with two same kind of URLs.
09-23 20:12:32.830 16002-16002/com.urbanpro.seeker E/RETROFIT? RestAdapter Init
09-23 20:12:32.833 16002-16002/com.urbanpro.seeker E/RETROFIT? calling the method
09-23 20:12:32.837 16002-16002/com.urbanpro.seeker E/ROBOSPICE? initialzig spice manager
09-23 20:12:32.860 16002-16002/com.urbanpro.seeker E/ROBOSPICE? Executing the method
09-23 20:12:33.537 16002-16002/com.urbanpro.seeker E/ROBOSPICE? on SUcceess
09-23 20:12:33.553 16002-16002/com.urbanpro.seeker E/ROBOSPICE? gettting the all contents
09-23 20:12:33.601 16002-21819/com.urbanpro.seeker E/RETROFIT? deseriazation starts
09-23 20:12:33.603 16002-21819/com.urbanpro.seeker E/RETROFIT? deseriazation ends
Replace all whitespace characters
You could use the function trim
let str = ' Hello World ';
alert (str.trim());
All the front and back spaces around Hello World would be removed.
Asking the user for input until they give a valid response
Why would you do a while True
and then break out of this loop while you can also just put your requirements in the while statement since all you want is to stop once you have the age?
age = None
while age is None:
input_value = input("Please enter your age: ")
try:
# try and convert the string input to a number
age = int(input_value)
except ValueError:
# tell the user off
print("{input} is not a number, please enter a number only".format(input=input_value))
if age >= 18:
print("You are able to vote in the United States!")
else:
print("You are not able to vote in the United States.")
This would result in the following:
Please enter your age: *potato*
potato is not a number, please enter a number only
Please enter your age: *5*
You are not able to vote in the United States.
this will work since age will never have a value that will not make sense and the code follows the logic of your "business process"
OVER clause in Oracle
The OVER
clause specifies the partitioning, ordering and window "over which" the analytic function operates.
Example #1: calculate a moving average
AVG(amt) OVER (ORDER BY date ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)
date amt avg_amt
===== ==== =======
1-Jan 10.0 10.5
2-Jan 11.0 17.0
3-Jan 30.0 17.0
4-Jan 10.0 18.0
5-Jan 14.0 12.0
It operates over a moving window (3 rows wide) over the rows, ordered by date.
Example #2: calculate a running balance
SUM(amt) OVER (ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
date amt sum_amt
===== ==== =======
1-Jan 10.0 10.0
2-Jan 11.0 21.0
3-Jan 30.0 51.0
4-Jan 10.0 61.0
5-Jan 14.0 75.0
It operates over a window that includes the current row and all prior rows.
Note: for an aggregate with an OVER
clause specifying a sort ORDER
, the default window is UNBOUNDED PRECEDING
to CURRENT ROW
, so the above expression may be simplified to, with the same result:
SUM(amt) OVER (ORDER BY date)
Example #3: calculate the maximum within each group
MAX(amt) OVER (PARTITION BY dept)
dept amt max_amt
==== ==== =======
ACCT 5.0 7.0
ACCT 7.0 7.0
ACCT 6.0 7.0
MRKT 10.0 11.0
MRKT 11.0 11.0
SLES 2.0 2.0
It operates over a window that includes all rows for a particular dept.
SQL Fiddle: http://sqlfiddle.com/#!4/9eecb7d/122
Cannot use Server.MapPath
I know this post is a few years old, but what I do is add this line to the top of your class and you will still be able to user Server.MapPath
Dim Server = HttpContext.Current.Server
or u can make a function
Public Function MapPath(sPath as String)
return HttpContext.Current.Server.MapPath(sPath)
End Function
I am all about making things easier. I have also added it to my Utilities class just in case i run into this again.
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
I installed MySQL as root user($SUDO
) and got this same issue
Here is how I fixed it-
$ sudo cat /etc/mysql/debian.cnf
This will show details as-
# Automatically generated for Debian scripts. DO NOT TOUCH!
[client]
host = localhost
user = debian-sys-maint
password = GUx0RblkD3sPhHL5
socket = /var/run/mysqld/mysqld.sock
[mysql_upgrade]
host = localhost
user = debian-sys-maint
password = GUx0RblkD3sPhHL5
socket = /var/run/mysqld/mysqld.sock
Above we can see password just we are going to use(GUx0RblkD3sPhHL5)
that in the prompt-
mysql -u debian-sys-maint -p
Enter password:
now provide password(GUx0RblkD3sPhHL5).
Now exit
from MySQL and login again as-
mysql -u root -p
Enter password:
Now provide new password. That's all, we have new password for further uses.
It worked for me, hope help you too!
Jenkins Host key verification failed
As for the workaround (e.g. Windows slave), define the following environment variable in global properties:
GIT_SSH_COMMAND="ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no"
Note: If you don't see the option, you probably need EnvInject plugin for it.
In a javascript array, how do I get the last 5 elements, excluding the first element?
ES6 way:
I use destructuring assignment for array to get first
and remaining rest
elements and then I'll take last five of the rest
with slice method:
_x000D_
_x000D_
const cutOffFirstAndLastFive = (array) => {_x000D_
const [first, ...rest] = array;_x000D_
return rest.slice(-5);_x000D_
}_x000D_
_x000D_
cutOffFirstAndLastFive([1, 55, 77, 88]);_x000D_
_x000D_
console.log(_x000D_
'Tests:',_x000D_
JSON.stringify(cutOffFirstAndLastFive([1, 55, 77, 88])),_x000D_
JSON.stringify(cutOffFirstAndLastFive([1, 55, 77, 88, 99, 22, 33, 44])),_x000D_
JSON.stringify(cutOffFirstAndLastFive([1]))_x000D_
);
_x000D_
_x000D_
_x000D_
How to use router.navigateByUrl and router.navigate in Angular
router.navigate vs router.navigateByUrl
router.navigate
is just a convenience method that wraps router.navigateByUrl
, it boils down to:
navigate(commands: any[], extras) {
return router.navigateByUrl(router.createUrlTree(commands, extras), extras);
}
As mentioned in other answers router.navigateByUrl
will only accept absolute URLs:
// This will work
router.navigateByUrl("http://localhost/team/33/user/11")
// This WON'T work even though relativeTo parameter is in the signature
router.navigateByUrl("../22", {relativeTo: route})
All the relative calculations are done by router.createUrlTree
and router.navigate
. Array syntax is used to treat every array element as a URL modifying "command". E.g. ".."
- go up, "path"
- go down, {expand: true}
- add query param, etc.. You can use it like this:
// create /team/33/user/11
router.navigate(['/team', 33, 'user', 11]);
// assuming the current url is `/team/33/user/11` and the route points to `user/11`
// navigate to /team/33/user/11/details
router.navigate(['details'], {relativeTo: route});
// navigate to /team/33/user/22
router.navigate(['../22'], {relativeTo: route});
// navigate to /team/44/user/22
router.navigate(['../../team/44/user/22'], {relativeTo: route});
That {relativeTo: route}
parameter is important as that's what router will use as the root for relative operations.
Get it through your component's constructor:
// In my-awesome.component.ts:
constructor(private route: ActivatedRoute, private router: Router) {}
// Example call
onNavigateClick() {
// Navigates to a parent component
this.router.navigate([..], { relativeTo: this.route })
}
routerLink directive
Nicest thing about this directive is that it will retrieve the ActivatedRoute
for you. Under the hood it's using already familiar:
router.navigateByUrl(router.createUrlTree(commands, { relativeTo: route }), { relativeTo: route });
Following variants will produce identical result:
[routerLink]="['../..']"
// if the string parameter is passed it will be wrapped into an array
routerLink="../.."
How can I list ALL DNS records?
In the absence of the ability to do zone transfers, I wrote this small bash script, dg
:
#!/bin/bash
COMMON_SUBDOMAINS=(www mail smtp pop imap blog en ftp ssh login)
if [[ "$2" == "x" ]]; then
dig +nocmd "$1" +noall +answer "${3:-any}"
wild_ips="$(dig +short "*.$1" "${3:-any}" | tr '\n' '|')"
wild_ips="${wild_ips%|}"
for sub in "${COMMON_SUBDOMAINS[@]}"; do
dig +nocmd "$sub.$1" +noall +answer "${3:-any}"
done | grep -vE "${wild_ips}"
dig +nocmd "*.$1" +noall +answer "${3:-any}"
else
dig +nocmd "$1" +noall +answer "${2:-any}"
fi
Now I use dg example.com
to get a nice, clean list of DNS records, or dg example.com x
to include a bunch of other popular subdomains.
grep -vE "${wild_ips}"
filters out records that could be the result of a wildcard DNS entry such as * 10800 IN A 1.38.216.82
. Otherwise, a wildcard entry would make it appear as if there were records for each $COMMON_SUBDOMAN
.
Note: This relies on ANY
queries, which are blocked by some DNS providers such as CloudFlare.
paint() and repaint() in Java
Difference between Paint() and Repaint() method
Paint():
This method holds instructions to paint this component. Actually, in Swing, you should change paintComponent() instead of paint(), as paint calls paintBorder(), paintComponent() and paintChildren(). You shouldn't call this method directly, you should call repaint() instead.
Repaint():
This method can't be overridden. It controls the update() -> paint() cycle. You should call this method to get a component to repaint itself. If you have done anything to change the look of the component, but not its size ( like changing color, animating, etc. ) then call this method.
How can I create a table with borders in Android?
After long search and hours of trying this is the simplest code i could make:
ShapeDrawable border = new ShapeDrawable(new RectShape());
border.getPaint().setStyle(Style.STROKE);
border.getPaint().setColor(Color.BLACK);
tv.setBackground(border);
content.addView(tv);
tv is a TextView with a simple text and content is my container (LinearLayout in this Case).
That's a little easier.
How do I find Waldo with Mathematica?
I don't know Mathematica . . . too bad. But I like the answer above, for the most part.
Still there is a major flaw in relying on the stripes alone to glean the answer (I personally don't have a problem with one manual adjustment). There is an example (listed by Brett Champion, here) presented which shows that they, at times, break up the shirt pattern. So then it becomes a more complex pattern.
I would try an approach of shape id and colors, along with spacial relations. Much like face recognition, you could look for geometric patterns at certain ratios from each other. The caveat is that usually one or more of those shapes is occluded.
Get a white balance on the image, and red a red balance from the image. I believe Waldo is always the same value/hue, but the image may be from a scan, or a bad copy. Then always refer to an array of the colors that Waldo actually is: red, white, dark brown, blue, peach, {shoe color}.
There is a shirt pattern, and also the pants, glasses, hair, face, shoes and hat that define Waldo. Also, relative to other people in the image, Waldo is on the skinny side.
So, find random people to obtain an the height of people in this pic. Measure the average height of a bunch of things at random points in the image (a simple outline will produce quite a few individual people). If each thing is not within some standard deviation from each other, they are ignored for now. Compare the average of heights to the image's height. If the ratio is too great (e.g., 1:2, 1:4, or similarly close), then try again. Run it 10(?) of times to make sure that the samples are all pretty close together, excluding any average that is outside some standard deviation. Possible in Mathematica?
This is your Waldo size. Walso is skinny, so you are looking for something 5:1 or 6:1 (or whatever) ht:wd. However, this is not sufficient. If Waldo is partially hidden, the height could change. So, you are looking for a block of red-white that ~2:1. But there has to be more indicators.
- Waldo has glasses. Search for two circles 0.5:1 above the red-white.
- Blue pants. Any amount of blue at the same width within any distance between the end of the red-white and the distance to his feet. Note that he wears his shirt short, so the feet are not too close.
- The hat. Red-white any distance up to twice the top of his head. Note that it must have dark hair below, and probably glasses.
- Long sleeves. red-white at some angle from the main red-white.
- Dark hair.
- Shoe color. I don't know the color.
Any of those could apply. These are also negative checks against similar people in the pic -- e.g., #2 negates wearing a red-white apron (too close to shoes), #5 eliminates light colored hair. Also, shape is only one indicator for each of these tests . . . color alone within the specified distance can give good results.
This will narrow down the areas to process.
Storing these results will produce a set of areas that should have Waldo in it. Exclude all other areas (e.g., for each area, select a circle twice as big as the average person size), and then run the process that @Heike laid out with removing all but red, and so on.
Any thoughts on how to code this?
Edit:
Thoughts on how to code this . . . exclude all areas but Waldo red, skeletonize the red areas, and prune them down to a single point. Do the same for Waldo hair brown, Waldo pants blue, Waldo shoe color. For Waldo skin color, exclude, then find the outline.
Next, exclude non-red, dilate (a lot) all the red areas, then skeletonize and prune. This part will give a list of possible Waldo center points. This will be the marker to compare all other Waldo color sections to.
From here, using the skeletonized red areas (not the dilated ones), count the lines in each area. If there is the correct number (four, right?), this is certainly a possible area. If not, I guess just exclude it (as being a Waldo center . . . it may still be his hat).
Then check if there is a face shape above, a hair point above, pants point below, shoe points below, and so on.
No code yet -- still reading the docs.
How do I lowercase a string in C?
It's in the standard library, and that's the most straight forward way I can see to implement such a function. So yes, just loop through the string and convert each character to lowercase.
Something trivial like this:
#include <ctype.h>
for(int i = 0; str[i]; i++){
str[i] = tolower(str[i]);
}
or if you prefer one liners, then you can use this one by J.F. Sebastian:
for ( ; *p; ++p) *p = tolower(*p);
iPhone SDK on Windows (alternative solutions)
You could easily build an app using PhoneGap or Appcelerators Titanium Mobile.
Both of these essentially act as a WebKit wrapper, so you can build your application with HTML/CSS/JavaScript. It's a pretty portable solution, too, but you are somewhat limited in what you can make - i.e, no intensive rendering or anything. It really all depends on what you're looking to do.
Get image dimensions
Using getimagesize function, we can also get these properties of that specific image-
<?php
list($width, $height, $type, $attr) = getimagesize("image_name.jpg");
echo "Width: " .$width. "<br />";
echo "Height: " .$height. "<br />";
echo "Type: " .$type. "<br />";
echo "Attribute: " .$attr. "<br />";
//Using array
$arr = array('h' => $height, 'w' => $width, 't' => $type, 'a' => $attr);
?>
Result like this -
Width: 200
Height: 100
Type: 2
Attribute: width='200' height='100'
Type of image consider like -
1 = GIF
2 = JPG
3 = PNG
4 = SWF
5 = PSD
6 = BMP
7 = TIFF(intel byte order)
8 = TIFF(motorola byte order)
9 = JPC
10 = JP2
11 = JPX
12 = JB2
13 = SWC
14 = IFF
15 = WBMP
16 = XBM
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
"unmappable character for encoding" warning in Java
I had the same problem, where the character index reported in the java error message was incorrect. I narrowed it down to the double quote characters just prior to the reported position being hex 094 (cancel instead of quote, but represented as a quote) instead of hex 022. As soon as I swapped for the hex 022 variant all was fine.
Casting a variable using a Type variable
If you need to cast objects at runtime without knowing destination type, you can use reflection to make a dynamic converter.
This is a simplified version (without caching generated method):
public static class Tool
{
public static object CastTo<T>(object value) where T : class
{
return value as T;
}
private static readonly MethodInfo CastToInfo = typeof (Tool).GetMethod("CastTo");
public static object DynamicCast(object source, Type targetType)
{
return CastToInfo.MakeGenericMethod(new[] { targetType }).Invoke(null, new[] { source });
}
}
then you can call it:
var r = Tool.DynamicCast(myinstance, typeof (MyClass));