If you are using a MongoDB server then after using connect in the cluster clock on connect and finding the URL, the URL will be somehing like this
<mongodb+srv://Rohan:<password>@cluster0-3kcv6.mongodb.net/<dbname>?retryWrites=true&w=majority>
In this case, don't forget to replace the password with your database password and db name and then use
const client = new MongoClient(url,{useUnifiedTopology:true});
Tried this on Android Studio and it worked for me:
Tools > SDK Manager (Make sure to check Show Packages below)
The easiest way I've found is delete Android Studio from the applications folder, then download & install it again.
This link android-9.0-changes-28-->Apache HTTP client deprecation explains reason for adding the following to your AndroidManifest.xml:
<uses-library android:name="org.apache.http.legacy" android:required="false"/>
With Android 6.0, we removed support for the Apache HTTP client. Beginning with Android 9, that library is removed from the bootclasspath and is not available to apps by default.
If username
or password
has the @
character, then use it like this:
mongoose
.connect(
'DB_url',
{ user: '@dmin', pass: 'p@ssword', useNewUrlParser: true }
)
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.log('Could not connect to MongoDB', err));
You can check detail of error by running this command
sudo service mongod status
if error is something like this
simply running this will resolve your issue
rm /tmp/mongodb-27017.sock
The error:
Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema
at com.android.repository.api.SchemaModule$SchemaModuleVersion.<init>(SchemaModule.java:156)
at com.android.repository.api.SchemaModule.<init>(SchemaModule.java:75)
at com.android.sdklib.repository.AndroidSdkHandler.<clinit>(AndroidSdkHandler.java:81)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:73)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.annotation.XmlSchema
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499)
... 5 more
is occurring because the current SDK version is incompatible with Java 9.
So, to solve it, you can downgrade your java version to Java 8, or with a workaround, you can export the following option on your terminal:
Linux:
export JAVA_OPTS='-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee'
Windows:
set JAVA_OPTS='-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee'
And to make it stick, you can export the JAVA_OPTS in your profile file on Linux (.zshrc
, .bashrc
and etc.) or add as an environment permanently on Windows.
Then, you can type the flutter or sdkmanager command:
Flutter:
flutter doctor --android-licenses
sdkmanager:
sdkmanager --licenses
and type Y when needed to accept the licenses.
ps. This doesn't work for Java 11/11+, which doesn't have Java EE modules. For this option is a good idea, downgrade your Java version or wait for a Flutter update.
I had the same issue, I could solve it by switching fom JDK 11 to JDK 8.
I did a little experimenting to see if I could keep the database name as part of the url. I prefer the promise syntax but it should still work for the callback syntax. Notice below that client.db() is called without passing any parameters.
MongoClient.connect(
'mongodb://localhost:27017/mytestingdb',
{ useNewUrlParser: true}
)
.then(client => {
// The database name is part of the url. client.db() seems
// to know that and works even without a parameter that
// relays the db name.
let db = client.db();
console.log('the current database is: ' + db.s.databaseName);
// client.close() if you want to
})
.catch(err => console.log(err));
My package.json lists monbodb ^3.2.5.
The 'useNewUrlParser' option is not required if you're willing to deal with a deprecation warning. But it is wise to use at this point until version 4 comes out where presumably the new driver will be the default and you won't need the option anymore.
The accepted answer is outdated as of February 2019. Here's an answer that will work until sdkmanager
migrates to a newer version of Java. But by then, you won't have this problem anymore.
OpenJDK 10 was superseeded by OpenJDK 11, which doesn't implement
java.se.ee
at all. This means that the hack of adding--add-modules java.se.ee
doesn't do anything anymore. It also means that OpenJDK 10 will be automatically removed from your system and replaced with OpenJDK 11 the next time you update, if your updates are configured properly.Modify
sdkmanager
to use Java 8 by settingJAVA_HOME
insidesdkmanager
to a Java 8 installation. It's, by default, at~/Android/Sdk/tools/bin/sdkmanager
.# Add default JVM options here. You can also use JAVA_OPTS and SDKMANAGER_OPTS to pass JVM options $ JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-amd64 DEFAULT_JVM_OPTS='"-Dcom.android.sdklib.toolsdir=$APP_HOME" -XX:+IgnoreUnrecognizedVMOptions'
@rem Add default JVM options here. You can also use JAVA_OPTS and SDKMANAGER_OPTS to pass JVM options to this script. set JAVA_HOME="C:\ProgramData\scoop\apps\android-studio\current\jre" set DEFAULT_JVM_OPTS="-Dcom.android.sdklib.toolsdir=%~dp0\.."
This way, you can keep using a sane and maintained version of Java on your system while simultaneously using
sdkmanager
.# Java export JAVA_HOME=/usr/lib/jvm/default-java
And now I've got some pipelines to repair.
You might be importing @Test
from org.junit.Test
, which is a JUnit 4 annotation. The Junit5 test runner will not discover it.
The Junit5 test runner will discover a test annotated with org.junit.jupiter.api.Test
Found the answer from Import org.junit.Test throws error as "No Test found with Test Runner "JUnit 5""
The solution was to install MongoDB from below location: https://www.mongodb.com/download-center/community
Update 2019-10:
As stated in the issue tracker, Google has been working on a new Android SDK Command-line Tools release that runs on current JVMs (9, 10, 11+) and does not depend on deprecated JAXB EE modules!
You can download and use the new Android SDK Command-line Tools inside Android Studio or by manually downloading them from the Google servers:
For the latest versions check the URLs inside the repository.xml.
If you manually unpack the command line tools, take care of placing them in a subfolder inside your $ANDROID_HOME
(e.g. $ANDROID_HOME/cmdline-tools/...
).
Replace the dependency in the POM.xml file
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.2.3</version>
</dependency>
By the dependency
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
I was wired, but my project was already migrated to AndroidX, but after migrating to androidX again, it refactored some part of my project and the problem solved.
I faced the similar problem in no reason, i think it was caused by IDE(android studio). I have tried all of above solutions but not worked. Finally, in my own situation, i solved this problem by the following actions:
- Close the current project and remove it from the list of projects in android studio ,and reopen it by Open an existing Android Studio project
, then it may be worked. I hope that my experience will be useful for you.
As the official documentation states:
When upgrading you may face the following:
java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
Hibernate typically requires JAXB that’s no longer provided by default. You can add the java.xml.bind module to restore this functionality with Java9 or Java10 (even if the module is deprecated).
As of Java11, the module is not available so your only option is to add the JAXB RI (you can do that as of Java9 in place of adding the java.xml.bind module:
Maven
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
</dependency>
Gradle (build.gradle.kts):
implementation("org.glassfish.jaxb:jaxb-runtime")
Gradle (build.gradle)
implementation 'org.glassfish.jaxb:jaxb-runtime'
If you rather specify a specific version, take a look here: https://mvnrepository.com/artifact/org.glassfish.jaxb/jaxb-runtime
I solved it by myself.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.7.Final</version>
</dependency>
The simple answer:
doing a MOV RBX, 3 and MUL RBX is expensive; just ADD RBX, RBX twice
ADD 1 is probably faster than INC here
MOV 2 and DIV is very expensive; just shift right
64-bit code is usually noticeably slower than 32-bit code and the alignment issues are more complicated; with small programs like this you have to pack them so you are doing parallel computation to have any chance of being faster than 32-bit code
If you generate the assembly listing for your C++ program, you can see how it differs from your assembly.
Yeah, resolved the exception by adding commons-collections4-4.1 jar file to the CLASSPATH user varible of system. Downloaded from https://mvnrepository.com/artifact/org.apache.commons/commons-collections4/4.1
navigator.clipboard doesn't work over http connection according to their document. So you can check if it's coming undefined and use document.execCommand('copy') instead, this solution should cover almost all the browsers
const defaultCopySuccessMessage = 'ID copied!'
const CopyItem = (props) => {
const { copySuccessMessage = defaultCopySuccessMessage, value } = props
const [showCopySuccess, setCopySuccess] = useState(false)
function fallbackToCopy(text) {
if (window.clipboardData && window.clipboardData.setData) {
// IE specific code path to prevent textarea being shown while dialog is visible.
return window.clipboardData.setData('Text', text)
} else if (document.queryCommandSupported && document.queryCommandSupported('copy')) {
const textarea = document.createElement('textarea')
textarea.innerText = text
// const parentElement=document.querySelector(".up-CopyItem-copy-button")
const parentElement = document.getElementById('copy')
if (!parentElement) {
return
}
parentElement.appendChild(textarea)
textarea.style.position = 'fixed' // Prevent scrolling to bottom of page in MS Edge.
textarea.select()
try {
setCopySuccess(true)
document.execCommand('copy') // Security exception may be thrown by some browsers.
} catch (ex) {
console.log('Copy to clipboard failed.', ex)
return false
} finally {
parentElement.removeChild(textarea)
}
}
}
const copyID = () => {
if (!navigator.clipboard) {
fallbackToCopy(value)
return
}
navigator.clipboard.writeText(value)
setCopySuccess(true)
}
return showCopySuccess ? (
<p>{copySuccessMessage}</p>
) : (
<span id="copy">
<button onClick={copyID}>Copy Item </button>
</span>
)
}
And you can just call and reuse the component anywhere you'd like to
const Sample=()=>(
<CopyItem value="item-to-copy"/>
)
mapStateToProps()
is a utility which helps your component get updated state(which is updated by some other components),
mapDispatchToProps()
is a utility which will help your component to fire an action event (dispatching action which may cause change of application state)
I had the same problem, Here is my code before modification :
package com.asagaama
import org.apache.spark.SparkContext
import org.apache.spark.SparkConf
import org.apache.spark.rdd.RDD
/**
* Created by asagaama on 16/02/2017.
*/
object Word {
def countWords(sc: SparkContext) = {
// Load our input data
val input = sc.textFile("/Users/Documents/spark/testscase/test/test.txt")
// Split it up into words
val words = input.flatMap(line => line.split(" "))
// Transform into pairs and count
val counts = words.map(word => (word, 1)).reduceByKey { case (x, y) => x + y }
// Save the word count back out to a text file, causing evaluation.
counts.saveAsTextFile("/Users/Documents/spark/testscase/test/result.txt")
}
def main(args: Array[String]) = {
val conf = new SparkConf().setAppName("wordCount")
val sc = new SparkContext(conf)
countWords(sc)
}
}
And after replacing :
val conf = new SparkConf().setAppName("wordCount")
With :
val conf = new SparkConf().setAppName("wordCount").setMaster("local[*]")
It worked fine !
I had the same problem. One day the program was working perfectly, and the following wasn't. I checked on Github the changes I made. For me the problem was on build.gradle (Module:app) in the dependencies:
compile 'com.android.tools.build:gradle:2.1.2'
This line was the one that was causing the problem. After changing it the app was running properly again
this is a version problem change version > 2.4 to 1.9 solve it
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-xml-provider</artifactId>
<version>2.4.1</version>
to
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.4</version>
In my case issue was with wrong path to NDK
.
If your project requires it please check it in menu File -> Project Structure -> SDK Location
:
In my case, the problem occurred when writing in Kotlin and using IDEA 2020.3. Despite proper entries in build.gradle.kts. It turned out that the problem was when generating test functions by IDEA IDE (Alt + Insert). It generates the following code:
@Test
internal fun name () {
TODO ("Not yet implemented")
}
And the problem will be fixed after removing the "internal" modifier:
@Test
fun name () {
TODO ("Not yet implemented")
}
providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")
This should be
compile("org.springframework.boot:spring-boot-starter-tomcat")
I have had the same error. I added dependency on pom.xml (I am working with Maven)
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.12.1</version>
</dependency>
I started trying with version 2.9.0, then I found a different error (com/fasterxml/jackson/core/exc/InputCoercionException) then I try different versions until all errors were solved with version 2.12.1
The MySQL dependency should be like the following syntax in the pom.xml file.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
Make sure the syntax, groupId, artifactId, Version has included in the dependancy.
The MongoDB find
method does not return a single result, but a list of results in the form of a Cursor
. This latter is an iterator, so you can go through it with a for
loop.
For your case, just use the findOne
method instead of find
. This will returns you a single document as a dictionary.
I have some additions to above mentioned answers Its infact a hack mentioned by Jesse Wilson from okhttp, square here. According to this hack, i had to rename my SSLSocketFactory variable to
private SSLSocketFactory delegate;
This is my TLSSocketFactory class
public class TLSSocketFactory extends SSLSocketFactory {
private SSLSocketFactory delegate;
public TLSSocketFactory() throws KeyManagementException, NoSuchAlgorithmException {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, null, null);
delegate = context.getSocketFactory();
}
@Override
public String[] getDefaultCipherSuites() {
return delegate.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return delegate.getSupportedCipherSuites();
}
@Override
public Socket createSocket() throws IOException {
return enableTLSOnSocket(delegate.createSocket());
}
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
return enableTLSOnSocket(delegate.createSocket(s, host, port, autoClose));
}
@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return enableTLSOnSocket(delegate.createSocket(host, port));
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
return enableTLSOnSocket(delegate.createSocket(host, port, localHost, localPort));
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return enableTLSOnSocket(delegate.createSocket(host, port));
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
return enableTLSOnSocket(delegate.createSocket(address, port, localAddress, localPort));
}
private Socket enableTLSOnSocket(Socket socket) {
if(socket != null && (socket instanceof SSLSocket)) {
((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2"});
}
return socket;
}
}
and this is how i used it with okhttp and retrofit
OkHttpClient client=new OkHttpClient();
try {
client = new OkHttpClient.Builder()
.sslSocketFactory(new TLSSocketFactory())
.build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
A CLASSPATH entry is either a directory at the head of a package hierarchy of .class files, or a .jar file. If you're expecting ./lib
to include all the .jar files in that directory, it won't. You have to name them explicitly.
#use return convertView;
Code:
public View getView(final int position, View convertView, ViewGroup parent) {
//convertView = null;
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.list_item, null);
TextView tv = (TextView) convertView.findViewById(R.id.name);
Button rm_btn = (Button) convertView.findViewById(R.id.rm_btn);
Model m = modelList.get(position);
tv.setText(m.getName());
// click listener for remove button ??????????
rm_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
modelList.remove(position);
notifyDataSetChanged();
}
});
}
///#use return convertView;
return convertView;
}
Please add the following dependency http://mvnrepository.com/artifact/org.json/json/20080701
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20080701</version>
</dependency>
Check your all these file:
var users = require('./routes/users');
var Users = require('./models/user');
var Items = require('./models/item');
Save properly, In my case, one file was missed and throwing the same error
you must use import android.support.v7.app.ActionBarDrawerToggle;
and use the constructor
public CustomActionBarDrawerToggle(Activity mActivity,DrawerLayout mDrawerLayout)
{
super(mActivity, mDrawerLayout, R.string.ns_menu_open, R.string.ns_menu_close);
}
and if the drawer toggle button becomes dark then you must use the supportActionBar provided in the support library.
You can implement supportActionbar from this link: http://developer.android.com/training/basics/actionbar/setting-up.html
Sometimes it occurs when some installations are not completed correctly, the process is stuck, or a file is still opened. So, when you try to run the installation again and the installation requires deleting, you can see the aforementioned error. In my case, shutting down the python processes and command prompt utilization helped.
A different case in which I encountered this was when I was using echo
to pipe the JSON into my python script and carelessly wrapped the JSON string in double quotes:
echo "{"thumbnailWidth": 640}" | myscript.py
Note that the JSON string itself has quotes and I should have done:
echo '{"thumbnailWidth": 640}' | myscript.py
As it was, this is what the python script received: {thumbnailWidth: 640}
; the double quotes were effectively stripped.
Right-Click on your project -> Properties -> Deployment Assembly.
On the Left-hand panel Click 'Add' and add the 'Project and External Dependencies'.
'Project and External Dependencies' will have all the spring related jars deployed along with your application
I have some problems with jquery mobile 1.4.5. For example it seems accepting format change only passing from "option". And there are some refresh problem with the calendar using "option". For all that have the same problems I can suggest this code:
$( "#mydatepicker" ).datepicker( "option", "dateFormat", "dd/mm/yy" );
$( "#mydatepicker" ).datepicker( "setDate", new Date());
$('.ui-datepicker-calendar').hide();
Make your audioSounds
and minTime
variables as static variables, as you are using them in a static method (playSound
).
Marking a method as static
prevents the usage of non-static (instance) members in that method.
To understand more , please read this SO QA:
It happen if there are two more ContextLoaderListener
exist in your project.
For ex: in my case 2 ContextLoaderListener
was exist using
So, remove any one ContextLoaderListener
from your project and run your application.
Don't call write.close()
in writeToFile()
.
At least in version 2.2.3 that I'm using, you must use autoClose
instead of autoclose
. Letter case matters.
I had a similar problem when deploying one of my portlets. The portlet has been developed for Liferay 6.2 on Windows. My runtime environment is Tomcat 7 running on JRE 1.6 (JRockit 1.6). I have recently migrated to Eclipse 2019-3. I checked my Java Build Path (Project->Properties, Libraries tab). I noticed that the Apache Tomcat that is specified in the list of JARs and class folders on the build path was unbound. I selected that item. I clicked on the Edit button. Server Libary dialog was opened. I selected the correct Apache Tomcat. After applying the change, I redeployed the portlet and the problem was resolved.
Sometimes you may need to delete the problematic portlet from the [Tomcat]/webapps
directory before deploying the corrected portlet. Also, sometimes I have experienced that deployment of a portlet takes more than usual, and redeploying it resolves the issue.
I had the same issue, for me this fixed the issue:
right click on the project ->maven -> update project
The answer to the above question is "none of the above". When you download new STS it won't support the old Spring Boot parent version. Just update parent version with latest comes with STS it will work.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
If you have problem getting the latest, just create a new Spring Starter Project. Go to File->New->Spring Start Project and create a demo project you will get the latest parent version, change your version with that all will work. I do this every time I change STS.
For those who struggle with this:
const value = $('SELECTOR').iCheck('update')[0].checked;
This directly returns true
or false
as boolean
.
This problem can be caused also by jvm version used to compile the project and the jvm supported by the servlet container. Try to Fix the project build path. For example if you deploy on tomcat 9, use jvm 1.8.0 or lower.
I faced a similar situation, so i replaced all the external jar files(poi-bin-3.17-20170915
) and make sure you add other jar
files present in lib and ooxml-lib
folders.
Hope this helps!!!:)
The option is locale: 'ru'
But first, you have to call the script ../moment.js/version/locale/ru.js
Hope this helps.
Try to delete the maven folder at ~/.m2/repository/org/apache/maven and build your project again to force the maven libraries be downloaded. This worked for me the last time I faced this java.lang.NoClassDefFoundError: org/apache/maven/shared/filtering/MavenFilteringException.
When you specify -jar
then the -cp
parameter will be ignored.
From the documentation:
When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.
You also cannot "include" needed jar files into another jar file (you would need to extract their contents and put the .class files into your jar file)
You have two options:
lib
directory into the manifest (you can use relative paths there)-cp
: java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main
It looks like you added a dependency on a Paypal library but did not include that library in your project:
Caused by: java.lang.ClassNotFoundException: com.paypal.exception.SSLConfigurationException
I'm not sure which jar, but it is most likely paypal-core.jar
. Try adding it under WEB-INF/lib
.
Another yet simple solution is to paste these line into the build.gradle file
dependencies {
//import of gridlayout
compile 'com.android.support:gridlayout-v7:19.0.0'
compile 'com.android.support:appcompat-v7:+'
}
if you are using gradlew
, go to ./gradle/wrapper/gradle-wrapper.properties
and change distributionUrl
to the correct version of gradle.
If you are using JDK14 try
distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip
I solve it editing the file bootstrap-datapicker.js.
Look for the text bellow in the file and edit the variable "Format:"
var defaults = $.fn.datepicker.defaults = {
assumeNearbyYear: false,
autoclose: false,
beforeShowDay: $.noop,
beforeShowMonth: $.noop,
beforeShowYear: $.noop,
beforeShowDecade: $.noop,
beforeShowCentury: $.noop,
calendarWeeks: false,
clearBtn: false,
toggleActive: false,
daysOfWeekDisabled: [],
daysOfWeekHighlighted: [],
datesDisabled: [],
endDate: Infinity,
forceParse: true,
format: 'dd/mm/yyyy',
keyboardNavigation: true,
language: 'en',
minViewMode: 0,
maxViewMode: 4,
multidate: false,
multidateSeparator: ',',
orientation: "auto",
rtl: false,
startDate: -Infinity,
startView: 0,
todayBtn: false,
todayHighlight: false,
weekStart: 0,
disableTouchKeyboard: false,
enableOnReadonly: true,
showOnFocus: true,
zIndexOffset: 10,
container: 'body',
immediateUpdates: false,
title: '',
templates: {
leftArrow: '«',
rightArrow: '»'
}
};
I actually built a Chrome extension that does exactly this, and for all web pages. The source code is on GitHub.
I find three bugs with Trello's approach, which I know because I've faced them myself :)
The copy doesn't work in these scenarios:
I solved #1 by always having a hidden span, rather than creating one when user hits Ctrl/Cmd.
I solved #2 by temporarily clearing the zero-length selection, saving the caret position, doing the copy and restoring the caret position.
I haven't found a fix for #3 yet :) (For information, check the open issue in my GitHub project).
Usually, define maven-compiler-plugin is sufficient enough. add the following to your compiler plugin definition.
<plugin>
<inherited>true</inherited>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
The problem is the indexing subplot
is using. Subplots are counted starting with 1!
Your code thus needs to read
fig=plt.figure(figsize=(15, 6),facecolor='w', edgecolor='k')
for i in range(10):
#this part is just arranging the data for contourf
ind2 = py.find(zz==i+1)
sfr_mass_mat = np.reshape(sfr_mass[ind2],(pixmax_x,pixmax_y))
sfr_mass_sub = sfr_mass[ind2]
zi = griddata(massloclist, sfrloclist, sfr_mass_sub,xi,yi,interp='nn')
temp = 251+i # this is to index the position of the subplot
ax=plt.subplot(temp)
ax.contourf(xi,yi,zi,5,cmap=plt.cm.Oranges)
plt.subplots_adjust(hspace = .5,wspace=.001)
#just annotating where each contour plot is being placed
ax.set_title(str(temp))
Note the change in the line where you calculate temp
It happens also if your code is expecting Java Mail 1.4 and your jars are Java Mail 1.3. Happened to me when upgraded Pentaho Kettle
Regards
Try this using HTML like here:
var myDate = window.document.getElementById("startdate").value;
Instructions:
which java
to find the path to the Java
executable file.su -
to become the root user.vi /root/.bash_profile
to open the system
bash_profile file in the Vi text editor. You can replace vi with
your preferred text editor.export JAVA_HOME=/usr/local/java/
at the bottom of the file.
Replace /usr/local/java
with the location found in step two.exit
to close the root session.echo $JAVA_HOME
to ensure that the path was set
correctly.I am not sure in your case. But as I know to run any jar file from cmd we can use following command:
Go up to the directory where your jar file is saved:
java -jar <jarfilename>.jar
But you can check following links. I hope it'll help you:
Run Netbeans maven project from command-line?
http://www.sonatype.com/books/mvnref-book/reference/running-sect-options.html
This problem also occurs if you have a private Rule in you class:
@Rule
private TemporaryFolder folderRule;
Make it public.
Or a super simple version with barely any css :)
<style>
.faq ul li {
display:block;
float:left;
padding:5px;
}
.faq ul li div {
display:none;
}
.faq ul li div:target {
display:block;
}
</style>
<div class="faq">
<ul>
<li><a href="#question1">Question 1</a>
<div id="question1">Answer 1 </div>
</li>
<li><a href="#question2">Question 2</a>
<div id="question2">Answer 2 </div>
</li>
<li><a href="#question3">Question 3</a>
<div id="question3">Answer 3 </div>
</li>
<li><a href="#question4">Question 4</a>
<div id="question4">Answer 4 </div>
</li>
<li><a href="#question5">Question 5</a>
<div id="question5">Answer 5 </div>
</li>
<li><a href="#question6">Question 6</a>
<div id="question6">Answer 6 </div>
</li>
</ul>
</div>
.clearfix
is defined in less/mixins.less
. Right above its definition is a comment with a link to this article:
The article explains how it all works.
UPDATE: Yes, link-only answers are bad. I knew this even at the time that I posted this answer, but I didn't feel like copying and pasting was OK due to copyright, plagiarism, and what have you. However, I now feel like it's OK since I have linked to the original article. I should also mention the author's name, though, for credit: Nicolas Gallagher. Here is the meat of the article (note that "Thierry’s method" is referring to Thierry Koblentz’s “clearfix reloaded”):
This “micro clearfix” generates pseudo-elements and sets their
display
totable
. This creates an anonymous table-cell and a new block formatting context that means the:before
pseudo-element prevents top-margin collapse. The:after
pseudo-element is used to clear the floats. As a result, there is no need to hide any generated content and the total amount of code needed is reduced.Including the
:before
selector is not necessary to clear the floats, but it prevents top-margins from collapsing in modern browsers. This has two benefits:
It ensures visual consistency with other float containment techniques that create a new block formatting context, e.g.,
overflow:hidden
It ensures visual consistency with IE 6/7 when
zoom:1
is applied.N.B.: There are circumstances in which IE 6/7 will not contain the bottom margins of floats within a new block formatting context. Further details can be found here: Better float containment in IE using CSS expressions.
The use of
content:" "
(note the space in the content string) avoids an Opera bug that creates space around clearfixed elements if thecontenteditable
attribute is also present somewhere in the HTML. Thanks to Sergio Cerrutti for spotting this fix. An alternative fix is to usefont:0/0 a
.Legacy Firefox
Firefox < 3.5 will benefit from using Thierry’s method with the addition of
visibility:hidden
to hide the inserted character. This is because legacy versions of Firefox needcontent:"."
to avoid extra space appearing between thebody
and its first child element, in certain circumstances (e.g., jsfiddle.net/necolas/K538S/.)Alternative float-containment methods that create a new block formatting context, such as applying
overflow:hidden
ordisplay:inline-block
to the container element, will also avoid this behaviour in legacy versions of Firefox.
hr {_x000D_
display: block;_x000D_
height: 1px;_x000D_
border: 0;_x000D_
border-top: 1px solid #ccc;_x000D_
margin: 1em 0;_x000D_
padding: 0;_x000D_
}
_x000D_
<div>Hello</div>_x000D_
<hr/>_x000D_
<div>World</div>
_x000D_
Here is how html5boilerplate does it:
hr {
display: block;
height: 1px;
border: 0;
border-top: 1px solid #ccc;
margin: 1em 0;
padding: 0;
}
Just in case there's anyone here using netbeans and has the same problem, all you have to do is
This should solve the problem
There is no official datepicker for bootstrap; as such, you should explicitly state which one you're using.
If you're using eternicode/bootstrap-datepicker, there's a startDate option. As discussed directly under the Options section in the README:
All options that take a "Date" can handle a Date object; a String formatted according to the given format; or a timedelta relative to today, eg '-1d', '+6m +1y', etc, where valid units are 'd' (day), 'w' (week), 'm' (month), and 'y' (year).
So you would do:
$('#datepicker').datepicker({
startDate: '+1d'
})
I faced the same problem,Eclipse splash screen for a second and it disappears.Then i noticed due to auto update of java there are two java version installed in my system. when i uninstalled one eclipse started working.
Thanks you..
When you extend indirectly JpaRepository ( KassaRepository extends BaseRepository that extends JpaRepository) then you have to annotate BaseRepository with @NoRepositoryBean
:
@NoRepositoryBean
public interface BaseRepository<T extends ModelBase> extends JpaRepository<T, Long> {
T findById(long id);
}
Make the class serializable by implementing the interface java.io.Serializable
.
java.io.Serializable
- Marker Interface which does not have any methods in it.ObjectOutputStream
that this object is a serializable object.I faced the same problem ant it took me tow days to figure out a solution that worked for me :
google-play-services_lib
(right click on the project delete )MainActivity
in my case ) if you have oneYou should see something like this :
Note : You should not have something like this ( the project should be referred from your workspace ):
I think that the problem is that tow projects are referencing the same library
Some of the solutions described here did not work for me. Others did, however they produced warnings on runtime and javadoc was still not linked. After some experimenting, I managed to solve this. The steps are:
Install the Google Play Services as recommended on Android Developers.
Set up your project as recommended on Android Developers.
If you followed 1. and 2., you should see two projects in your workspace: your project and google-play-services_lib project. Copy the docs
folder which contains the javadoc from <android-sdk>/extras/google/google_play_services/
to libs
folder of your project.
Copy google-play-services.jar
from <android-sdk>/extras/google/google_play_services/libproject/google-play-services_lib/libs
to 'libs' folder of your project.
In google-play-services_lib
project, edit libs/google-play-services.jar.properties . The <path>
in doc=<path>
should point to the subfolder reference
of the folder docs
, which you created in step 3.
In Eclipse, do Project > Clean. Done, javadoc is now linked.
"java.lang.NoClassDefFoundError: com.google.android.gms.R$styleable"
A had this error too, you need to: File -> import -> Existing Android Code Into Workspace -> Browse -> Android sdks -> extras -> google -> google_play_services -> lib_project -> google_play_services_lib and OK. Check the project and Finish.
The project goes to Package Explorer. Now go to your project (with error) -> properties -> Android and in Library click Add... the google_play_services_lib should be there! add and try again :)
try this, the following code solved my problem
table.dataTable tbody th,table.dataTable tbody td
{
white-space: nowrap;
}
for more information pls refer Here.
Closeable
extends AutoCloseable
, and is specifically dedicated to IO streams: it throws IOException instead of Exception, and is idempotent, whereas AutoCloseable doesn't provide this guarantee.
This is all explained in the javadoc of both interfaces.
Implementing AutoCloseable (or Closeable) allows a class to be used as a resource of the try-with-resources construct introduced in Java 7, which allows closing such resources automatically at the end of a block, without having to add a finally block which closes the resource explicitely.
Your class doesn't represent a closeable resource, and there's absolutely no point in implementing this interface: an IOTest can't be closed. It shouldn't even be possible to instantiate it, since it doesn't have any instance method. Remember that implementing an interface means that there is a is-a relationship between the class and the interface. You have no such relationship here.
a possible solution could be
create a batch file
there do a loop on lib directory for all files inside it and set each file unside lib on classpath
then after that run the jar
source for loop in batch file for info on loops
To be more specific if you are missing the class com.vaadin.external.org.slf4j.LoggerFactory add the below dependency.
<dependency>
<groupId>com.vaadin.external.slf4j</groupId>
<artifactId>vaadin-slf4j-jdk14</artifactId>
<version>1.6.1</version>
</dependency>
If you are missing any other org.slf4j.LoggerFactory, just go to Maven central class name search and search for the exact class name to determine what exact dependency you are missing.
The message you mention is quite clear:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
SLF4J API could not find a binding, and decided to default to a NOP implementation. In your case slf4j-log4j12.jar was somehow not visible when the LoggerFactory class was loaded into memory, which is admittedly very strange. What does "mvn dependency:tree" tell you?
The various dependency declarations may not even be directly at cause here. I strongly suspect that a pre-1.6 version of slf4j-api.jar
is being deployed without your knowledge.
web module -> Properties -> Deployment Assembly -> (add folder "src/main/webapp", Maven Dependencies and other needed module)
You could really, really, really optimize your code a lot by paying the price of creating the delegate only once (there's also no need to instantiate the class to call an static method). I've done something very similar, and I just cache a delegate to the "Run" method with the help of a helper class :-). It looks like this:
static class Indent{
public static void Run(){
// implementation
}
// other helper methods
}
static class MacroRunner {
static MacroRunner() {
BuildMacroRunnerList();
}
static void BuildMacroRunnerList() {
macroRunners = System.Reflection.Assembly.GetExecutingAssembly()
.GetTypes()
.Where(x => x.Namespace.ToUpper().Contains("MACRO"))
.Select(t => (Action)Delegate.CreateDelegate(
typeof(Action),
null,
t.GetMethod("Run", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public)))
.ToList();
}
static List<Action> macroRunners;
public static void Run() {
foreach(var run in macroRunners)
run();
}
}
It is MUCH faster this way.
If your method signature is different from Action you could replace the type-casts and typeof from Action to any of the needed Action and Func generic types, or declare your Delegate and use it. My own implementation uses Func to pretty print objects:
static class PrettyPrinter {
static PrettyPrinter() {
BuildPrettyPrinterList();
}
static void BuildPrettyPrinterList() {
printers = System.Reflection.Assembly.GetExecutingAssembly()
.GetTypes()
.Where(x => x.Name.EndsWith("PrettyPrinter"))
.Select(t => (Func<object, string>)Delegate.CreateDelegate(
typeof(Func<object, string>),
null,
t.GetMethod("Print", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public)))
.ToList();
}
static List<Func<object, string>> printers;
public static void Print(object obj) {
foreach(var printer in printers)
print(obj);
}
}
Prepare MANIFEST.MF
file with the following content
Manifest-Version: 1.0
Main-Class: org.testng.TestNG
Pack all test and dependency classes in the same jar, say tests.jar
jar cmf MANIFEST.MF tests.jar -C folder-with-classes/ .
Notice trailing ".", replace folder-with-classes/
with proper folder name or path.
Create testng.xml
with content like below
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Tests" verbose="5">
<test name="Test1">
<classes>
<class name="com.example.yourcompany.qa.Test1"/>
</classes>
</test>
</suite>
Replace com.example.yourcompany.qa.Test1
with path to your Test class.
Run your tests
java -jar tests.jar testng.xml
For Java 8 on a *nix OS, go to <jdk root>/jre/lib
(for me, /usr/java/jdk1.8.0_05/jre/lib
). From this directory, execute:
../../bin/unpack200 rt.pack rt.jar
../../bin/unpack200 jsse.pack jsse.rar
../../bin/unpack200 charsets.pack charsets.jar
To prevent version problems in case you have another JRE installed, use the same unpack200
that ships with the JRE you are fixing – that is, from the command line, use ../../bin/unpack200
(for me, this expands to /usr/java/jdk1.8.0_05/bin/unpack200
), not just unpack200
.
The simplest and the most efficient way is to use an uber plugin like this:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
<configuration>
<finalName>uber-${project.artifactId}-${project.version}</finalName>
</configuration>
</plugin>
You will have de-normalized all in one JAR file.
Found it. System property 'java.home' is not JAVA_HOME environment variable. JAVA_HOME points to the JDK, while java.home points to the JRE. See that page for more info.
Soo... My problem was that my startpoint was the jre folder (C:\jdk1.6.0_26\jre) and not the jdk folder (C:\jdk1.6.0_26) as I thought(tools.jar is on the C:\jdk1.6.0_26\lib folder ). The compile line in dependencies.gradle should be:
compile files("${System.properties['java.home']}/../lib/tools.jar")
use maven dependency
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
or download commons-io.1.3.2.jar to your lib folder
Me too faced the similar issue. But in my case I used apache-maven-3.3.3-src folder in path variables. Later I corrected those with correct path of folder apache-maven-3.3.3-bin. This resolved the issue. Am not telling that is the same error reported here but this way also you can get this error and rectify it. That is what I am trying to say here.
I had this problem and this is the best solution without any external or additional script libraries: In Javascript tags or file create this function: We assume here that canvas is your canvas:
function download(){
var download = document.getElementById("download");
var image = document.getElementById("canvas").toDataURL("image/png")
.replace("image/png", "image/octet-stream");
download.setAttribute("href", image);
}
In the body part of your HTML specify the button:
<a id="download" download="image.png"><button type="button" onClick="download()">Download</button></a>
This is working and download link looks like a button. Tested in Firefox and Chrome.
In my environment, I just added the two files to class path. And is work fine.
slf4j-jdk14-1.7.25.jar
slf4j-api-1.7.25.jar
For some reason, the lib is present while compiling, but missing while running.
My situation is, two versions of one lib conflict.
For example, A depends on B and C, while B depends on D:1.0, C depends on D:1.1, maven may just import D:1.0. If A uses one class which is in D:1.1 but not in D:1.0, a NoClassDefFoundError will be throwed.
If you are in this situation too, you need to resolve the dependency conflict.
If any project that you were using and now closed in workspace might lead to this issue, try deleting context from server folder inside eclipse or open the projects.
You may create a new list with an input of a previous list like so:
List one = new ArrayList()
//... add data, sort, etc
List two = new ArrayList(one);
This will allow you to modify the order or what elemtents are contained independent of the first list.
Keep in mind that the two lists will contain the same objects though, so if you modify an object in List two, the same object will be modified in list one.
example:
MyObject value1 = one.get(0);
MyObject value2 = two.get(0);
value1 == value2 //true
value1.setName("hello");
value2.getName(); //returns "hello"
Edit
To avoid this you need a deep copy of each element in the list like so:
List<Torero> one = new ArrayList<Torero>();
//add elements
List<Torero> two = new Arraylist<Torero>();
for(Torero t : one){
Torero copy = deepCopy(t);
two.add(copy);
}
with copy like the following:
public Torero deepCopy(Torero input){
Torero copy = new Torero();
copy.setValue(input.getValue());//.. copy primitives, deep copy objects again
return copy;
}
I solved my issue by doing this:
Strangely it started working again after that.
Inner Meta Class Document:
This document of django
Model metadata is “anything that’s not a field”, such as ordering options (ordering), database table name (db_table), or human-readable singular and plural names (verbose_name and verbose_name_plural)
. None are required, and adding class Meta to a model is completely optional.
https://docs.djangoproject.com/en/dev/topics/db/models/#meta-options
this
inside of doThings
is the window object. Try this instead:
var doThings = function (element) {
var eventHandler = function(ev, func){
if (element[ev] == undefined) {
return;
}
element[ev] = function(e){
func(e, element);
}
};
return {
eventHandler: eventHandler
};
};
You can also get this error if you try to include a jar which was compiled with jdk 1.7 instead of 1.6.
In my case, I figured this out by trying to package my app with the Ant scripts provided by the SDK, instead of ADT, and I noticed these errors, which ADT did not show me:
[dex] Pre-Dexing libjingle_peerconnection.jar -> libjingle_peerconnection-2f82c9bf868a6c58eaf2c3b2fe6a09f3.jar
[dx]
[dx] trouble processing:
[dx] bad class file magic (cafebabe) or version (0033.0000)
[dx] ...while parsing org/webrtc/StatsReport$Value.class
[dx] ...while processing org/webrtc/StatsReport$Value.class
I recompiled my jar with jdk 1.6 and the error was fixed.
This problem occurs if there are different jar versions. Especially versions of httpcore and httpclient. Use same versions of httpcore and httpclient.
Memory management in Linux is a bit tricky to understand, and I can't say I fully understand it yet, but I'll try to share a little bit of my experience and knowledge.
Short answer to your question: Yes there are other stuff included than whats in the list.
What's being shown in your list is applications run in userspace. The kernel uses memory for itself and modules, on top of that it also has a lower limit of free memory that you can't go under. When you've reached that level it will try to free up resources, and when it can't do that anymore, you end up with an OOM problem.
From the last line of your list you can read that the kernel reports a total-vm usage of: 1498536kB (1,5GB), where the total-vm includes both your physical RAM and swap space. You stated you don't have any swap but the kernel seems to think otherwise since your swap space is reported to be full (Total swap = 524284kB, Free swap = 0kB) and it reports a total vmem size of 1,5GB.
Another thing that can complicate things further is memory fragmentation. You can hit the OOM killer when the kernel tries to allocate lets say 4096kB of continous memory, but there are no free ones availible.
Now that alone probably won't help you solve the actual problem. I don't know if it's normal for your program to require that amount of memory, but I would recommend to try a static code analyzer like cppcheck to check for memory leaks or file descriptor leaks. You could also try to run it through Valgrind to get a bit more information out about memory usage.
When I ran into this error the fix was simple. I was simply missing a setter for a property. Make sure you define matching getters / setters for all your properties.
I think you are trying to over complicate things. A simple solution is to just style your checkbox by default with the unchecked styles and then add the checked state styles.
input[type="checkbox"] {
// Unchecked Styles
}
input[type="checkbox"]:checked {
// Checked Styles
}
I apologize for bringing up an old thread but felt like it could have used a better answer.
EDIT (3/3/2016):
W3C Specs state that :not(:checked)
as their example for selecting the unchecked state. However, this is explicitly the unchecked state and will only apply those styles to the unchecked state. This is useful for adding styling that is only needed on the unchecked state and would need removed from the checked state if used on the input[type="checkbox"]
selector. See example below for clarification.
input[type="checkbox"] {
/* Base Styles aka unchecked */
font-weight: 300; // Will be overwritten by :checked
font-size: 16px; // Base styling
}
input[type="checkbox"]:not(:checked) {
/* Explicit Unchecked Styles */
border: 1px solid #FF0000; // Only apply border to unchecked state
}
input[type="checkbox"]:checked {
/* Checked Styles */
font-weight: 900; // Use a bold font when checked
}
Without using :not(:checked)
in the example above the :checked
selector would have needed to use a border: none;
to achieve the same affect.
Use the input[type="checkbox"]
for base styling to reduce duplication.
Use the input[type="checkbox"]:not(:checked)
for explicit unchecked styles that you do not want to apply to the checked state.
On Android Studio:
1) Add multiDexEnabled = true
in your default Config
2) Add compile com.android.support:multidex:1.0.0 in your dependencies
3) Application class
extend MultiDexApplication
instead of just Application
Just include following in your code
<body background="C:\Users\Desktop\images.jpg">
if you want to specify the size and opacity you can use following
<p><img style="opacity:0.9;" src="C:\Users\Desktop\images.jpg" width="300" height="231" alt="Image" /></p>
I've seen this behavior today when the
<service name="A.B.C.D" behaviorConfiguration="returnFaults">
<endpoint contract="A.B.C.ID" binding="basicHttpBinding" address=""/>
</service>
was missing from the web.config. The service.svc
file was there and got served. It took a while to realize that the problem was not in the binding configuration it self...
This happened to me because I was using a Tomcat 5.5 catalina.sh
file with a Tomcat 7 installation. Using the catalina.sh
that came with the Tomcat 7 install fixed the problem.
I spent a lot of time looking for a solution to this problem too. Here's what i've found thus far:
If you want your users to be able to click on a button and copy some text, you may have to use Flash.
If you want your users to press Ctrl+C anywhere on the page, but always copy xyz to the clipboard, I wrote an all-JS solution in YUI3 (although it could easily be ported to other frameworks, or raw JS if you're feeling particularly self-loathing).
It involves creating a textbox off the screen which gets highlighted as soon as the user hits Ctrl/CMD. When they hit 'C' shortly after, they copy the hidden text. If they hit 'V', they get redirected to a container (of your choice) before the paste event fires.
This method can work well, because while you listen for the Ctrl/CMD keydown anywhere in the body, the 'A', 'C' or 'V' keydown listeners only attach to the hidden text box (and not the whole body). It also doesn't have to break the users expectations - you only get redirected to the hidden box if you had nothing selected to copy anyway!
Here's what i've got working on my site, but check http://at.cg/js/clipboard.js for updates if there are any:
YUI.add('clipboard', function(Y) {
// Change this to the id of the text area you would like to always paste in to:
pasteBox = Y.one('#pasteDIV');
// Make a hidden textbox somewhere off the page.
Y.one('body').append('<input id="copyBox" type="text" name="result" style="position:fixed; top:-20%;" onkeyup="pasteBox.focus()">');
copyBox = Y.one('#copyBox');
// Key bindings for Ctrl+A, Ctrl+C, Ctrl+V, etc:
// Catch Ctrl/Window/Apple keydown anywhere on the page.
Y.on('key', function(e) {
copyData();
// Uncomment below alert and remove keyCodes after 'down:' to figure out keyCodes for other buttons.
// alert(e.keyCode);
// }, 'body', 'down:', Y);
}, 'body', 'down:91,224,17', Y);
// Catch V - BUT ONLY WHEN PRESSED IN THE copyBox!!!
Y.on('key', function(e) {
// Oh no! The user wants to paste, but their about to paste into the hidden #copyBox!!
// Luckily, pastes happen on keyPress (which is why if you hold down the V you get lots of pastes), and we caught the V on keyDown (before keyPress).
// Thus, if we're quick, we can redirect the user to the right box and they can unload their paste into the appropriate container. phew.
pasteBox.select();
}, '#copyBox', 'down:86', Y);
// Catch A - BUT ONLY WHEN PRESSED IN THE copyBox!!!
Y.on('key', function(e) {
// User wants to select all - but he/she is in the hidden #copyBox! That wont do.. select the pasteBox instead (which is probably where they wanted to be).
pasteBox.select();
}, '#copyBox', 'down:65', Y);
// What to do when keybindings are fired:
// User has pressed Ctrl/Meta, and is probably about to press A,C or V. If they've got nothing selected, or have selected what you want them to copy, redirect to the hidden copyBox!
function copyData() {
var txt = '';
// props to Sabarinathan Arthanari for sharing with the world how to get the selected text on a page, cheers mate!
if (window.getSelection) { txt = window.getSelection(); }
else if (document.getSelection) { txt = document.getSelection(); }
else if (document.selection) { txt = document.selection.createRange().text; }
else alert('Something went wrong and I have no idea why - please contact me with your browser type (Firefox, Safari, etc) and what you tried to copy and I will fix this immediately!');
// If the user has nothing selected after pressing Ctrl/Meta, they might want to copy what you want them to copy.
if(txt=='') {
copyBox.select();
}
// They also might have manually selected what you wanted them to copy! How unnecessary! Maybe now is the time to tell them how silly they are..?!
else if (txt == copyBox.get('value')) {
alert('This site uses advanced copy/paste technology, possibly from the future.\n \nYou do not need to select things manually - just press Ctrl+C! \n \n(Ctrl+V will always paste to the main box too.)');
copyBox.select();
} else {
// They also might have selected something completely different! If so, let them. It's only fair.
}
}
});
Hope someone else finds this useful :]
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.21</version>
</dependency>
Put above mentioned dependency in pom.xml file
I encounter the same problem. I inited a bean object in static block like below:
static {
try{
mqttConfiguration = SpringBootBeanUtils.<MqttConfiguration>getBean(MqttConfiguration.class);
}catch (Throwable e){
System.out.println(e);
}
}
Just because the process the my bean obejct inition caused a NPE, I get trouble into it. So I think you should check you static code block carefully.
Your null pointer exception seems to be on this line:
String url = intent.getExtras().getString("userurl");
because intent.getExtras()
returns null when the intent doesn't have any extras.
You have to realize that this piece of code:
Intent Main = new Intent(this, ToClass.class);
Main.putExtra("userurl", url);
startActivity(Main);
doesn't start the activity you wrote in Main.java, it will attempt to start an activity called ToClass
and if that doesn't exist, your app crashes.
Also, there is no such thing as "android.intent.action.start"
so the manifest should look more like:
<activity android:name=".start" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name= ".Main">
</activity>
I hope this fixes some of the issues you are encountering but I strongly suggest you check out some "getting started" tutorials for android development and build up from there.
i got this error because I closed ServerSocket
inside a for loop that try to accept number of clients inside it (I did not finished accepting all clints)
so be careful where to close your Socket
just remove s from the permission you are using sss you have to use ss
I spent four hours trying various permutations & search suggestions.
At last, found this post that worked but not the best solution to change the original code to test it.
set classpath=JDKbin;JDKlib;JREbin;JRElib;myClassLib;.
java <packageName>.<className>
also tried the java ..\<packageName>.<className>
Neither worked.
However first response alone worked. Thank you so much Abhi!!!
"I found one another common reason. If you create the java file inside a package using IDE like eclipse, you will find the package name on the top of your java file like "package pkgName". If you try to run this file from command prompt, you will get the NoClassDefFoundError error. Remove the package name from the java file and use the commands in the command prompt. Wasted 3 hours for this. -- Abhi"
Curious if there is any other way to make it work without having to change the original code? Thank you!
If sounds like the type ACTInterface
is not public
, but is using the default accessibility of either internal
(if it is top-level) or private
(if it is nested in another type).
Giving the type the public
modifier would fix it.
Another approach is to make both the type and the method internal
, if that is your intent.
The issue is not the accessibility of the field (oActInterface
), but rather of the type ACTInterface
itself.
// The interface
interface Blah {
void something();
}
...
// Something that expects an object implementing that interface
void chewOnIt(Blah b) {
b.something();
}
...
// Let's provide an object of an anonymous class
chewOnIt(
new Blah() {
@Override
void something() { System.out.println("Anonymous something!"); }
}
);
To run Java class file from the command line, the syntax is:
java -classpath /path/to/jars <packageName>.<MainClassName>
where packageName (usually starts with either com
or org
) is the folder name where your class file is present.
For example if your main class name is App and Java package name of your app is com.foo.app
, then your class file needs to be in com/foo/app
folder (separate folder for each dot), so you run your app as:
$ java com.foo.app.App
Note: $
is indicating shell prompt, ignore it when typing
If your class doesn't have any package
name defined, simply run as: java App
.
If you've any other jar dependencies, make sure you specified your classpath parameter either with -cp
/-classpath
or using CLASSPATH
variable which points to the folder with your jar/war/ear/zip/class files. So on Linux you can prefix the command with: CLASSPATH=/path/to/jars
, on Windows you need to add the folder into system variable. If not set, the user class path consists of the current directory (.
).
Given we've created sample project using Maven as:
$ mvn archetype:generate -DgroupId=com.foo.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
and we've compiled our project by mvn compile
in our my-app/
dir, it'll generate our class file is in target/classes/com/foo/app/App.class
.
To run it, we can either specify class path via -cp
or going to it directly, check examples below:
$ find . -name "*.class"
./target/classes/com/foo/app/App.class
$ CLASSPATH=target/classes/ java com.foo.app.App
Hello World!
$ java -cp target/classes com.foo.app.App
Hello World!
$ java -classpath .:/path/to/other-jars:target/classes com.foo.app.App
Hello World!
$ cd target/classes && java com.foo.app.App
Hello World!
To double check your class and package name, you can use Java class file disassembler tool, e.g.:
$ javap target/classes/com/foo/app/App.class
Compiled from "App.java"
public class com.foo.app.App {
public com.foo.app.App();
public static void main(java.lang.String[]);
}
Note: javap
won't work if the compiled file has been obfuscated.
Function RemoveCharacter(ByVal stringToCleanUp, ByVal characterToRemove)
' replace the target with nothing
' Replace() returns a new String and does not modify the current one
Return stringToCleanUp.Replace(characterToRemove, "")
End Function
Here's more information about VB's Replace function
That data:image/png;base64
URL is cool, I’ve never run into it before. The long encrypted link is the actual image, i.e. no image call to the server. See RFC 2397 for details.
Side note: I have had trouble getting larger base64 images to render on IE8. I believe IE8 has a 32K limit that can be problematic for larger files. See this other StackOverflow thread for details.
For JBoss, in standalone.xml, put after .
<extensions>
</extensions>
<system-properties>
<property name="my.project.dir" value="/home/francesco" />
</system-properties>
For eclipse:
http://www.avajava.com/tutorials/lessons/how-do-i-set-system-properties.html?page=2
A NoClassDefFoundError
is thrown when the JRE can't find a class. In your case, it can't find the class com.google.common.base.Function
, which you most probably did not add to your classpath.
After downloading the following libraries:
and unzipping them and putting all JAR files in a folder called lib
, the test class:
import org.openqa.selenium.firefox.FirefoxDriver;
public class Test {
public static void main(String[] args) {
try{
FirefoxDriver driver = new FirefoxDriver();
driver.get("http:www.yahoo.com");
} catch(Exception e){
e.printStackTrace();
}
}
}
ran without any problems.
You can compile and run the class as follows:
# compile and run on Linux & Mac javac -cp .:lib/* Test.java java -cp .:lib/* Test # compile and run on Windows javac -cp .;lib/* Test.java java -cp .;lib/* Test
The source code for the Android mobile application open-gpstracker which you appreciated is available here.
You can checkout the code using SVN client application or via Git:
Debugging the source code will surely help you.
Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.
http://www.rgagnon.com/javadetails/java-0542.html
Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.
package filesendtest;
import java.io.*;
import java.net.*;
class TCPServer {
private final static String fileToSend = "C:\\test1.pdf";
public static void main(String args[]) {
while (true) {
ServerSocket welcomeSocket = null;
Socket connectionSocket = null;
BufferedOutputStream outToClient = null;
try {
welcomeSocket = new ServerSocket(3248);
connectionSocket = welcomeSocket.accept();
outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
} catch (IOException ex) {
// Do exception handling
}
if (outToClient != null) {
File myFile = new File( fileToSend );
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException ex) {
// Do exception handling
}
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0, mybytearray.length);
outToClient.flush();
outToClient.close();
connectionSocket.close();
// File sent, exit the main method
return;
} catch (IOException ex) {
// Do exception handling
}
}
}
}
}
package filesendtest;
import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;
class TCPClient {
private final static String serverIP = "127.0.0.1";
private final static int serverPort = 3248;
private final static String fileOutput = "C:\\testout.pdf";
public static void main(String args[]) {
byte[] aByte = new byte[1];
int bytesRead;
Socket clientSocket = null;
InputStream is = null;
try {
clientSocket = new Socket( serverIP , serverPort );
is = clientSocket.getInputStream();
} catch (IOException ex) {
// Do exception handling
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (is != null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream( fileOutput );
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
clientSocket.close();
} catch (IOException ex) {
// Do exception handling
}
}
}
}
Related
Byte array of unknown length in java
Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):
public static String md5String(File file) {
try {
InputStream fin = new FileInputStream(file);
java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int read;
do {
read = fin.read(buffer);
if (read > 0) {
md5er.update(buffer, 0, read);
}
} while (read != -1);
fin.close();
byte[] digest = md5er.digest();
if (digest == null) {
return null;
}
String strDigest = "0x";
for (int i = 0; i < digest.length; i++) {
strDigest += Integer.toString((digest[i] & 0xff)
+ 0x100, 16).substring(1).toUpperCase();
}
return strDigest;
} catch (Exception e) {
return null;
}
}
Typically, you would use a hash table for a situation where you want to map a name to some value, and be able to retrieve both.
var obj = { myFirstName: 'John' };_x000D_
obj.foo = 'Another name';_x000D_
for(key in obj)_x000D_
console.log(key + ': ' + obj[key]);
_x000D_
If you want to change one specific onclick event with jQuery, you better use the functions .on() and .off() with a namespace (see documentation).
Use .on()
to create your event and .off()
to remove it. You can also create a global object like g_specific_events_set = {};
to avoid duplicates:
$('#alert').click(function()_x000D_
{_x000D_
alert('First alert!');_x000D_
});_x000D_
_x000D_
g_specific_events_set = {};_x000D_
_x000D_
add_specific_event = function(namespace)_x000D_
{_x000D_
if (!g_specific_events_set[namespace])_x000D_
{_x000D_
$('#alert').on('click.' + namespace, function()_x000D_
{_x000D_
alert('SECOND ALERT!!!!!!');_x000D_
});_x000D_
g_specific_events_set[namespace] = true;_x000D_
}_x000D_
};_x000D_
_x000D_
remove_specific_event = function(namespace)_x000D_
{_x000D_
$('#alert').off('click.' + namespace);_x000D_
g_specific_events_set[namespace] = false;_x000D_
};_x000D_
_x000D_
_x000D_
_x000D_
$('#add').click(function(){ add_specific_event('eventnumber2'); });_x000D_
_x000D_
$('#remove').click(function(){ remove_specific_event('eventnumber2'); });
_x000D_
div {_x000D_
display:inline-block;_x000D_
vertical-align:top;_x000D_
margin:0 5px 1px 5px;_x000D_
padding:5px 20px;_x000D_
background:#ddd;_x000D_
border:1px solid #aaa;_x000D_
cursor:pointer;_x000D_
}_x000D_
div:active {_x000D_
margin-top:1px;_x000D_
margin-bottom:0px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="alert">_x000D_
Alert_x000D_
</div>_x000D_
<div id="add">_x000D_
Add event_x000D_
</div>_x000D_
<div id="remove">_x000D_
Remove event_x000D_
</div>
_x000D_
This error also comes if 2 versions of hamcrest-library or hamcrest-core is present in the classpath.
In the pom file, you can exclude the extra version and it works.
Two options, either reference the new jars in your classpath or unpack all classes in the enclosing jars and re-jar the whole lot! As far as I know packaging jars within jars is not recommeneded and you'll forever have the class not found exception!
You have included the dependency for sflj's api, but not the dependency for the implementation of the api, that is a separate jar, you could try slf4j-simple-1.6.1.jar.
(This is the KISS answer.)
Let's say you have several .java files in the current directory:
$ ls -1 *.java
javaFileName1.java
javaFileName2.java
Let's say each of them have a main()
method (so they are programs, not libs), then to compile them do:
javac *.java -d .
This will generate as many subfolders as "packages" the .java files are associated to. In my case all java files where inside under the same package name packageName
, so only one folder was generated with that name, so to execute each of them:
java -cp . packageName.javaFileName1
java -cp . packageName.javaFileName2
Usually when tests pass in eclipse and fail with maven it is a classpath issue because it is the main difference between the two.
So you can check the classpath with maven -X test and check the classpath of eclipse via the menus or in the .classpath file in the root of your project.
Are you sure for example that personservice-test.xml is in the classpath ?
I have also faced same problem....
Actually this problem is raised due to the fact that your program .class
files are not saved in that directory. Remove your CLASSPATH from your environment variable (you do no need to set classpath for simple Java programs) and reopen cmd prompt, then compile and execute.
If you observe carefully your .class
file will save in the same location. (I am not an expert, I am also basic programer if there is any mistake in my sentences please ignore it :-))
public class Sol {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}
}
I had this problem and it was caused by not "exporting" the library.Issue was just because the .class files for some classes are not available while packaging the APK.Compile time it will work fine with out exporiting
In my case I was using "CusrsorAdapter" class and under "JavaBuildPath->Order and Export" I didn't check the support V4 jar.Once it is selected issue is gone.
To make sure you are getting noClassDefFound error because of above reason, please check your logacat, you will see unknown super classs error at run time.
I found that I had a jar in WEB-INF/lib that was in my classpath, however when I upgraded it to the latest version, the filename was different. Removing the old jar file from the classpath and adding the new one fixed the problem. Strangely, Eclipse did not seem to warn me that the old jar file was missing and appeared to compile, however nothing was getting compiled, hence the NoClassDefFoundError. The clue for me was that the build/classes directory was setup in the project as the output folder but no class files were getting created there after the build.
you can get ip of that computer runs server program from DHCP list in that router you connected to.
To execute SomeClass.main(String [] args) from a deployed war file do:
Step 1: Write class SomeClass.java that has a main method method i.e. (public static void main(String[] args) {...})
Step 2: Deploy your WAR
Step 3: cd /usr/local/yourprojectsname/tomcat/webapps/projectName/WEB-INF
Step 4: java -cp "lib/jar1.jar:lib/jar2.jar: ... :lib/jarn.jar" com.mypackage.SomeClass arg1 arg2 ... arg3
Note1: (to see if the class SomeOtherClass.class is in /usr/tomcat/webapps/projectName/WEB-INF/lib)
run --> cd /usr/tomcat/webapps/projectName/WEB-INF/lib && find . -name '*.jar' | while read jarfile; do if jar tf "$jarfile" | grep SomeOtherClass.class; then echo "$jarfile"; fi; done
Note2: Write to standard out so you can see if your main actually works via print statements to the console. This is called a back door.
Note3: The comment above by Bozhidar Bozhanov seems correct
public static <T> void copyAvalableFields(@NotNull T source, @NotNull T target) throws IllegalAccessException {
Field[] fields = source.getClass().getDeclaredFields();
for (Field field : fields) {
if (!Modifier.isStatic(field.getModifiers())
&& !Modifier.isFinal(field.getModifiers())) {
field.set(target, field.get(source));
}
}
}
We read all the fields of the class. Filter non-static and non-final fields from the result. But there may be an error accessing non-public fields. For example, if this function is in the same class, and the class being copied does not contain public fields, an access error will occur. The solution may be to place this function in the same package or change access to public or in this code inside the loop call field.setAccessible (true); what will make the fields available
Even I was facing a similar error. Try below 2 steps (the first of which has been recommended here already) -
1. Add the dependencies to your pom.xml
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
jar
files in your .m2\repository\javax\<folder>\<version>\
directory.Adding commons-logging.jar or commons-logging-1.1.jar will solve this...
Try the Apache Commons HttpClient library instead of trying to roll your own: http://hc.apache.org/httpclient-3.x/index.html
From their sample code:
HttpClient httpclient = new HttpClient();
httpclient.getHostConfiguration().setProxy("myproxyhost", 8080);
/* Optional if authentication is required.
httpclient.getState().setProxyCredentials("my-proxy-realm", " myproxyhost",
new UsernamePasswordCredentials("my-proxy-username", "my-proxy-password"));
*/
PostMethod post = new PostMethod("https://someurl");
NameValuePair[] data = {
new NameValuePair("user", "joe"),
new NameValuePair("password", "bloggs")
};
post.setRequestBody(data);
// execute method and handle any error responses.
// ...
InputStream in = post.getResponseBodyAsStream();
// handle response.
/* Example for a GET reqeust
GetMethod httpget = new GetMethod("https://someurl");
try {
httpclient.executeMethod(httpget);
System.out.println(httpget.getStatusLine());
} finally {
httpget.releaseConnection();
}
*/
Example #1:
class A{
void met(){
Class.forName("com.example.Class1");
}
}
If com/example/Class1
doesn't exist in any of the classpaths, then It throws ClassNotFoundException
.
Example #2:
Class B{
void met(){
com.example.Class2 c = new com.example.Class2();
}
}
If com/example/Class2
existed while compiling B, but not found while execution, then It throws NoClassDefFoundError
.
Both are run time exceptions.
Realised that I was using OpenJDK when I saw this error. Fixed it once I installed the Oracle JDK instead.
You have no valid main method... The signature should be: public static void main(String[] args);
Hence, in your case the code should look like this:
public class Echo {
public static void main (String[] arg) {
System.out.println(arg[0]);
}
}
Edit: Please note that Oscar is also right in that you are missing . in your classpath, you would run into the problem I solve after you have dealt with that error.
Bit late for reply but this should do the trick
Type myType = Type.GetType("AssemblyQualifiedName");
your assembly qualified name should be like this
"Boom.Bam.Class, Boom.Bam, Version=1.0.0.262, Culture=neutral, PublicKeyToken=e16dba1a3c4385bd"
You can try -Xbootclasspath/a:path option of java application launcher. By description it specifies "a colon-separated path of directires, JAR archives, and ZIP archives to append to the default bootstrap class path."
You should check out this plugin:
https://github.com/kemayo/maphilight
and the demo:
http://davidlynch.org/js/maphilight/docs/demo_usa.html
if anything, you might be able to borrow some code from it to fix yours.
This approach from Microsoft works very well and provides the option to compare one list to another and switch them to get the difference in each. If you are comparing classes simply add your objects to two separate lists and then run the comparison.
Here's an elegant solution for Angular 5.x+:
Component:
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ElementRef,
EventEmitter,
Input,
OnInit,
Output,
Renderer2,
ViewChild
} from '@angular/core';
@Component({
selector: 'copy-to-clipboard',
templateUrl: './copy-to-clipboard.component.html',
styleUrls: ['./copy-to-clipboard.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class CopyToClipboardComponent implements OnInit {
@ViewChild('input') input: ElementRef;
@Input() size = 'md';
@Input() theme = 'complement';
@Input() content: string;
@Output() copied: EventEmitter<string> = new EventEmitter<string>();
@Output() error: EventEmitter<string> = new EventEmitter<string>();
constructor(private renderer: Renderer2) {}
ngOnInit() {}
copyToClipboard() {
const rootElement = this.renderer.selectRootElement(this.input.nativeElement);
// iOS Safari blocks programmtic execCommand copying normally, without this hack.
// https://stackoverflow.com/questions/34045777/copy-to-clipboard-using-javascript-in-ios
if (navigator.userAgent.match(/ipad|ipod|iphone/i)) {
this.renderer.setAttribute(this.input.nativeElement, 'contentEditable', 'true');
const range = document.createRange();
range.selectNodeContents(this.input.nativeElement);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
rootElement.setSelectionRange(0, 999999);
} else {
rootElement.select();
}
try {
document.execCommand('copy');
this.copied.emit();
} catch (err) {
this.error.emit(err);
}
};
}
Template:
<button class="btn btn-{{size}} btn-{{theme}}" type="button" (click)="copyToClipboard()">
<ng-content></ng-content>
</button>
<input #input class="hidden-input" [ngModel]="content">
Styles:
.hidden-input {
position: fixed;
top: 0;
left: 0;
width: 1px;
height: 1px;
padding: 0;
border: 0;
box-shadow: none;
outline: none;
background: transparent;
}
If you need to use multiple dialog boxes on one page and open, close and reopen them the following works well:
JS CODE:
$(".sectionHelp").click(function(){
$("#dialog_"+$(this).attr('id')).dialog({autoOpen: false});
$("#dialog_"+$(this).attr('id')).dialog("open");
});
HTML:
<div class="dialog" id="dialog_help1" title="Dialog Title 1">
<p>Dialog 1</p>
</div>
<div class="dialog" id="dialog_help2" title="Dialog Title 2">
<p>Dialog 2 </p>
</div>
<a href="#" id="help1" class="sectionHelp"></a>
<a href="#" id="help2" class="sectionHelp"></a>
CSS:
div.dialog{
display:none;
}
if you use external libraries in your program and you try to pack all together in a jar file it's not that simple, because of classpath issues etc.
I'd prefer to use OneJar for this issue.
Everyone talks here about some Java configuration stuff, JVM problems etc., in my case the error was not related to these topics at all and had a very trivial and easy to solve reason: I had a wrong annotation at my endpoint in my Controller (Spring Boot application).
You could search for the corresponding key or you could "invert" the dictionary, but considering how you use it, it would be best if you just iterated over key/value pairs in the first place, which you can do with items()
. Then you have both directly in variables and don't need a lookup at all:
for key, value in PIX0.items():
NUM = input("What is the Resolution of %s?" % key)
if NUM == value:
You can of course use that both ways then.
Or if you don't actually need the dictionary for something else, you could ditch the dictionary and have an ordinary list of pairs.
Without seeing your full code, this is impossible to answer with any certainty. The error usually occurs when you are trying to unload a control rather than the form.
Make sure that you don't have the "me" in brackets.
Also if you can post the full code for the userform it would help massively.
Put your parameters in a hash table and pass them like this:
$postParams = @{username='me';moredata='qwerty'}
Invoke-WebRequest -Uri http://example.com/foobar -Method POST -Body $postParams
JSON decoding in JavaScript is simply an eval() if you trust the string or the more safe code you can find on http://json.org if you don't.
You will then have a JavaScript datastructure that you can traverse for the data you need.
$string = preg_replace('~&([a-z]{1,2})(acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', htmlentities($string, ENT_COMPAT, 'UTF-8'));
Steps to rename author name after commit pushed
git rebase i HEAD~10 (10 is the total commit to display on rebase)
If you Get anything like below
fatal: It seems that there is already a rebase-merge directory, and
I wonder if you are in the middle of another rebase. If that is the
case, please try
git rebase (--continue | --abort | --skip)
If that is not the case, please rm -fr
".git/rebase-merge"
and run me again. I am stopping in case you still have something
valuable there.
Then type "git rebase --continue" or "git rebase --abort" as per your need
pick 897fe9e simplify code a little
pick abb60f9 add new feature
pick dc18f70 bugfix
Now you need to add below command just below of the commit you want to edit, like below
pick 897fe9e simplify code a little
exec git commit --amend --author 'Author Name <[email protected]>'
pick abb60f9 add new feature
exec git commit --amend --author 'Author Name <[email protected]>'
pick dc18f70 bugfix
exec git commit --amend --author 'Author Name <[email protected]>'
That's it, now just press ESC, :wq and you are all set
Then git push origin HEAD:BRANCH NAME -f [please take care of -f Force push]
like git push -f
or git push origin HEAD: dev -f
Antti Sykäri's algorithm is nice and short. I initially made a variation that replaced JavaScript's Math.random
when you call Math.seed(s)
, but then Jason commented that returning the function would be better:
Math.seed = function(s) {
return function() {
s = Math.sin(s) * 10000; return s - Math.floor(s);
};
};
// usage:
var random1 = Math.seed(42);
var random2 = Math.seed(random1());
Math.random = Math.seed(random2());
This gives you another functionality that JavaScript doesn't have: multiple independent random generators. That is especially important if you want to have multiple repeatable simulations running at the same time.
This option comes in curl 7.73.0:
curl --create-dirs -O --output-dir /tmp/receipes https://example.com/pancakes.jpg
They're two phrases that describe the same thing from (very slightly) different viewpoints. Parallel programming is describing the situation from the viewpoint of the hardware -- there are at least two processors (possibly within a single physical package) working on a problem in parallel. Concurrent programming is describing things more from the viewpoint of the software -- two or more actions may happen at exactly the same time (concurrently).
The problem here is that people are trying to use the two phrases to draw a clear distinction when none really exists. The reality is that the dividing line they're trying to draw has been fuzzy and indistinct for decades, and has grown ever more indistinct over time.
What they're trying to discuss is the fact that once upon a time, most computers had only a single CPU. When you executed multiple processes (or threads) on that single CPU, the CPU was only really executing one instruction from one of those threads at a time. The appearance of concurrency was an illusion--the CPU switching between executing instructions from different threads quickly enough that to human perception (to which anything less than 100 ms or so looks instantaneous) it looked like it was doing many things at once.
The obvious contrast to this is a computer with multiple CPUs, or a CPU with multiple cores, so the machine is executing instructions from multiple threads and/or processes at exactly the same time; code executing one can't/doesn't have any effect on code executing in the other.
Now the problem: such a clean distinction has almost never existed. Computer designers are actually fairly intelligent, so they noticed a long time ago that (for example) when you needed to read some data from an I/O device such as a disk, it took a long time (in terms of CPU cycles) to finish. Instead of leaving the CPU idle while that happened, they figured out various ways of letting one process/thread make an I/O request, and let code from some other process/thread execute on the CPU while the I/O request completed.
So, long before multi-core CPUs became the norm, we had operations from multiple threads happening in parallel.
That's only the tip of the iceberg though. Decades ago, computers started providing another level of parallelism as well. Again, being fairly intelligent people, computer designers noticed that in a lot of cases, they had instructions that didn't affect each other, so it was possible to execute more than one instruction from the same stream at the same time. One early example that became pretty well known was the Control Data 6600. This was (by a fairly wide margin) the fastest computer on earth when it was introduced in 1964--and much of the same basic architecture remains in use today. It tracked the resources used by each instruction, and had a set of execution units that executed instructions as soon as the resources on which they depended became available, very similar to the design of most recent Intel/AMD processors.
But (as the commercials used to say) wait--that's not all. There's yet another design element to add still further confusion. It's been given quite a few different names (e.g., "Hyperthreading", "SMT", "CMP"), but they all refer to the same basic idea: a CPU that can execute multiple threads simultaneously, using a combination of some resources that are independent for each thread, and some resources that are shared between the threads. In a typical case this is combined with the instruction-level parallelism outlined above. To do that, we have two (or more) sets of architectural registers. Then we have a set of execution units that can execute instructions as soon as the necessary resources become available. These often combine well because the instructions from the separate streams virtually never depend on the same resources.
Then, of course, we get to modern systems with multiple cores. Here things are obvious, right? We have N (somewhere between 2 and 256 or so, at the moment) separate cores, that can all execute instructions at the same time, so we have clear-cut case of real parallelism--executing instructions in one process/thread doesn't affect executing instructions in another.
Well, sort of. Even here we have some independent resources (registers, execution units, at least one level of cache) and some shared resources (typically at least the lowest level of cache, and definitely the memory controllers and bandwidth to memory).
To summarize: the simple scenarios people like to contrast between shared resources and independent resources virtually never happen in real life. With all resources shared, we end up with something like MS-DOS, where we can only run one program at a time, and we have to stop running one before we can run the other at all. With completely independent resources, we have N computers running MS-DOS (without even a network to connect them) with no ability to share anything between them at all (because if we can even share a file, well, that's a shared resource, a violation of the basic premise of nothing being shared).
Every interesting case involves some combination of independent resources and shared resources. Every reasonably modern computer (and a lot that aren't at all modern) has at least some ability to carry out at least a few independent operations simultaneously, and just about anything more sophisticated than MS-DOS has taken advantage of that to at least some degree.
The nice, clean division between "concurrent" and "parallel" that people like to draw just doesn't exist, and almost never has. What people like to classify as "concurrent" usually still involves at least one and often more different types of parallel execution. What they like to classify as "parallel" often involves sharing resources and (for example) one process blocking another's execution while using a resource that's shared between the two.
People trying to draw a clean distinction between "parallel" and "concurrent" are living in a fantasy of computers that never actually existed.
This is my solution. When Set-Location fails it throws a non-terminating error which is not seen by the catch block. Adding -ErrorAction Stop is the easiest way around this.
try {
Set-Location "$YourPath" -ErrorAction Stop;
} catch {
Write-Host "Exception has been caught";
}
As an option you can use double brace initialization here:
List<String> list = new ArrayList<String>(){
{
add("a");
add("b");
}
};
str.erase(str.begin() + str.size() - 1)
str.erase(str.rbegin())
does not compile unfortunately, since reverse_iterator
cannot be converted to a normal_iterator.
C++11 is your friend in this case.
Here's a special case where one of data field has semicolon (";") as part of it's data in that case most of answers above will fail.
Solution it that case will be
string[] csvRows = System.IO.File.ReadAllLines(FullyQaulifiedFileName);
string[] fields = null;
List<string> lstFields;
string field;
bool quoteStarted = false;
foreach (string csvRow in csvRows)
{
lstFields = new List<string>();
field = "";
for (int i = 0; i < csvRow.Length; i++)
{
string tmp = csvRow.ElementAt(i).ToString();
if(String.Compare(tmp,"\"")==0)
{
quoteStarted = !quoteStarted;
}
if (String.Compare(tmp, ";") == 0 && !quoteStarted)
{
lstFields.Add(field);
field = "";
}
else if (String.Compare(tmp, "\"") != 0)
{
field += tmp;
}
}
if(!string.IsNullOrEmpty(field))
{
lstFields.Add(field);
field = "";
}
// This will hold values for each column for current row under processing
fields = lstFields.ToArray();
}
You can also open your js file path in the chrome browser which will only display text.
However you can dynamically create the page by including:
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'myjs.js';
document.head.appendChild(script);
Now you can have access to the js variables and functions in the console.
Now when you explore the elements it should have included.
So not i guess you dont need a html file.
Please NOTE that this procedure of adding the reporting services described by @Rich Shealer above will be iterated every time you start a different project. In order to avoid that:
If you may need to set up a different computer (eg, at home without internet), then keep your downloaded installers from the marketplace somewhere safe, ie:
Fetch the following libraries from the packages or bin folder of the application you have created with reporting services in it:
Install the 2 components from 1 above
You are now good to go! ReportViewer icon will be added to your toolbar, and you will also now find Report and ReportWizard templates added to your Common list of templates when you want to add a New Item... (Report) to your project
NB: When set up using Nuget package manager, the Report and ReportWizard templates are grouped under Reporting. Using my method described above however does not add the Reporting grouping in installed templates, but I dont think it is any trouble given that it enables you to quickly integrate rdlc without internet and without downloading what you already have from Nuget every time!
You mean how to get date without the time component? Use DateTimePicker.Value.Date But you need to format the output to your needs.
[>=1000]#,##0,"K";[<=-1000]-#,##0,"K";0
teylyn's answer is great. This just adds negatives beyond -1000 following the same format.
// Use any date you want, for the purpose of this example we use 1980-08-03.
var myDate = new DateTime(1980,8,3);
var lastDayOfMonth = new DateTime(myDate.Year, myDate.Month, DateTime.DaysInMonth(myDate.Year, myDate.Month));
const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const firstDate = new Date(2008, 1, 12);
const secondDate = new Date(2008, 1, 22);
const diffDays = Math.round(Math.abs((firstDate - secondDate) / oneDay));
If you want to save the model and wants to resume the training later:
Single GPU: Save:
state = {
'epoch': epoch,
'state_dict': model.state_dict(),
'optimizer': optimizer.state_dict(),
}
savepath='checkpoint.t7'
torch.save(state,savepath)
Load:
checkpoint = torch.load('checkpoint.t7')
model.load_state_dict(checkpoint['state_dict'])
optimizer.load_state_dict(checkpoint['optimizer'])
epoch = checkpoint['epoch']
Multiple GPU: Save
state = {
'epoch': epoch,
'state_dict': model.module.state_dict(),
'optimizer': optimizer.state_dict(),
}
savepath='checkpoint.t7'
torch.save(state,savepath)
Load:
checkpoint = torch.load('checkpoint.t7')
model.load_state_dict(checkpoint['state_dict'])
optimizer.load_state_dict(checkpoint['optimizer'])
epoch = checkpoint['epoch']
#Don't call DataParallel before loading the model otherwise you will get an error
model = nn.DataParallel(model) #ignore the line if you want to load on Single GPU
Yes, any string in JavaScript has a toLowerCase()
method that will return a new string that is the old string in all lower case. The old string will remain unchanged.
So, you can do something like:
"Foo".toLowerCase();
document.getElementById('myField').value.toLowerCase();
Maven uses batch files to do its business. With any batch script, you must call another script using the call
command so it knows to return back to your script after the called script completes. Try prepending call
to all commands.
Another thing you could try is using the start
command which should work similarly.
( BONUS1 : NODES MAY or MAY NOT BE ORDERED )
( BONUS2 : NO 3RD PARTY LIBRARY NEEDED, PLAIN JS )
( BONUS3 : User "Elias Rabl" says this is the fastest solution, see his answer below )
Here it is:
const createDataTree = dataset => {
const hashTable = Object.create(null);
dataset.forEach(aData => hashTable[aData.ID] = {...aData, childNodes: []});
const dataTree = [];
dataset.forEach(aData => {
if(aData.parentID) hashTable[aData.parentID].childNodes.push(hashTable[aData.ID])
else dataTree.push(hashTable[aData.ID])
});
return dataTree;
};
Here is a test, it might help you to understand how the solution works :
it('creates a correct shape of dataTree', () => {
const dataSet = [{
"ID": 1,
"Phone": "(403) 125-2552",
"City": "Coevorden",
"Name": "Grady"
}, {
"ID": 2,
"parentID": 1,
"Phone": "(979) 486-1932",
"City": "Chelm",
"Name": "Scarlet"
}];
const expectedDataTree = [{
"ID": 1,
"Phone": "(403) 125-2552",
"City": "Coevorden",
"Name": "Grady",
childNodes: [{
"ID": 2,
"parentID": 1,
"Phone": "(979) 486-1932",
"City": "Chelm",
"Name": "Scarlet",
childNodes : []
}]
}];
expect(createDataTree(dataSet)).toEqual(expectedDataTree);
});
This worked for me with a string-array named shoes
loaded from the projects resources:
Spinner spinnerCountShoes = (Spinner)findViewById(R.id.spinner_countshoes);
ArrayAdapter<String> spinnerCountShoesArrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_spinner_dropdown_item,
getResources().getStringArray(R.array.shoes));
spinnerCountShoes.setAdapter(spinnerCountShoesArrayAdapter);
This is my resource file (res/values/arrays.xml
) with the string-array named shoes
:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="shoes">
<item>0</item>
<item>5</item>
<item>10</item>
<item>100</item>
<item>1000</item>
<item>10000</item>
</string-array>
</resources>
With this method it's easier to make it multilingual (if necessary).
Again if using IOS on Xamarin there is a new component called BTProgressHUD in the component store
You can use numpy.shape
.
import numpy as np
x = np.array([[1, 2],[3, 4],[5, 6]])
Result:
>>> x
array([[1, 2],
[3, 4],
[5, 6]])
>>> np.shape(x)
(3, 2)
First value in the tuple is number rows = 3; second value in the tuple is number of columns = 2.
In windows for me it kept saying "id_ed25135: No such file or directory" upon entering above commands. So I went to the folder, copied the path within folder explorer and added "\id_ed25135" at the end.
This is what I ended up typing and worked:
ssh-keygen -p -f C:\Users\john\.ssh\id_ed25135
This worked. Because for some reason, in Cmder the default path was something like this C:\Users\capit/.ssh/id_ed25135 (some were backslashes: "\" and some were forward slashes: "/")
Update: created a js fiddle here to see it live: http://jsfiddle.net/HFMvX/
I went through tons of google searches and didn't find anything satisfying. i like how passpack have done it so essentially reverse-engineered their approach, here we go:
function scorePassword(pass) {
var score = 0;
if (!pass)
return score;
// award every unique letter until 5 repetitions
var letters = new Object();
for (var i=0; i<pass.length; i++) {
letters[pass[i]] = (letters[pass[i]] || 0) + 1;
score += 5.0 / letters[pass[i]];
}
// bonus points for mixing it up
var variations = {
digits: /\d/.test(pass),
lower: /[a-z]/.test(pass),
upper: /[A-Z]/.test(pass),
nonWords: /\W/.test(pass),
}
var variationCount = 0;
for (var check in variations) {
variationCount += (variations[check] == true) ? 1 : 0;
}
score += (variationCount - 1) * 10;
return parseInt(score);
}
Good passwords start to score around 60 or so, here's function to translate that in words:
function checkPassStrength(pass) {
var score = scorePassword(pass);
if (score > 80)
return "strong";
if (score > 60)
return "good";
if (score >= 30)
return "weak";
return "";
}
you might want to tune this a bit but i found it working for me nicely
Add a try/catch block, if the transaction succeeds it will commit the changes, if the transaction fails the transaction is rolled back:
BEGIN TRANSACTION [Tran1]
BEGIN TRY
INSERT INTO [Test].[dbo].[T1] ([Title], [AVG])
VALUES ('Tidd130', 130), ('Tidd230', 230)
UPDATE [Test].[dbo].[T1]
SET [Title] = N'az2' ,[AVG] = 1
WHERE [dbo].[T1].[Title] = N'az'
COMMIT TRANSACTION [Tran1]
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION [Tran1]
END CATCH
use DateTime.Now
try this:
DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
I've encountered this today and the accepted answers did not work for me. Here is how I did it.
if( $('#div-id *').length === 0 ) {
// your code here...
}
My solution checks if there are any elements inside the div so it would still mark the div empty if there is only text inside it.
Got to
gradle-wrapper.properties
Change the version of the below mentioned distribution (gradle-5.6.4-bin.zip)
distributionUrl=https://services.gradle.org/distributions/gradle-5.6.4-bin.zip
I ran across the same issue you did but the above answers did not solve my issue. The only way I was able to resolve it - was to make a class and use specific widths to trigger the wrapping for my specific use case. As an example, I provided a snippet below - but I found you will need to adjust it for the table in question - since I typically use multiple colspans depending on the layout. The reasoning I believe Bootstrap is failing - is because it removes the wrapping constraints to get a full table for the scrollbars. THe colspan must be tripping it up.
<style>
@media (max-width: 768px) { /* use the max to specify at each container level */
.specifictd {
width:360px; /* adjust to desired wrapping */
display:table;
white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}
}
I hope this helps
VBA has a CurDir keyword that will return the "current directory" as stored in Excel. I'm not sure all the things that affect the current directory, but definitely opening or saving a workbook will change it.
MyWorkbook.SaveAs CurDir & Application.PathSeparator & "MySavedWorkbook.xls"
This assumes that the sheet you want to save has never been saved and you want to define the file name in code.
Note: This is an answer useful for Python's ElementTree standard library without using hardcoded namespaces.
To extract namespace's prefixes and URI from XML data you can use ElementTree.iterparse
function, parsing only namespace start events (start-ns):
>>> from io import StringIO
>>> from xml.etree import ElementTree
>>> my_schema = u'''<rdf:RDF xml:base="http://dbpedia.org/ontology/"
... xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
... xmlns:owl="http://www.w3.org/2002/07/owl#"
... xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
... xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
... xmlns="http://dbpedia.org/ontology/">
...
... <owl:Class rdf:about="http://dbpedia.org/ontology/BasketballLeague">
... <rdfs:label xml:lang="en">basketball league</rdfs:label>
... <rdfs:comment xml:lang="en">
... a group of sports teams that compete against each other
... in Basketball
... </rdfs:comment>
... </owl:Class>
...
... </rdf:RDF>'''
>>> my_namespaces = dict([
... node for _, node in ElementTree.iterparse(
... StringIO(my_schema), events=['start-ns']
... )
... ])
>>> from pprint import pprint
>>> pprint(my_namespaces)
{'': 'http://dbpedia.org/ontology/',
'owl': 'http://www.w3.org/2002/07/owl#',
'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
'rdfs': 'http://www.w3.org/2000/01/rdf-schema#',
'xsd': 'http://www.w3.org/2001/XMLSchema#'}
Then the dictionary can be passed as argument to the search functions:
root.findall('owl:Class', my_namespaces)
the pattern maybe looks like this :
substr(STRING, ( length(STRING) - (TOTAL_GET_LENGTH - 1) ),TOTAL_GET_LENGTH)
in your case , it will like this :
substr('299123456789', (length('299123456789')-(9 - 1)),9)
substr('299123456789', (12-8),9)
substr('299123456789', 4,9)
the result ? of course '123456789'
the length is dynamic , voila :)
When you have 'NA' values in the column, then
sum(as.numeric(JuneData1$Account.Balance), na.rm = TRUE)
Did you try using the -ArgumentList
parameter:
invoke-command -ComputerName studio -ScriptBlock { param ( $myarg ) ping.exe $myarg } -ArgumentList localhost
http://technet.microsoft.com/en-us/library/dd347578.aspx
An example of invoking a program that is not in the path and has a space in it's folder path:
invoke-command -ComputerName Computer1 -ScriptBlock { param ($myarg) & 'C:\Program Files\program.exe' -something $myarg } -ArgumentList "myArgValue"
If the value of the argument is static you can just provide it in the script block like this:
invoke-command -ComputerName Computer1 -ScriptBlock { & 'C:\Program Files\program.exe' -something "myArgValue" }
Try this in your css:
#ntext{
color: #000000;
}
Then the following in all your navigation bar list codes:
<li><a href="#" id="ntext"><span class="glyphicon glyphicon-user"></span> About</a></li>
The question is asked in a misleading manner. "Removing the selected
attribute" and "deselecting all options" are entirely different things.
To deselect all options in a documented, cross-browser manner use either
$("select").val([]);
or
// Note the use of .prop instead of .attr
$("select option").prop("selected", false);
You could use table
:
R> x <- read.table(textConnection('
Believe Age Gender Presents Behaviour
1 FALSE 9 male 25 naughty
2 TRUE 5 male 20 nice
3 TRUE 4 female 30 nice
4 TRUE 4 male 34 naughty'
), header=TRUE)
R> table(x$Believe)
FALSE TRUE
1 3
using sinon
:
const mockAction = sinon.stub(MyService.prototype,'actionBeingCalled')
.returns(httpPromise(200));
Known that, httpPromise
can be :
const httpPromise = (code) => new Promise((resolve, reject) =>
(code >= 200 && code <= 299) ? resolve({ code }) : reject({ code, error:true })
);
Use the Path
class from System.IO
. It contains useful calls for manipulating file paths, including GetDirectoryName
which does what you want, returning the directory portion of the file path.
Usage is simple.
string directoryPath = Path.GetDirectoryName(filePath);
There is no simple and elegant solution to the Redirect
problem in ASP.Net WebForms. You can choose between the Dirty solution and the Tedious solution
Dirty: Response.Redirect(url)
sends a redirect to the browser, and then throws a ThreadAbortedException
to terminate the current thread. So no code is executed past the Redirect()-call. Downsides: It is bad practice and have performance implications to kill threads like this. Also, ThreadAbortedExceptions
will show up in exception logging.
Tedious: The recommended way is to call Response.Redirect(url, false)
and then Context.ApplicationInstance.CompleteRequest()
However, code execution will continue and the rest of the event handlers in the page lifecycle will still be executed. (E.g. if you perform the redirect in Page_Load, not only will the rest of the handler be executed, Page_PreRender and so on will also still be called - the rendered page will just not be sent to the browser. You can avoid the extra processing by e.g. setting a flag on the page, and then let subsequent event handlers check this flag before before doing any processing.
(The documentation to CompleteRequest
states that it "Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution". This can easily be misunderstood. It does bypass further HTTP filters and modules, but it doesn't bypass further events in the current page lifecycle.)
The deeper problem is that WebForms lacks a level of abstraction. When you are in a event handler, you are already in the process of building a page to output. Redirecting in an event handler is ugly because you are terminating a partially generated page in order to generate a different page. MVC does not have this problem since the control flow is separate from rendering views, so you can do a clean redirect by simply returning a RedirectAction
in the controller, without generating a view.
No need to add permission and do tricks. Just use below text in your main layout.
android:keepScreenOn="true"
Here is a quick example:
public class One {
/**
* @param args
*/
public static void main(String[] args) {
double a = 4.56777;
System.out.println( new Float( Math.round(a)) );
}
}
the result and output will be: 5.0
the closest upper bound Float to the starting value of double a = 4.56777
in this case the use of round is recommended since it takes in double
values and provides whole long
values
Regards
Now I use the following to get the list of changed files my current branch has, comparing it to master (the compare-to branch is easily changed):
git log --oneline --pretty="format:" --name-only master.. | awk 'NF' | sort -u
Before, I used to rely on this:
git log --name-status <branch>..<branch> | grep -E '^[A-Z]\b' | sort -k 2,2 -u
which outputs a list of files only and their state (added, modified, deleted):
A foo/bar/xyz/foo.txt
M foo/bor/bar.txt
...
The -k2,2
option for sort, makes it sort by file path instead of the type of change (A, M, D,).
I think what you want to do is this:
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="--Select One--" Value="" />
</asp:DropDownList>
Make sure the 'AppendDataBoundItems' is set to true or else you will clear the '--Select One--' list item when you bind your data.
If you have the 'AutoPostBack' property of the drop down list set to true you will have to also set the 'CausesValidation' property to true then use a 'RequiredFieldValidator' to make sure the '--Select One--' option doesn't cause a postback.
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="DropDownList1"></asp:RequiredFieldValidator>
<?php
if (!preg_match("/^(http|ftp):/", $_POST['url'])) {
$_POST['url'] = 'http://'.$_POST['url'];
}
$url = $_POST['url'];
?>
This code will add http:// to the URL if it’s not there.
Running this in the commandline will fix the problem also. SETX VisualStudioVersion "12.0"
You should initialize your variables outside the while loop. Outside the while loop, they currently have no scope. You are just relying on the good graces of php to let the values carry over outside the loop
$hn = "";
$pid = "";
$datereg = "";
$prefix = "";
$fname = "";
$lname = "";
$age = "";
$sex = "";
while (...){}
alternatively, it looks like you are just expecting a single row back. so you could just say
$row = pg_fetch_array($result);
if(!row) {
return array();
}
$hn = $row["patient_hn"];
$pid = $row["patient_id"];
$datereg = $row["patient_date_register"];
$prefix = $row["patient_prefix"];
$fname = $row["patient_fname"];
$lname = $row["patient_lname"];
$age = $row["patient_age"];
$sex = $row["patient_sex"];
return array($hn,$pid,$datereg,$prefix,$fname,$lname,$age,$sex) ;
Creating a builder launcher is an issue since 2 projects cannot have the same external tool build name. Each name has to be unique. I am currently facing this issue to automate my build and copy the JAR to an external location.
I am using IBM's Zip Builder, but that is just a help but not doing the real.
People can try using IBM ZIP Creation plugin. http://www.ibm.com/developerworks/websphere/library/techarticles/0112_deboer/deboer2.html#download
e.which doesn't work in IE try e.keyCode, also you probably want to use keydown() instead of keypress() if you are targeting IE.
See http://unixpapa.com/js/key.html for more information.
Download MongoDB and install it on your local machine. Link https://www.mongodb.com/try/download/enterprise
Extract the file and put it on the desktop. Create another folder where you want to store the data. I have created mongodb-data folder. Then run the below command.
Desktop/mongodb/bin/mongod --dbpath=/Users/yourname/Desktop/mongodb-data/
Before the hyphen is the executable path of your mongoDB and after hyphen is your data store.
You can do that with bool query and combination of must and must_not like this:
GET index/_search
{
"query": {
"bool": {
"must": [
{"exists": {"field": "field1"}}
],
"must_not": [
{"term": {"field1": ""}}
]
}
}
}
I tested this with Elasticsearch 5.6.5 in Kibana.
As stated by a few others, this is a linking error. The section of code where this function is being called doesn't know what this function is. It either needs to be declared in a header file an defined in its own source file, or defined or declared in the same source file, above where it's being called.
Edit: In older versions of C, C89/C90, function declarations weren't actually required. So, you could just add the definition anywhere in the file in which you're using the function, even after the call and the compiler would infer the declaration. For example,
int main()
{
int a = func();
}
int func()
{
return 1;
}
However, this isn't good practice today and most languages, C++ for example, won't allow it. One way to get away with defining the function in the same source file in which you're using it, is to declare it at the beginning of the file. So, the previous example would look like this instead.
int func();
int main()
{
int a = func();
}
int func()
{
return 1;
}
I agree with @bortunac's solution. my.conf is mysql specific while netstat will provide you with all the listening ports.
Perhaps use both, one to confirm which is port set for mysql and the other to check that the system is listening through that port.
My client uses CentOS 6.6 and I have found the my.conf file under /etc/, so I used:
grep port /etc/my.conf
(CentOS 6.6)
I know this is old, but for the sake of somebody looking for an answer...
There's a JSON library for MYSQL that can be found here You need to have root access to your server and be comfortable installing plugins (it's simple).
1) upload the lib_mysqludf_json.so into the plugins directory of your mysql installation
2) run the lib_mysqludf_json.sql file (it pretty much does all of the work for you. If you run into trouble just delete anything that starts with 'DROP FUNCTION...')
3) encode your query in something like this:
SELECT json_array(
group_concat(json_object( name, email))
FROM ....
WHERE ...
and it will return something like
[
{
"name": "something",
"email": "[email protected]"
},
{
"name": "someone",
"email": "[email protected]"
}
]
Open a terminal window. Type:
node -v
This will display your nodejs
version.
Navigate to where you saved your script and input:
node script.js
This will run your script.
For modern browsers, use td:nth-child(2)
for the second td
, and td:nth-child(3)
for the third. Remember that these retrieve the second and third td
for every row.
If you need compatibility with IE older than version 9, use sibling combinators or JavaScript as suggested by Tim. Also see my answer to this related question for an explanation and illustration of his method.
Going back to Servlet days, web.xml can have only one <context-param>
, so only one context object gets created when server loads an application and the data in that context is shared among all resources (Ex: Servlets and JSPs). It is same as having Database driver name in the context, which will not change. In similar way, when we declare contextConfigLocation param in <contex-param>
Spring creates one Application Context object.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.myApp.ApplicationContext</param-value>
</context-param>
You can have multiple Servlets in an application. For example you might want to handle /secure/* requests in one way and /non-seucre/* in other way. For each of these Servlets you can have a context object, which is a WebApplicationContext.
<servlet>
<servlet-name>SecureSpringDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>com.myapp.secure.SecureContext</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>SecureSpringDispatcher</servlet-name>
<url-pattern>/secure/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>NonSecureSpringDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>com.myapp.non-secure.NonSecureContext</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>NonSecureSpringDispatcher</servlet-name>
<url-pattern>/non-secure/*</url-patten>
</servlet-mapping>
We can create a new CSS class for div.
.div {
position: absolute;
left: 150px;
width: 200px;
height: 120px;
}
The pragmatic regex (<[^>]+) style=".*?"
will solve this problem in all reasonable cases. The part of the match that is not the first captured group should be removed, like this:
$output = preg_replace('/(<[^>]+) style=".*?"/i', '$1', $input);
Match a <
followed by one or more "not >
" until we come to space
and the style="..."
part. The /i
makes it work even with STYLE="..."
. Replace this match with $1
, which is the captured group. It will leave the tag as is, if the tag doesn't include style="..."
.
I just came across this. The correct answer is:
awk 'BEGIN{FS=OFS=","} {gsub(/^[[:space:]]+|[[:space:]]+$/,"",$2)} 1'
You just need a binary (with debugging symbols included) that is identical to the one that generated the core dump file. Then you can run gdb path/to/the/binary path/to/the/core/dump/file
to debug it.
When it starts up, you can use bt
(for backtrace) to get a stack trace from the time of the crash. In the backtrace, each function invocation is given a number. You can use frame number
(replacing number with the corresponding number in the stack trace) to select a particular stack frame.
You can then use list
to see code around that function, and info locals
to see the local variables. You can also use print name_of_variable
(replacing "name_of_variable" with a variable name) to see its value.
Typing help
within GDB will give you a prompt that will let you see additional commands.
Using scanf
is very easy, this is an example :
if (scanf("%d", &val_a_tester) == 1) {
... // it's an integer
}
When an object in a TempDataDictionary
is read, it will be marked for deletion at the end of that request.
That means if you put something on TempData like
TempData["value"] = "someValueForNextRequest";
And on another request you access it, the value will be there but as soon as you read it, the value will be marked for deletion:
//second request, read value and is marked for deletion
object value = TempData["value"];
//third request, value is not there as it was deleted at the end of the second request
TempData["value"] == null
The Peek
and Keep
methods allow you to read the value without marking it for deletion. Say we get back to the first request where the value was saved to TempData.
With Peek
you get the value without marking it for deletion with a single call, see msdn:
//second request, PEEK value so it is not deleted at the end of the request
object value = TempData.Peek("value");
//third request, read value and mark it for deletion
object value = TempData["value"];
With Keep
you specify a key that was marked for deletion that you want to keep. Retrieving the object and later on saving it from deletion are 2 different calls. See msdn
//second request, get value marking it from deletion
object value = TempData["value"];
//later on decide to keep it
TempData.Keep("value");
//third request, read value and mark it for deletion
object value = TempData["value"];
You can use Peek
when you always want to retain the value for another request. Use Keep
when retaining the value depends on additional logic.
You have 2 good questions about how TempData works here and here
Hope it helps!
To stop animation you may set such objectAnimator that do nothing, e.g.
first when manual flipping there is animation left to right:
flipper.setInAnimation(leftIn);
flipper.setOutAnimation(rightOut);
then when switching to auto flipping there's no animation
flipper.setInAnimation(doNothing);
flipper.setOutAnimation(doNothing);
doNothing = ObjectAnimator.ofFloat(flipper, "x", 0f, 0f).setDuration(flipperSwipingDuration);
Give your radiobutton a custom style:
<style name="MyRadioButtonStyle" parent="@android:style/Widget.CompoundButton.RadioButton">
<item name="android:button">@drawable/custom_btn_radio</item>
</style>
custom_btn_radio.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:state_window_focused="false"
android:drawable="@drawable/btn_radio_on" />
<item android:state_checked="false" android:state_window_focused="false"
android:drawable="@drawable/btn_radio_off" />
<item android:state_checked="true" android:state_pressed="true"
android:drawable="@drawable/btn_radio_on_pressed" />
<item android:state_checked="false" android:state_pressed="true"
android:drawable="@drawable/btn_radio_off_pressed" />
<item android:state_checked="true" android:state_focused="true"
android:drawable="@drawable/btn_radio_on_selected" />
<item android:state_checked="false" android:state_focused="true"
android:drawable="@drawable/btn_radio_off_selected" />
<item android:state_checked="false" android:drawable="@drawable/btn_radio_off" />
<item android:state_checked="true" android:drawable="@drawable/btn_radio_on" />
</selector>
Replace the drawables with your own.
[root@localhost Certificate]# openssl pkcs12 -export -in
/opt/Certificate/115c99f4c5aa98f5.crt -inkey /opt/Certificate/ravi.in.key -certfile
/opt/Certificate/gd_bundle-g2-g1.crt -out RaviNew.p12
Enter Export Password: <Password>
Verifying - Enter Export Password: <Password>
Note :- Above Export Pasworrd write down anywhere because it is must to create JKS file ( It is depend on your choice what password you want to make )
keytool -importkeystore -srckeystore DigiEduNew.p12 -srcstoretype pkcs12 -destkeystore finaldigiEdu.jks -deststoretype JKS
Importing keystore DigiEduNew.p12 to finaldigiEdu.jks...
Enter destination keystore password: <Any Password >
Re-enter new password: <Any Password >
Enter source keystore password: <.P12 Password >
Entry for alias 1 successfully imported.
Import command completed: 1 entries successfully imported, 0 entries failed or
cancelled
Warning:
The JKS keystore uses a proprietary format. It is recommended to migrate to PKCS12
which is an industry standard format using "keytool -importkeystore -srckeystore
finaldigiEdu.jks -destkeystore finaldigiEdu.jks -deststoretype pkcs12".
I've tried several minifiers and they either remove too little or too much.
This code removes redundant empty spaces and optional HTML (ending) tags. Also it plays it safe and does not remove anything that could potentially break HTML, JS or CSS.
Also the code shows how to do that in Zend Framework:
class Application_Plugin_Minify extends Zend_Controller_Plugin_Abstract {
public function dispatchLoopShutdown() {
$response = $this->getResponse();
$body = $response->getBody(); //actually returns both HEAD and BODY
//remove redundant (white-space) characters
$replace = array(
//remove tabs before and after HTML tags
'/\>[^\S ]+/s' => '>',
'/[^\S ]+\</s' => '<',
//shorten multiple whitespace sequences; keep new-line characters because they matter in JS!!!
'/([\t ])+/s' => ' ',
//remove leading and trailing spaces
'/^([\t ])+/m' => '',
'/([\t ])+$/m' => '',
// remove JS line comments (simple only); do NOT remove lines containing URL (e.g. 'src="http://server.com/"')!!!
'~//[a-zA-Z0-9 ]+$~m' => '',
//remove empty lines (sequence of line-end and white-space characters)
'/[\r\n]+([\t ]?[\r\n]+)+/s' => "\n",
//remove empty lines (between HTML tags); cannot remove just any line-end characters because in inline JS they can matter!
'/\>[\r\n\t ]+\</s' => '><',
//remove "empty" lines containing only JS's block end character; join with next line (e.g. "}\n}\n</script>" --> "}}</script>"
'/}[\r\n\t ]+/s' => '}',
'/}[\r\n\t ]+,[\r\n\t ]+/s' => '},',
//remove new-line after JS's function or condition start; join with next line
'/\)[\r\n\t ]?{[\r\n\t ]+/s' => '){',
'/,[\r\n\t ]?{[\r\n\t ]+/s' => ',{',
//remove new-line after JS's line end (only most obvious and safe cases)
'/\),[\r\n\t ]+/s' => '),',
//remove quotes from HTML attributes that does not contain spaces; keep quotes around URLs!
'~([\r\n\t ])?([a-zA-Z0-9]+)="([a-zA-Z0-9_/\\-]+)"([\r\n\t ])?~s' => '$1$2=$3$4', //$1 and $4 insert first white-space character found before/after attribute
);
$body = preg_replace(array_keys($replace), array_values($replace), $body);
//remove optional ending tags (see http://www.w3.org/TR/html5/syntax.html#syntax-tag-omission )
$remove = array(
'</option>', '</li>', '</dt>', '</dd>', '</tr>', '</th>', '</td>'
);
$body = str_ireplace($remove, '', $body);
$response->setBody($body);
}
}
But note that when using gZip compression your code gets compressed a lot more that any minification can do so combining minification and gZip is pointless, because time saved by downloading is lost by minification and also saves minimum.
Here are my results (download via 3G network):
Original HTML: 150kB 180ms download
gZipped HTML: 24kB 40ms
minified HTML: 120kB 150ms download + 150ms minification
min+gzip HTML: 22kB 30ms download + 150ms minification
Emacs has a number of extensions to allow blind users to manipulate text files. You'd have to consult an expert on the topic, but emacs has text-to-speech capabilities. And probably more.
In addition, there's BLinux:
Linux for the blind. Been around for a very long time. More than ten years I think, and very mature.
It is configured to use localhost:25
for the mail server.
The error message says that it can't connect to localhost:25
.
Therefore you have two options:
This operator allows you to determine the type of an object.
It returns a boolean
value.
For example
package test;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;
public class instanceoftest
{
public static void main(String args[])
{
Map m=new HashMap();
System.out.println("Returns a boolean value "+(m instanceof Map));
System.out.println("Returns a boolean value "+(m instanceof HashMap));
System.out.println("Returns a boolean value "+(m instanceof Object));
System.out.println("Returns a boolean value "+(m instanceof Date));
}
}
the output is:
Returns a boolean value true
Returns a boolean value true
Returns a boolean value true
Returns a boolean value false
Simplest solution is mySql workBench just copy the .sql file text to query window of mysql-workbenck and just execute it, All renaming things will done by it.
Check if you have used a proper view engine. In my case I updated the npm and end up in changing the engine to 'hjs'(I was trying to uninstall jade to use pug). So changing it to jade from hjs in app.js file worked for me.
app.set('view engine','jade');
Why hasn't anyone thought it was worth mentioning Scanner?
Scanner input = new Scanner(new File("foo.txt"));
while (input.hasNextLine())
{
System.out.println(input.nextLine());
}
I've tested all anwers, but they were all too slow for me. If you have Excel installed you can use the COM.
I thought initially it would be slower since it will load everything for the actual Excel application, but it isn't for huge files. Maybe because the algorithm for opening and saving files runs a heavily optimized compiled code, Microsoft guys make a lot of money for it after all.
import sys
import os
import glob
from win32com.client import Dispatch
def main(path):
excel = Dispatch("Excel.Application")
if is_full_path(path):
process_file(excel, path)
else:
files = glob.glob(path)
for file_path in files:
process_file(excel, file_path)
excel.Quit()
def process_file(excel, path):
fullpath = os.path.abspath(path)
full_csv_path = os.path.splitext(fullpath)[0] + '.csv'
workbook = excel.Workbooks.Open(fullpath)
workbook.Worksheets(1).SaveAs(full_csv_path, 6)
workbook.Saved = 1
workbook.Close()
def is_full_path(path):
return path.find(":") > -1
if __name__ == '__main__':
main(sys.argv[1])
This is very raw code and won't check for errors, print help or anything, it will just create a csv file for each file that matches the pattern you entered in the function so you can batch process a lot of files only launching excel application once.
With Microsoft SQL Server:
Use Syntax for CONVERT:
CONVERT ( data_type [ ( length ) ] , expression [ , style ] )
Example:
SELECT CONVERT(varchar,d.dateValue,1-9)
For the style you can find more info here: MSDN - Cast and Convert (Transact-SQL).
I was recently struggling with a similar problem. It turned out that the database was missing indexes on foreign keys. That caused Oracle to lock many more records than required which quickly led to a deadlock during high concurrency.
Here is an excellent article with lots of good detail, suggestions, and details about how to fix a deadlock: http://www.oratechinfo.co.uk/deadlocks.html#unindex_fk
No need to do all above lengthy steps.
Simply delete c:\Users\.m2\Repository\org folder
Maven will automatically downloads what it needs
function millisToMinutesAndSeconds(millis) {
var minutes = Math.floor(millis / 60000);
var seconds = ((millis % 60000) / 1000).toFixed(0);
return minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
}
millisToMinutesAndSeconds(298999); // "4:59"
millisToMinutesAndSeconds(60999); // "1:01"
As User HelpingHand
pointed in the comments the return statement should be
return (seconds == 60 ? (minutes+1) + ":00" : minutes + ":" + (seconds < 10 ? "0" : "") + seconds);
EDIT: This function only swaps the endianness of aligned 16 bit words. A function often necessary for UTF-16/UCS-2 encodings. EDIT END.
If you want to change the endianess of a memory block you can use my blazingly fast approach. Your memory array should have a size that is a multiple of 8.
#include <stddef.h>
#include <limits.h>
#include <stdint.h>
void ChangeMemEndianness(uint64_t *mem, size_t size)
{
uint64_t m1 = 0xFF00FF00FF00FF00ULL, m2 = m1 >> CHAR_BIT;
size = (size + (sizeof (uint64_t) - 1)) / sizeof (uint64_t);
for(; size; size--, mem++)
*mem = ((*mem & m1) >> CHAR_BIT) | ((*mem & m2) << CHAR_BIT);
}
This kind of function is useful for changing the endianess of Unicode UCS-2/UTF-16 files.
The following link explains filters in Angular extremely well. It shows how it is possible to define custom sort logic within an ng-repeat. http://toddmotto.com/everything-about-custom-filters-in-angular-js
For sorting object with properties, this is the code I have used: (Note that this sort is the standard JavaScript sort method and not specific to angular) Column Name is the name of the property on which sorting is to be performed.
self.myArray.sort(function(itemA, itemB) {
if (self.sortOrder === "ASC") {
return itemA[columnName] > itemB[columnName];
} else {
return itemA[columnName] < itemB[columnName];
}
});
Create an array to store the objects:
ArrayList<MyObject> list = new ArrayList<MyObject>();
In a single step:
list.add(new MyObject (1, 2, 3)); //Create a new object and adding it to list.
or
MyObject myObject = new MyObject (1, 2, 3); //Create a new object.
list.add(myObject); // Adding it to the list.
select COUNT(*)
from Monitor as m
inner join Monitor_Request as mr on mr.Company_ID=m.Company_id
group by m.Company_id
having COUNT(m.Monitor_id)>=5
Resurrecting this question because the regex in the accepted answer doesn't seem quite correct to me. Why? Because
(?<=This is)(.*)(?=sentence)
will match my first sentence. This is my second
in This is my first sentence. This is my second sentence.
You need a lazy quantifier between the two lookarounds. Adding a ?
makes the star lazy.
This matches what you want:
(?<=This is).*?(?=sentence)
See demo. I removed the capture group, which was not needed.
DOTALL Mode to Match Across Line Breaks
Note that in the demo the "dot matches line breaks mode" (a.k.a.) dot-all is set (see how to turn on DOTALL in various languages). In many regex flavors, you can set it with the online modifier (?s)
, turning the expression into:
(?s)(?<=This is).*?(?=sentence)
Reference
var post:NSString = "api=myposts&userid=\(uid)&page_no=0&limit_no=10"
NSLog("PostData: %@",post);
var url1:NSURL = NSURL(string: url)!
var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
var postLength:NSString = String( postData.length )
var request:NSMutableURLRequest = NSMutableURLRequest(URL: url1)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var reponseError: NSError?
var response: NSURLResponse?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
if ( urlData != nil ) {
let res = response as NSHTTPURLResponse!;
NSLog("Response code: %ld", res.statusCode);
if (res.statusCode >= 200 && res.statusCode < 300)
{
var responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
NSLog("Response ==> %@", responseData);
var error: NSError?
let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary
let success:NSInteger = jsonData.valueForKey("error") as NSInteger
//[jsonData[@"success"] integerValue];
NSLog("Success: %ld", success);
if(success == 0)
{
NSLog("Login SUCCESS");
self.dataArr = jsonData.valueForKey("data") as NSMutableArray
self.table.reloadData()
} else {
NSLog("Login failed1");
ZAActivityBar.showErrorWithStatus("error", forAction: "Action2")
}
} else {
NSLog("Login failed2");
ZAActivityBar.showErrorWithStatus("error", forAction: "Action2")
}
} else {
NSLog("Login failed3");
ZAActivityBar.showErrorWithStatus("error", forAction: "Action2")
}
it will help you surely
It is indeed possible with the following code
<div href="#" id='a'>
Hover me
</div>
<div id='b'>
Show me
</div>
and css
#a {
display: block;
}
#a:hover + #b {
display:block;
}
#b {
display:none;
}
Now by hovering on element #a shows element #b.
CREATE FUNCTION [dbo].[_DATES]
(
@startDate DATETIME,
@endDate DATETIME
)
RETURNS
@DATES TABLE(
DATE1 DATETIME
)
AS
BEGIN
WHILE @startDate <= @endDate
BEGIN
INSERT INTO @DATES (DATE1)
SELECT @startDate
SELECT @startDate = DATEADD(d,1,@startDate)
END
RETURN
END
Thanks to A Ghazal, just what I needed. Here's a slightly cleaned up version of his(her) answer:
create FUNCTION [dbo].[fnMinutesToDuration]
(
@minutes int
)
RETURNS nvarchar(30)
-- Based on http://stackoverflow.com/questions/17733616/how-to-convert-number-of-minutes-to-hhmm-format-in-tsql
AS
BEGIN
return rtrim(isnull(cast(nullif((@minutes / 60)
, 0
) as varchar
) + 'h '
,''
)
+ isnull(CAST(nullif((@minutes % 60)
,0
) AS VARCHAR(2)
) + 'm'
,''
)
)
end
The answer I was looking for is at https://unix.stackexchange.com/a/9557/114862.
Using the
-c
flag when the local file is of greater or equal size to the server version will avoid re-downloading.
I tested below code with SQL Server 2008 R2 Express and I believe we should have solution for all 6 steps you outlined. Let's take on them one-by-one:
We can enable TCP/IP protocol with WMI:
set wmiComputer = GetObject( _
"winmgmts:" _
& "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProtocols = wmiComputer.ExecQuery( _
"select * from ServerNetworkProtocol " _
& "where InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'")
if tcpProtocols.Count = 1 then
' set tcpProtocol = tcpProtocols(0)
' I wish this worked, but unfortunately
' there's no int-indexed Item property in this type
' Doing this instead
for each tcpProtocol in tcpProtocols
dim setEnableResult
setEnableResult = tcpProtocol.SetEnable()
if setEnableResult <> 0 then
Wscript.Echo "Failed!"
end if
next
end if
I believe your solution will work, just make sure you specify the right port. I suggest we pick a different port than 1433 and make it a static port SQL Server Express will be listening on. I will be using 3456 in this post, but please pick a different number in the real implementation (I feel that we will see a lot of applications using 3456 soon :-)
We can use WMI again. Since we are using static port 3456, we just need to update two properties in IPAll section: disable dynamic ports and set the listening port to 3456
:
set wmiComputer = GetObject( _
"winmgmts:" _
& "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProperties = wmiComputer.ExecQuery( _
"select * from ServerNetworkProtocolProperty " _
& "where InstanceName='SQLEXPRESS' and " _
& "ProtocolName='Tcp' and IPAddressName='IPAll'")
for each tcpProperty in tcpProperties
dim setValueResult, requestedValue
if tcpProperty.PropertyName = "TcpPort" then
requestedValue = "3456"
elseif tcpProperty.PropertyName ="TcpDynamicPorts" then
requestedValue = ""
end if
setValueResult = tcpProperty.SetStringValue(requestedValue)
if setValueResult = 0 then
Wscript.Echo "" & tcpProperty.PropertyName & " set."
else
Wscript.Echo "" & tcpProperty.PropertyName & " failed!"
end if
next
Note that I didn't have to enable any of the individual addresses to make it work, but if it is required in your case, you should be able to extend this script easily to do so.
Just a reminder that when working with WMI, WBEMTest.exe is your best friend!
I wish we could use WMI again, but unfortunately this setting is not exposed through WMI. There are two other options:
Use LoginMode
property of Microsoft.SqlServer.Management.Smo.Server
class, as described here.
Use LoginMode value in SQL Server registry, as described in this post. Note that by default the SQL Server Express instance is named SQLEXPRESS
, so for my SQL Server 2008 R2 Express instance the right registry key was
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQLServer
.
You got this one covered.
Since we are using a static port assigned to our SQL Server Express instance, there's no need to use instance name in the server address anymore.
SQLCMD -U sa -P newPassword -S 192.168.0.120,3456
Please let me know if this works for you (fingers crossed!).
%~dp0
may be a relative path.
To convert it to a full path, try something like this:
pushd %~dp0
set script_dir=%CD%
popd
It runs Java compiled code, it can maintain database connection pools, it can log errors of various types. I'd call it an application server, in fact I do. In our environment we have Apache as the webserver fronting a number of different application servers, including Tomcat and Coldfusion, and others.
If you wrap your form elements in a form tag with a name attribute you can easily get the value using document.formName.radioGroupName.value.
<form name="myForm">
<input type="radio" id="genderm" name="gender" value="male" />
<label for="genderm">Male</label>
<input type="radio" id="genderf" name="gender" value="female" />
<label for="genderf">Female</label>
</form>
<script>
var selected = document.forms.myForm.gender.value;
</script>
Lookarounds can be nested.
So this regex matches "drupal-6.14/" that is not followed by "sites" that is not followed by "/all" or "/default".
Confusing? Using different words, we can say it matches "drupal-6.14/" that is not followed by "sites" unless that is further followed by "/all" or "/default"
Under Trace properties > Events Selection tab > select show all columns. Now under column filters, you should see the database name. Enter the database name for the Like section and you should see traces only for that database.
You'll first need to separate your numpy array into two separate arrays containing x and y values.
x = [1, 2, 3, 9]
y = [1, 4, 1, 3]
curve_fit also requires a function that provides the type of fit you would like. For instance, a linear fit would use a function like
def func(x, a, b):
return a*x + b
scipy.optimize.curve_fit(func, x, y)
will return a numpy array containing two arrays: the first will contain values for a
and b
that best fit your data, and the second will be the covariance of the optimal fit parameters.
Here's an example for a linear fit with the data you provided.
import numpy as np
from scipy.optimize import curve_fit
x = np.array([1, 2, 3, 9])
y = np.array([1, 4, 1, 3])
def fit_func(x, a, b):
return a*x + b
params = curve_fit(fit_func, x, y)
[a, b] = params[0]
This code will return a = 0.135483870968
and b = 1.74193548387
Here's a plot with your points and the linear fit... which is clearly a bad one, but you can change the fitting function to obtain whatever type of fit you would like.
Use numpy's random.permuation
function:
In [1]: df = pd.DataFrame({'A':range(10), 'B':range(10)})
In [2]: df
Out[2]:
A B
0 0 0
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
6 6 6
7 7 7
8 8 8
9 9 9
In [3]: df.reindex(np.random.permutation(df.index))
Out[3]:
A B
0 0 0
5 5 5
6 6 6
3 3 3
8 8 8
7 7 7
9 9 9
1 1 1
2 2 2
4 4 4
See http://jsfiddle.net/qP8DY/24/
You can add a class (such as "success-dialog" in my example) to div#success, either directly in your HTML, or in your JavaScript by adding to the dialogClass option, as I've done.
$('#success').dialog({
height: 50,
width: 350,
modal: true,
resizable: true,
dialogClass: 'no-close success-dialog'
});
Then just add the success-dialog class to your CSS rules as appropriate. To indicate an element with two (or more) classes applied to it, just write them all together, with no spaces in between. For example:
.ui-dialog.success-dialog {
font-family: Verdana,Arial,sans-serif;
font-size: .8em;
}
Try eUML2. its a single click generator no need to drag n drop.
You should consider using a dict
type instead of pre-initialized list. The cost of a dictionary look-up is small and comparable to the cost of accessing arbitrary list element.
And when using a mapping you can write:
aDict = {}
aDict[100] = fetchElement()
putElement(fetchElement(), fetchPosition(), aDict)
And the putElement
function can store item at any given position. And if you need to check if your collection contains element at given index it is more Pythonic to write:
if anIndex in aDict:
print "cool!"
Than:
if not myList[anIndex] is None:
print "cool!"
Since the latter assumes that no real element in your collection can be None
. And if that happens - your code misbehaves.
And if you desperately need performance and that's why you try to pre-initialize your variables, and write the fastest code possible - change your language. The fastest code can't be written in Python. You should try C instead and implement wrappers to call your pre-initialized and pre-compiled code from Python.
<style type="text/css">
td { word-wrap: break-word;max-width:50px; }
</style>
You must set the setOpaque(true) to true other wise the background will not be painted to the form. I think from reading that if it is not set to true that it will paint some or not any of its pixels to the form. The background is transparent by default which seems odd to me at least but in the way of programming you have to set it to true as shown below.
JLabel lb = new JLabel("Test");
lb.setBackground(Color.red);
lb.setOpaque(true); <--This line of code must be set to true or otherwise the
From the JavaDocs
setOpaque
public void setOpaque(boolean isOpaque)
If true the component paints every pixel within its bounds. Otherwise,
the component may not paint some or all of its pixels, allowing the underlying
pixels to show through.
The default value of this property is false for JComponent. However,
the default value for this property on most standard JComponent subclasses
(such as JButton and JTree) is look-and-feel dependent.
Parameters:
isOpaque - true if this component should be opaque
See Also:
isOpaque()
Yes with the help of Arrays you can initialize array list in one line,
List<String> strlist= Arrays.asList("aaa", "bbb", "ccc");
While the answer from alireza is correct, it has one gotcha:
You can't install Microsoft Visual C++ 2015 redist (runtime) unless you have Windows Update KB2999226 installed (at least on Windows 7 64-bit SP1).
If you have cloned using HTTPS (recommended) then:-
git config --global credential.helper cache
and then
git config --global credential.helper 'cache --timeout=2592000'
timeout=2592000 (30 Days in seconds) to enable caching for 30 days (or whatever suites you).
Now run a simple git command that requires your username and password.
Enter your credentials once and now caching is enabled for 30 Days.
Try again with any git command and now you don't need any credentials.
For more info :- Caching your GitHub password in Git
Note : You need Git 1.7.10 or newer to use the credential helper. On system restart, we might have to enter the password again.
Update #1:
If you are receiving this error git: 'credential-cache' is not a git command. See 'get --help'
then replace git config --global credential.helper 'cache --timeout=2592000'
with git config --global credential.helper 'store --file ~/.my-credentials'
Update #2:
If you keep getting the prompt of username and password and getting this issue:
Logon failed, use ctrl+c to cancel basic credential prompt.
Reinstalling the latest version of git worked for me.
See following snippet :
$(document).on("click", "a.deleteText", function() {_x000D_
if (confirm('Are you sure ?')) {_x000D_
$(this).prev('span.text').remove();_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div class="container">_x000D_
<span class="text">some text</span>_x000D_
<a href="#" class="deleteText"><span class="delete-icon"> x Delete </span></a>_x000D_
</div>
_x000D_
You have no combinator (space, >
, +
...) so no children will get involved, ever.
However, you could avoid the need for jQuery by using an ID
and getElementById
, or you could use the old getElementsByName("frmSave")[0]
or the even older document.forms['frmSave']
. jQuery is unnecessary here.
I recommend using boost serialization as described by other posters. Here is a good detailed tutorial on how to use it which complements the boost tutorials nicely: http://www.ocoudert.com/blog/2011/07/09/a-practical-guide-to-c-serialization/
You can just use the Select()
extension method:
IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };
IEnumerable<string> strings = integers.Select(i => i.ToString());
Or in LINQ syntax:
IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };
var strings = from i in integers
select i.ToString();
I tried everything mentioned here and in other posts. Some of the solutions that people proffered were:
There were many, many more but the one that I found to work was as follows: Close the development environment. Delete the jars used by the project from my local Maven repository. Open the IDE. Build the project. Run the test.
After hours of beating my head against my keyboard and following suggested solutions, this one worked!
The title "WPF Label Foreground Color" is very simple (exactly what I was looking for) but the OP's code is so cluttered it's easy to miss how simple it can be to set text foreground color on two different labels:
<StackPanel>
<Label Foreground="Red">Red text</Label>
<Label Foreground="Blue">Blue text</Label>
</StackPanel>
In summary, No, there was nothing wrong with your snippet.
The composer documentation states that:
After adding the autoload field, you have to re-run install to re-generate the vendor/autoload.php file.
Assuming your "src" dir resides at the same level as "vendor" dir:
the following config is absolutely correct:
{
"autoload": {
"psr-0": {"AppName": "src/"}
}
}
but you must re-update/install dependencies to make it work for you, i.e. run:
php composer.phar update
This command will get the latest versions of the dependencies and update the file "vendor/composer/autoload_namespaces.php" to match your configuration.
Also as noted by @Dom, you can use composer dump-autoload
to update the autoloader without having to go through an update.
var newTH = document.createElement('th');
newTH.onclick = function() {
//Your code here
}
For a method that works with both C and C++, you might want to consider using the standard library function strtol().
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
string s = "abcd";
char * p;
long n = strtol( s.c_str(), & p, 16 );
if ( * p != 0 ) { //my bad edit was here
cout << "not a number" << endl;
}
else {
cout << n << endl;
}
}
Pretty Diff tool was created with XML in mind. Just ensure you click the option for "markup".
Check this simple code
import java.util.ArrayList;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class FirstFrame extends JFrame{
static JComboBox<ArrayList> mycombo;
FirstFrame()
{
this.setSize(600,500);
this.setTitle("My combo");
this.setLayout(null);
ArrayList<String> names=new ArrayList<String>();
names.add("jessy");
names.add("albert");
names.add("grace");
mycombo=new JComboBox(names.toArray());
mycombo.setBounds(60,32,200,50);
this.add(mycombo);
this.setVisible(true); // window visible
}
public static void main(String[] args) {
FirstFrame frame=new FirstFrame();
}
}
Yes, it's probably dependent on various things - but I doubt it will make very much difference. I tend to opt for 16K or 32K as a good balance between memory usage and performance.
Note that you should have a try/finally block in the code to make sure the stream is closed even if an exception is thrown.
I ran into the same problem and my issue was that the DB I was trying to connect to didn't exist.
I created the DB, verified the URL/connection string and reran and everything worked as expected.
This light weight date parsing library should solve all similar problems. I like the library because it is quite easy to extend. It's also possible to i18n it (not very straight forward, but not that hard).
Parsing example:
var caseOne = Date.parseDate("Jul 8, 2005", "M d, Y");
var caseTwo = Date.parseDate("2005-07-08", "Y-m-d");
And formatting back to string (you will notice both cases give exactly the same result):
console.log( caseOne.dateFormat("M d, Y") );
console.log( caseTwo.dateFormat("M d, Y") );
console.log( caseOne.dateFormat("Y-m-d") );
console.log( caseTwo.dateFormat("Y-m-d") );
On some CPUs, there is a dedicated set of registers for the stack. When a call instruction is executed, one register is loaded with the program counter at the same time as a second register is loaded with the contents of the first, a third register is be loaded with the second, and a fourth with the third, etc. When a return instruction is executed, the program counter is latched with the contents of the first stack register and the same time as that register is latched from the second; that second register is loaded from a third, etc. Note that such hardware stacks tend to be rather small (many the smaller PIC series micros, for example, have a two-level stack).
While a hardware stack does have some advantages (push and pop don't add any time to a call/return, for example) having registers which can be loaded with two sources adds cost. If the stack gets very big, it will be cheaper to replace the push-pull registers with an addressable memory. Even if a small dedicated memory is used for this, it's cheaper to have 32 addressable registers and a 5-bit pointer register with increment/decrement logic, than it is to have 32 registers each with two inputs. If an application might need more stack than would easily fit on the CPU, it's possible to use a stack pointer along with logic to store/fetch stack data from main RAM.
One special case: a cookie has no path.
In this case set path as cookie.setPath(request.getRequestURI())
The javascript sets cookie without path so the browser shows it as cookie for the current page only. If I try to send the expired cookie with path == /
the browser shows two cookies: one expired with path == /
and another one with path == current page
.
In general, you can pass any query to mysql
from shell with -e option.
mysql -u username -p -D dbname -e "DROP DATABASE dbname"
From the javadoc
@param the sole object to be stored in the returned list.
@return an immutable list containing only the specified object.
example
import java.util.*;
public class HelloWorld {
public static void main(String args[]) {
// create an array of string objs
String initList[] = { "One", "Two", "Four", "One",};
// create one list
List list = new ArrayList(Arrays.asList(initList));
System.out.println("List value before: "+list);
// create singleton list
list = Collections.singletonList("OnlyOneElement");
list.add("five"); //throws UnsupportedOperationException
System.out.println("List value after: "+list);
}
}
Use it when code expects a read-only list, but you only want to pass one element in it. singletonList
is (thread-)safe and fast.
Named exports:
Let's say you create a file called utils.js
, with utility functions that you want to make available for other modules (e.g. a React component). Then you would make each function a named export:
export function add(x, y) {
return x + y
}
export function mutiply(x, y) {
return x * y
}
Assuming that utils.js is located in the same directory as your React component, you can use its exports like this:
import { add, multiply } from './utils.js';
...
add(2, 3) // Can be called wherever in your component, and would return 5.
Or if you prefer, place the entire module's contents under a common namespace:
import * as utils from './utils.js';
...
utils.multiply(2,3)
Default exports:
If you on the other hand have a module that only does one thing (could be a React class, a normal function, a constant, or anything else) and want to make that thing available to others, you can use a default export. Let's say we have a file log.js
, with only one function that logs out whatever argument it's called with:
export default function log(message) {
console.log(message);
}
This can now be used like this:
import log from './log.js';
...
log('test') // Would print 'test' in the console.
You don't have to call it log
when you import it, you could actually call it whatever you want:
import logToConsole from './log.js';
...
logToConsole('test') // Would also print 'test' in the console.
Combined:
A module can have both a default export (max 1), and named exports (imported either one by one, or using *
with an alias). React actually has this, consider:
import React, { Component, PropTypes } from 'react';
Press Windows + R type cmd
and Enter
In command prompt type
telnet "machine name/ip" "port number"
If port is not open, this message will display:
"Connecting To "machine name"...Could not open connection to the host, on port "port number":
Otherwise you will be take in to opened port (empty screen will display)
you can add tag without any text but with link. and when you click the button like you have in code , just run the $("yourlinkclass").click() function.
To match your sample code, you can wrap your commands inside single or double qoutes. For example
ssh blah_server "
ls
pwd
"
As per PostgreSQL documentation, https://www.postgresql.org/docs/9.6/static/functions-datetime.html
now, CURRENT_TIMESTAMP, LOCALTIMESTAMP return the time of transaction.
This is considered a feature: the intent is to allow a single transaction to have a consistent notion of the "current" time, so that multiple modifications within the same transaction bear the same time stamp.
You might want to use statement_timestamp or clock_timestamp if you don't want transaction timestamp.
statement_timestamp()
returns the start time of the current statement (more specifically, the time of receipt of the latest command message from the client). statement_timestamp
clock_timestamp()
returns the actual current time, and therefore its value changes even within a single SQL command.
Use prepopulated_fields
in your admin class:
class ArticleAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
admin.site.register(Article, ArticleAdmin)
Model.select(:rating)
The result of this is a collection of Model
objects. Not plain ratings. And from uniq
's point of view, they are completely different. You can use this:
Model.select(:rating).map(&:rating).uniq
or this (most efficient):
Model.uniq.pluck(:rating)
Model.distinct.pluck(:rating)
Apparently, as of rails 5.0.0.1, it works only on "top level" queries, like above. Doesn't work on collection proxies ("has_many" relations, for example).
Address.distinct.pluck(:city) # => ['Moscow']
user.addresses.distinct.pluck(:city) # => ['Moscow', 'Moscow', 'Moscow']
In this case, deduplicate after the query
user.addresses.pluck(:city).uniq # => ['Moscow']
To check a remote SSH server prior to the first connection, you can give a look at www.server-stats.net/ssh/ to see all SHH keys for the server, as well as from when the key is known.
That's not like an SSL certificate, but definitely a must-do before connecting to any SSH server for the first time.
You can use the upper() function in your query, and to increase performance you can use a function-base index
CREATE INDEX upper_index_name ON table(upper(name))
You're probably looking for something like this:
// original_x000D_
var arr = [ _x000D_
{key : '11', value : '1100', $$hashKey : '00X' },_x000D_
{key : '22', value : '2200', $$hashKey : '018' }_x000D_
];_x000D_
_x000D_
//convert_x000D_
var result = {};_x000D_
for (var i = 0; i < arr.length; i++) {_x000D_
result[arr[i].key] = arr[i].value;_x000D_
}_x000D_
_x000D_
console.log(result);
_x000D_
To make it fixed: Try this way,
jsFiddleLink: http://jsfiddle.net/PERtY/
<div class="body">This is a sample body This is a sample body
This is a sample body
This is a sample body
This is a sample body
This is a sample body
This is a sample body
This is a sample bodyThis is a sample bodyThis is a sample body
This is a sample body
This is a sample body
This is a sample body
This is a sample body
This is a sample body
This is a sample body
This is a sample body
v
This is a sample body
This is a sample body
This is a sample body
This is a sample body
This is a sample body
This is a sample body
<div class="watermark">
Sample Watermark
</div>
This is a sample body
This is a sample bodyThis is a sample bodyThis is a sample body
</div>
.watermark {
opacity: 0.5;
color: BLACK;
position: fixed;
top: auto;
left: 80%;
}
To use absolute:
.watermark {
opacity: 0.5;
color: BLACK;
position: absolute;
bottom: 0;
right: 0;
}
jsFiddle: http://jsfiddle.net/6YSXC/
Try setting a Windows System Environment variable called _JAVA_OPTIONS
with the heap size you want. Java should be able to find it and act accordingly.
Numeric precision refers to the maximum number of digits that are present in the number.
ie 1234567.89 has a precision of 9
Numeric scale refers to the maximum number of decimal places
ie 123456.789 has a scale of 3
Thus the maximum allowed value for decimal(5,2) is 999.99
The only true way to keep these private is to keep them on your server, and have the app send whatever it is to the server, and the server interacts with Dropbox. That way you NEVER distribute your private key in any format.
The request body is available as byte stream by HttpServletRequest#getInputStream()
:
InputStream body = request.getInputStream();
// ...
Or as character stream by HttpServletRequest#getReader()
:
Reader body = request.getReader();
// ...
Note that you can read it only once. The client ain't going to resend the same request multiple times. Calling getParameter()
and so on will implicitly also read it. If you need to break down parameters later on, you've got to store the body somewhere and process yourself.
Yes, that's possible - you can use INSERT ... ON DUPLICATE KEY UPDATE.
Using your example:
INSERT INTO table (id,Col1,Col2) VALUES (1,1,1),(2,2,3),(3,9,3),(4,10,12)
ON DUPLICATE KEY UPDATE Col1=VALUES(Col1),Col2=VALUES(Col2);
I prefer using a top-level namespace for the application and sub namespaces for the components.
The way you can use classes from other namespaces is surprisingly very similar to the way in java. You can either use "use NAMESPACE" which is similar to an "import PACKAGE" statement, e.g. use std. Or you specify the package as prefix of the class separated with "::", e.g. std::string. This is similar to "java.lang.String" in Java.
Set a negative z-index
for the child, and remove the one set on the parent.
.parent {_x000D_
position: relative;_x000D_
width: 350px;_x000D_
height: 150px;_x000D_
background: red;_x000D_
border: solid 1px #000;_x000D_
}_x000D_
.parent2 {_x000D_
position: relative;_x000D_
width: 350px;_x000D_
height: 40px;_x000D_
background: red;_x000D_
border: solid 1px #000;_x000D_
}_x000D_
.child {_x000D_
position: relative;_x000D_
background-color: blue;_x000D_
height: 200px;_x000D_
}_x000D_
.wrapper {_x000D_
position: relative;_x000D_
background: green;_x000D_
height: 350px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="parent">parent 1 parent 1_x000D_
<div class="child">child child child</div>_x000D_
</div>_x000D_
<div class="parent2">parent 2 parent 2_x000D_
</div>_x000D_
</div>
_x000D_
Use the SQLite keyword default
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " ("
+ KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_NAME + " TEXT NOT NULL, "
+ KEY_WORKED + " INTEGER, "
+ KEY_NOTE + " INTEGER DEFAULT 0);");
This link is useful: http://www.sqlite.org/lang_createtable.html
JS does not have a sleep function, it has setTimeout() or setInterval() functions.
If you can move the code that you need to run after the pause into the setTimeout()
callback, you can do something like this:
//code before the pause
setTimeout(function(){
//do what you need here
}, 2000);
see example here : http://jsfiddle.net/9LZQp/
This won't halt the execution of your script, but due to the fact that setTimeout()
is an asynchronous function, this code
console.log("HELLO");
setTimeout(function(){
console.log("THIS IS");
}, 2000);
console.log("DOG");
will print this in the console:
HELLO
DOG
THIS IS
(note that DOG is printed before THIS IS)
You can use the following code to simulate a sleep for short periods of time:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
now, if you want to sleep for 1 second, just use:
sleep(1000);
example: http://jsfiddle.net/HrJku/1/
please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.
I created a framework using Swift3/Xcode 8.1 and was consuming it in an Objective-C/Xcode 8.1 project. To fix this issue I had to enable Always Embed Swift Standard Libraries
option under Build Options
.
Have a look at this screenshot:
just use a Button with android:drawableRight properties like this:
<Button android:id="@+id/btnNovaCompra" android:layout_width="wrap_content"
android:text="@string/btn_novaCompra"
android:gravity="center"
android:drawableRight="@drawable/shoppingcart"
android:layout_height="wrap_content"/>
This original answer I wrote is a myth from the folklore of computing: debunked by Dennis Ritchie as "historically impossible" as noted in the letters to the editors of Communications of the ACM July 2012 doi:10.1145/2209249.2209251
The C increment/decrement operators were invented at a time when the C compiler wasn't very smart and the authors wanted to be able to specify the direct intent that a machine language operator should be used which saved a handful of cycles for a compiler which might do a
load memory
load 1
add
store memory
instead of
inc memory
and the PDP-11 even supported "autoincrement" and "autoincrement deferred" instructions corresponding to *++p
and *p++
, respectively. See section 5.3 of the manual if horribly curious.
As compilers are smart enough to handle the high-level optimization tricks built into the syntax of C, they are just a syntactic convenience now.
Python doesn't have tricks to convey intentions to the assembler because it doesn't use one.
There's no need to wait for input before closing, just change your command like so:
cmd /K python <script>
The /K
switch will execute the command that follows, but leave the command interpreter window open, in contrast to /C
, which executes and then closes.
Use TCPView if you want a GUI for this. It's the old Sysinternals application that Microsoft bought out.
Using SQL connection via Windows Authentication: A "Kerberos double hop" is happening: one hop is your client application connecting to the SQL Server, a second hop is the SQL Server connecting to the remote "\\NETWORK_MACHINE\". Such a double hop falls under the restrictions of Constrained Delegation and you end up accessing the share as Anonymous Login and hence the Access Denied.
To resolve the issue you need to enable constrained delegation for the SQL Server service account. See here for a good post that explains it quite well
SQL Server using SQL Authentication You need to create a credential for your SQL login and use that to access that particular network resource. See here
With marquee
tag.
HTML
<marquee behavior="scroll" bgcolor="yellow" loop="-1" width="30%">
<i>
<font color="blue">
Today's date is :
<strong>
<span id="time"></span>
</strong>
</font>
</i>
</marquee>
JS
var today = new Date();
document.getElementById('time').innerHTML=today;
Without marquee
tag and with CSS
.
HTML
<p class="marquee">
<span id="dtText"></span>
</p>
CSS
.marquee {
width: 350px;
margin: 0 auto;
background:yellow;
white-space: nowrap;
overflow: hidden;
box-sizing: border-box;
color:blue;
font-size:18px;
}
.marquee span {
display: inline-block;
padding-left: 100%;
text-indent: 0;
animation: marquee 15s linear infinite;
}
.marquee span:hover {
animation-play-state: paused
}
@keyframes marquee {
0% { transform: translate(0, 0); }
100% { transform: translate(-100%, 0); }
}
JS
var today = new Date();
document.getElementById('dtText').innerHTML=today;
The for if (something)
and if (!something)
is commonly used to check if something is defined or not defined. For example:
if (document.getElementById)
The identifier is converted to a boolean value, so undefined
is interpreted as false
. There are of course other values (like 0 and '') that also are interpreted as false
, but either the identifier should not reasonably have such a value or you are happy with treating such a value the same as undefined.
Javascript has a delete
operator that can be used to delete a member of an object. Depending on the scope of a variable (i.e. if it's global or not) you can delete it to make it undefined.
There is no undefined
keyword that you can use as an undefined literal. You can omit parameters in a function call to make them undefined, but that can only be used by sending less paramters to the function, you can't omit a parameter in the middle.
I've used a simple technique that works nicely for small cases with no special tags and no additional context. Sometimes this comes in handy
{% for i in '0123456789'|make_list %}
{{ forloop.counter }}
{% endfor %}
SELECT ...
SELECT SLEEP(5);
SELECT ...
But what are you using this for? Are you trying to circumvent/reinvent mutexes or transactions?
what is the way to retrieve a Date object so that its always in GMT?
Instant.now()
You are using troublesome confusing old date-time classes that are now supplanted by the java.time classes.
Instant
= UTCThe Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now() ; // Current moment in UTC.
To exchange this data as text, use the standard ISO 8601 formats exclusively. These formats are sensibly designed to be unambiguous, easy to process by machine, and easy to read across many cultures by people.
The java.time classes use the standard formats by default when parsing and generating strings.
String output = instant.toString() ;
2017-01-23T12:34:56.123456789Z
If you want to see that same moment as presented in the wall-clock time of a particular region, apply a ZoneId
to get a ZonedDateTime
.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-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( "Asia/Singapore" ) ;
ZonedDateTime zdt = instant.atZone( z ) ; // Same simultaneous moment, same point on the timeline.
See this code live at IdeOne.com.
Notice the eight hour difference, as the time zone of Asia/Singapore
currently has an offset-from-UTC of +08:00. Same moment, different wall-clock time.
instant.toString(): 2017-01-23T12:34:56.123456789Z
zdt.toString(): 2017-01-23T20:34:56.123456789+08:00[Asia/Singapore]
Avoid the legacy java.util.Date
class. But if you must, you can convert. Look to new methods added to the old classes.
java.util.Date date = Date.from( instant ) ;
…going the other way…
Instant instant = myJavaUtilDate.toInstant() ;
For date-only, use LocalDate
.
LocalDate ld = zdt.toLocalDate() ;
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
If you want a more robust solution with ShellExecute that will open ANY file, folder or URL using the default OS associated program to do so, here is a function taken from http://access.mvps.org/access/api/api0018.htm:
'************ Code Start **********
' This code was originally written by Dev Ashish.
' It is not to be altered or distributed,
' except as part of an application.
' You are free to use it in any application,
' provided the copyright notice is left unchanged.
'
' Code Courtesy of
' Dev Ashish
'
Private Declare Function apiShellExecute Lib "shell32.dll" _
Alias "ShellExecuteA" _
(ByVal hwnd As Long, _
ByVal lpOperation As String, _
ByVal lpFile As String, _
ByVal lpParameters As String, _
ByVal lpDirectory As String, _
ByVal nShowCmd As Long) _
As Long
'***App Window Constants***
Public Const WIN_NORMAL = 1 'Open Normal
Public Const WIN_MAX = 3 'Open Maximized
Public Const WIN_MIN = 2 'Open Minimized
'***Error Codes***
Private Const ERROR_SUCCESS = 32&
Private Const ERROR_NO_ASSOC = 31&
Private Const ERROR_OUT_OF_MEM = 0&
Private Const ERROR_FILE_NOT_FOUND = 2&
Private Const ERROR_PATH_NOT_FOUND = 3&
Private Const ERROR_BAD_FORMAT = 11&
'***************Usage Examples***********************
'Open a folder: ?fHandleFile("C:\TEMP\",WIN_NORMAL)
'Call Email app: ?fHandleFile("mailto:[email protected]",WIN_NORMAL)
'Open URL: ?fHandleFile("http://home.att.net/~dashish", WIN_NORMAL)
'Handle Unknown extensions (call Open With Dialog):
' ?fHandleFile("C:\TEMP\TestThis",Win_Normal)
'Start Access instance:
' ?fHandleFile("I:\mdbs\CodeNStuff.mdb", Win_NORMAL)
'****************************************************
Function fHandleFile(stFile As String, lShowHow As Long)
Dim lRet As Long, varTaskID As Variant
Dim stRet As String
'First try ShellExecute
lRet = apiShellExecute(hWndAccessApp, vbNullString, _
stFile, vbNullString, vbNullString, lShowHow)
If lRet > ERROR_SUCCESS Then
stRet = vbNullString
lRet = -1
Else
Select Case lRet
Case ERROR_NO_ASSOC:
'Try the OpenWith dialog
varTaskID = Shell("rundll32.exe shell32.dll,OpenAs_RunDLL " _
& stFile, WIN_NORMAL)
lRet = (varTaskID <> 0)
Case ERROR_OUT_OF_MEM:
stRet = "Error: Out of Memory/Resources. Couldn't Execute!"
Case ERROR_FILE_NOT_FOUND:
stRet = "Error: File not found. Couldn't Execute!"
Case ERROR_PATH_NOT_FOUND:
stRet = "Error: Path not found. Couldn't Execute!"
Case ERROR_BAD_FORMAT:
stRet = "Error: Bad File Format. Couldn't Execute!"
Case Else:
End Select
End If
fHandleFile = lRet & _
IIf(stRet = "", vbNullString, ", " & stRet)
End Function
'************ Code End **********
Just put this into a separate module and call fHandleFile() with the right parameters.
and with --outdated as an extra argument, you will get the Current and Latest versions of the packages you are using :
$ pip list --outdated
distribute (Current: 0.6.34 Latest: 0.7.3)
django-bootstrap3 (Current: 1.1.0 Latest: 4.3.0)
Django (Current: 1.5.4 Latest: 1.6.4)
Jinja2 (Current: 2.6 Latest: 2.8)
So combining with AdamKG 's answer :
$ pip list --outdated | grep Jinja2
Jinja2 (Current: 2.6 Latest: 2.8)
Check pip-tools too : https://github.com/nvie/pip-tools
Just use this css method:
body{
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
You can find the same answer here: How to disable text selection highlighting using CSS?
For ubuntu users, this error may arise because setuptool is not installed system-wide. Simply install setuptool using the command:
sudo apt-get install -y python-setuptools
For python3:
sudo apt-get install -y python3-setuptools
After that, install your package again normally, using
sudo python setup.py install
That's all.
//Inside the folder,
svn cleanup
svn update
//If are viewing any conflicts,
svn revert --depth infinity conflicted_filename
svn update conflicted_filename
svn update
1)row level trigger is used to perform action on set of rows as insert , update or delete
example:-you have to delete a set of rows and simultaneously that deleted rows must also inserted in new table for audit purpose;
2)statement level trigger:- it generally used to imposed restriction on the event you are performing.
example:- restriction to delete the data between 10 pm and 6 am;
hope this helps:)
To store DataTable
in Session:
DataTable dtTest = new DataTable();
Session["dtTest"] = dtTest;
To retrieve DataTable
from Session:
DataTable dt = (DataTable) Session["dtTest"];
The Algorithm for given flow chart :
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Step :01
Step :02 [Variable initialization]
Step :03[Condition Check]
Step:04
My hard drive in my Mac was making beeping noises in the middle of a project so I decided to install a SSD. I needed to move my project from one disk to another. A few things to consider:
This is what worked for me:
1.) Copy your ~/.vagrant.d directory to your new machine.
2.) Copy your ~/VirtualBox\ VMs directory to your new machine.
3.) In VirtualBox add the machines one by one using **Machine** >> **Add**
4.) Run `vagrant box list` to see if vagrant acknowledges your machines.
5.) `git clone my_project`
6.) `vagrant up`
I had a few problems with VB Guest additions.
I fixed them with this solution.
The ??
operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.
int? variable1 = null;
int variable2 = variable1 ?? 100;
Set variable2
to the value of variable1
, if variable1
is NOT null;
otherwise, if variable1 == null
, set variable2
to 100.
** Finally!!! Resolved App transport Security **
1. Follow the follow the screen shot. Do it in Targets info Section.
Using ES6 the javascript becomes a little cleaner
handleFiles(input) {
const file = input.target.files[0];
const reader = new FileReader();
reader.onload = (event) => {
const file = event.target.result;
const allLines = file.split(/\r\n|\n/);
// Reading line by line
allLines.forEach((line) => {
console.log(line);
});
};
reader.onerror = (event) => {
alert(event.target.error.name);
};
reader.readAsText(file);
}
int myNumber = 8383;
char firstDigit = myNumber.ToString()[0];
// char = '8'
I ran into this problem, however while running the command:
Install-Package -IncludePrerelease Microsoft.AspNet.Web.Optimization
I received the cryptic message (gotta love a great pun before the first cup of coffee):
Install-Package : The specified cryptographic algorithm is not supported on this platform.
I am running this on Windows XP SP3 (not by choice) and what I found was that I had to follow the instructions posted by the user artsnob on the ASP.NET Forum
Once I ran this I could then run the command line to update the Web.Optimization.
Hope this saves someone some digging.
Following is the list of conversion characters that you may use in the printf:
%d – for signed decimal integer
%f – for the floating point
%o – octal number
%c – for a character
%s – a string
%i – use for integer base 10
%u – for unsigned decimal number
%x – hexadecimal number
%% – for writing % (percentage)
%n – for new line = \n
I ran into this same issue, but I think I know what's causing the confusion. If you use MySql Query Analyzer, you can do this just fine:
SELECT myvalue
INTO @myvar
FROM mytable
WHERE anothervalue = 1;
However, if you put that same query in MySql Workbench, it will throw a syntax error. I don't know why they would be different, but they are. To work around the problem in MySql Workbench, you can rewrite the query like this:
SELECT @myvar:=myvalue
FROM mytable
WHERE anothervalue = 1;
Use !(window.ActiveXObject) && "ActiveXObject" in window
to detect IE11 explicitly.
To detect any IE (pre-Edge, "Trident") version, use "ActiveXObject" in window
instead.
I've used git rev-list
for this sort of thing. For example, (note the 3 dots)
$ git rev-list --boundary branch-a...master | grep "^-" | cut -c2-
will spit out the branch point. Now, it's not perfect; since you've merged master into branch A a couple of times, that'll split out a couple possible branch points (basically, the original branch point and then each point at which you merged master into branch A). However, it should at least narrow down the possibilities.
I've added that command to my aliases in ~/.gitconfig
as:
[alias]
diverges = !sh -c 'git rev-list --boundary $1...$2 | grep "^-" | cut -c2-'
so I can call it as:
$ git diverges branch-a master
Definitely use Pyglet for this. It's kind of a large package, but it is pure python with no extension modules. That will definitely be the easiest for deployment. It's also got great format and codec support.
import pyglet
music = pyglet.resource.media('music.mp3')
music.play()
pyglet.app.run()
PHP 5 >= 5.5.0, PHP 7
Use array_column on the result array
$column = array_column($result, 'names');
Be careful of a global temp table solution as this may fail if two users use the same routine at the same time as a global temp table can be seen by all users...
Both the annotations behave exactly in same manner.
Only 2 special characters '!' and '@' are accepted by the annotations @PathVariable and @RequestParam.
To check and confirm the behavior I have created a spring boot application that contains only 1 controller.
@RestController
public class Controller
{
@GetMapping("/pvar/{pdata}")
public @ResponseBody String testPathVariable(@PathVariable(name="pdata") String pathdata)
{
return pathdata;
}
@GetMapping("/rpvar")
public @ResponseBody String testRequestParam(@RequestParam("param") String paramdata)
{
return paramdata;
}
}
Hitting following Requests I got the same response:
!@ was received as response in both the requests
Changing compile 'com.android.support:appcompat-v7:21.0.0'
into compile 'com.android.support:appcompat-v7:20.0.0'
in gradle.build works for me.
EDIT (02 Jan 2012):
I created a small open source Android Library Project that streamlines this process, while also providing a built-in file explorer (in case the user does not have one present). It's extremely simple to use, requiring only a few lines of code.
You can find it at GitHub: aFileChooser.
ORIGINAL
If you want the user to be able to choose any file in the system, you will need to include your own file manager, or advise the user to download one. I believe the best you can do is look for "openable" content in an Intent.createChooser()
like this:
private static final int FILE_SELECT_CODE = 0;
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
You would then listen for the selected file's Uri
in onActivityResult()
like so:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
Log.d(TAG, "File Uri: " + uri.toString());
// Get the path
String path = FileUtils.getPath(this, uri);
Log.d(TAG, "File Path: " + path);
// Get the file instance
// File file = new File(path);
// Initiate the upload
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
The getPath()
method in my FileUtils.java
is:
public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = { "_data" };
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
}
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
Of-course this is an old thread but to make it complete.
From SQL 2008 you can use DATE datatype so you can simply do:
SELECT CONVERT(DATE,GETDATE())
Only "keyboard focusable" elements can be focused with .focus()
. div
aren't meant to be natively focusable. You have to add tabindex="0"
attributes to it to achieve that. input
, button
, a
etc... are natively focusable.
My problem was caused by having external ip in $ZBX_SERVER setting.
I changed it to localhost instead so that ip was resolved internally,
$sudo nano /etc/zabbix/web/zabbix.conf.php
Changed
$ZBX_SERVER = 'external ip was written here';
to
$ZBX_SERVER = 'localhost';
then
$sudo service zabbix-server restart
Zabbix 3.4 on Ubuntu 14.04.3 LTS
Simply pass the inspector flag and you'll be provided with a URL to the inspector:
node --inspect server.js
You can also break on the first line by passing --inspect-brk
instead.
The solution is much too big. Try this simple one. Please provide a 7+ character buffer, no check made.
char *i2str(int i, char *buf){
byte l=0;
if(i<0) buf[l++]='-';
boolean leadingZ=true;
for(int div=10000, mod=0; div>0; div/=10){
mod=i%div;
i/=div;
if(!leadingZ || i!=0){
leadingZ=false;
buf[l++]=i+'0';
}
i=mod;
}
buf[l]=0;
return buf;
}
Can be easily modified to give back end of buffer, if you discard index 'l' and increment the buffer directly.
You can try to use Prettyfox UI library http://ng.prettyfox.org
This library use bootstrap 4 styles and not need jquery.
I found this explanation from the Hibernate docs enlightening, because they contain a use case:
The usage and semantics of merge() seems to be confusing for new users. Firstly, as long as you are not trying to use object state loaded in one entity manager in another new entity manager, you should not need to use merge() at all. Some whole applications will never use this method.
Usually merge() is used in the following scenario:
- The application loads an object in the first entity manager
- the object is passed up to the presentation layer
- some modifications are made to the object
- the object is passed back down to the business logic layer
- the application persists these modifications by calling merge() in a second entity manager
Here is the exact semantic of merge():
- if there is a managed instance with the same identifier currently associated with the persistence context, copy the state of the given object onto the managed instance
- if there is no managed instance currently associated with the persistence context, try to load it from the database, or create a new managed instance
- the managed instance is returned
- the given instance does not become associated with the persistence context, it remains detached and is usually discarded
From: http://docs.jboss.org/hibernate/entitymanager/3.6/reference/en/html/objectstate.html
Similar to what Richard Detsch but with a bit easier to follow (works with packages as well)
Step 1: Unwrap the War file.
jar -xvf MyWar.war
Step 2: move into the directory
cd WEB-INF
Step 3: Run your main with all dependendecies
java -classpath "lib/*:classes/." my.packages.destination.FileToRun
When you use the url tag you should use quotes for string literals, for example:
{% url 'products' %}
At the moment product
is treated like a variable and evaluates to ''
in the error message.
I do this using associative arrays since bash 4 and setting IFS
to a value that can be defined manually.
The purpose of this approach is to have arrays as values of associative array keys.
In order to set IFS back to default just unset it.
unset IFS
This is an example:
#!/bin/bash
set -euo pipefail
# used as value in asscciative array
test=(
"x3:x4:x5"
)
# associative array
declare -A wow=(
["1"]=$test
["2"]=$test
)
echo "default IFS"
for w in ${wow[@]}; do
echo " $w"
done
IFS=:
echo "IFS=:"
for w in ${wow[@]}; do
for t in $w; do
echo " $t"
done
done
echo -e "\n or\n"
for w in ${!wow[@]}
do
echo " $w"
for t in ${wow[$w]}
do
echo " $t"
done
done
unset IFS
unset w
unset t
unset wow
unset test
The output of the script below is:
default IFS
x3:x4:x5
x3:x4:x5
IFS=:
x3
x4
x5
x3
x4
x5
or
1
x3
x4
x5
2
x3
x4
x5
When PowerShell sees a command starting with a string it just evaluates the string, that is, it typically echos it to the screen, for example:
PS> "Hello World"
Hello World
If you want PowerShell to interpret the string as a command name then use the call operator (&) like so:
PS> & 'C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe'
After that you probably only need to quote parameter/argument pairs that contain spaces and/or quotation chars. When you invoke an EXE file like this with complex command line arguments it is usually very helpful to have a tool that will show you how PowerShell sends the arguments to the EXE file. The PowerShell Community Extensions has such a tool. It is called echoargs. You just replace the EXE file with echoargs - leaving all the arguments in place, and it will show you how the EXE file will receive the arguments, for example:
PS> echoargs -verb:sync -source:dbfullsql="Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;" -dest:dbfullsql="Data Source=.\mydestsource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;",computername=10.10.10.10,username=administrator,password=adminpass
Arg 0 is <-verb:sync>
Arg 1 is <-source:dbfullsql=Data>
Arg 2 is <Source=mysource;Integrated>
Arg 3 is <Security=false;User>
Arg 4 is <ID=sa;Pwd=sapass!;Database=mydb;>
Arg 5 is <-dest:dbfullsql=Data>
Arg 6 is <Source=.\mydestsource;Integrated>
Arg 7 is <Security=false;User>
Arg 8 is <ID=sa;Pwd=sapass!;Database=mydb; computername=10.10.10.10 username=administrator password=adminpass>
Using echoargs you can experiment until you get it right, for example:
PS> echoargs -verb:sync "-source:dbfullsql=Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;"
Arg 0 is <-verb:sync>
Arg 1 is <-source:dbfullsql=Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;>
It turns out I was trying too hard before to maintain the double quotes around the connection string. Apparently that isn't necessary because even cmd.exe will strip those out.
BTW, hats off to the PowerShell team. They were quite helpful in showing me the specific incantation of single & double quotes to get the desired result - if you needed to keep the internal double quotes in place. :-) They also realize this is an area of pain, but they are driven by the number of folks are affected by a particular issue. If this is an area of pain for you, then please vote up this PowerShell bug submission.
For more information on how PowerShell parses, check out my Effective PowerShell blog series - specifically item 10 - "Understanding PowerShell Parsing Modes"
UPDATE 4/4/2012: This situation gets much easier to handle in PowerShell V3. See this blog post for details.
How about something like this?
<html>
<head>
<script type="text/javascript">
var HoverListener = {
addElem: function( elem, callback, delay )
{
if ( delay === undefined )
{
delay = 1000;
}
var hoverTimer;
addEvent( elem, 'mouseover', function()
{
hoverTimer = setTimeout( callback, delay );
} );
addEvent( elem, 'mouseout', function()
{
clearTimeout( hoverTimer );
} );
}
}
function tester()
{
alert( 'hi' );
}
// Generic event abstractor
function addEvent( obj, evt, fn )
{
if ( 'undefined' != typeof obj.addEventListener )
{
obj.addEventListener( evt, fn, false );
}
else if ( 'undefined' != typeof obj.attachEvent )
{
obj.attachEvent( "on" + evt, fn );
}
}
addEvent( window, 'load', function()
{
HoverListener.addElem(
document.getElementById( 'test' )
, tester
);
HoverListener.addElem(
document.getElementById( 'test2' )
, function()
{
alert( 'Hello World!' );
}
, 2300
);
} );
</script>
</head>
<body>
<div id="test">Will alert "hi" on hover after one second</div>
<div id="test2">Will alert "Hello World!" on hover 2.3 seconds</div>
</body>
</html>
If you want to rank just one person you can do the following:
SELECT COUNT(Age) + 1
FROM PERSON
WHERE(Age < age_to_rank)
This ranking corresponds to the oracle RANK function (Where if you have people with the same age they get the same rank, and the ranking after that is non-consecutive).
It's a little bit faster than using one of the above solutions in a subquery and selecting from that to get the ranking of one person.
This can be used to rank everyone but it's slower than the above solutions.
SELECT
Age AS age_var,
(
SELECT COUNT(Age) + 1
FROM Person
WHERE (Age < age_var)
) AS rank
FROM Person
What good will it do to override static methods. You cannot call static methods through an instance.
MyClass.static1()
MySubClass.static1() // If you overrode, you have to call it through MySubClass anyway.
EDIT : It appears that through an unfortunate oversight in language design, you can call static methods through an instance. Generally nobody does that. My bad.
psql
's inline help:
\h ALTER TABLE
Also documented in the postgres docs (an excellent resource, plus easy to read, too).
ALTER TABLE tablename ADD CONSTRAINT constraintname UNIQUE (columns);
In core-site.xml:
<configuration>
<property>
<name>fs.defaultFS</name>
<value>hdfs://localhost:9000</value>
</property>
<property>
<name>hadoop.tmp.dir</name>
<value>/home/yourusername/hadoop/tmp/hadoop-${user.name}
</value>
</property>
</configuration>
and format of namenode with :
hdfs namenode -format
worked for hadoop 2.8.1