Even without looking at assembly, the most obvious reason is that /= 2
is probably optimized as >>=1
and many processors have a very quick shift operation. But even if a processor doesn't have a shift operation, the integer division is faster than floating point division.
Edit: your milage may vary on the "integer division is faster than floating point division" statement above. The comments below reveal that the modern processors have prioritized optimizing fp division over integer division. So if someone were looking for the most likely reason for the speedup which this thread's question asks about, then compiler optimizing /=2
as >>=1
would be the best 1st place to look.
On an unrelated note, if n
is odd, the expression n*3+1
will always be even. So there is no need to check. You can change that branch to
{
n = (n*3+1) >> 1;
count += 2;
}
So the whole statement would then be
if (n & 1)
{
n = (n*3 + 1) >> 1;
count += 2;
}
else
{
n >>= 1;
++count;
}
Note that in order to create a so called "feature module", you need to import CommonModule
inside it. So, your module initialization code will look like this:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TaskCardComponent } from './task-card/task-card.component';
import { MdCardModule } from '@angular2-material/card';
@NgModule({
imports: [
CommonModule,
MdCardModule
],
declarations: [
TaskCardComponent
],
exports: [
TaskCardComponent
]
})
export class TaskModule { }
More information available here: https://angular.io/guide/ngmodule#create-the-feature-module
The lookup module of ansible works fine for me. The yml is:
- hosts: test
vars:
time: "{{ lookup('pipe', 'date -d \"1 day ago\" +\"%Y%m%d\"') }}"
You can replace any command with date to get result of the command.
Use FileSaver.js
. It supports Chrome, Edge, Firefox, and IE 10+ (and probably IE < 10 with a few "polyfills" - see Note 4). FileSaver.js
implements the saveAs() FileSaver interface in browsers that do not natively support it:
https://github.com/eligrey/FileSaver.js
Minified version is really small at < 2.5KB, gzipped < 1.2KB.
Usage:
/* TODO: replace the blob content with your byte[] */
var blob = new Blob([yourBinaryDataAsAnArrayOrAsAString], {type: "application/octet-stream"});
var fileName = "myFileName.myExtension";
saveAs(blob, fileName);
You might need Blob.js in some browsers (see Note 3). Blob.js implements the W3C Blob interface in browsers that do not natively support it. It is a cross-browser implementation:
https://github.com/eligrey/Blob.js
Consider StreamSaver.js if you have files larger than blob's size limitations.
Complete example:
/* Two options_x000D_
* 1. Get FileSaver.js from here_x000D_
* https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.min.js -->_x000D_
* <script src="FileSaver.min.js" />_x000D_
*_x000D_
* Or_x000D_
*_x000D_
* 2. If you want to support only modern browsers like Chrome, Edge, Firefox, etc., _x000D_
* then a simple implementation of saveAs function can be:_x000D_
*/_x000D_
function saveAs(blob, fileName) {_x000D_
var url = window.URL.createObjectURL(blob);_x000D_
_x000D_
var anchorElem = document.createElement("a");_x000D_
anchorElem.style = "display: none";_x000D_
anchorElem.href = url;_x000D_
anchorElem.download = fileName;_x000D_
_x000D_
document.body.appendChild(anchorElem);_x000D_
anchorElem.click();_x000D_
_x000D_
document.body.removeChild(anchorElem);_x000D_
_x000D_
// On Edge, revokeObjectURL should be called only after_x000D_
// a.click() has completed, atleast on EdgeHTML 15.15048_x000D_
setTimeout(function() {_x000D_
window.URL.revokeObjectURL(url);_x000D_
}, 1000);_x000D_
}_x000D_
_x000D_
(function() {_x000D_
// convert base64 string to byte array_x000D_
var byteCharacters = atob("R0lGODlhkwBYAPcAAAAAAAABGRMAAxUAFQAAJwAANAgwJSUAACQfDzIoFSMoLQIAQAAcQwAEYAAHfAARYwEQfhkPfxwXfQA9aigTezchdABBckAaAFwpAUIZflAre3pGHFpWVFBIf1ZbYWNcXGdnYnl3dAQXhwAXowkgigIllgIxnhkjhxktkRo4mwYzrC0Tgi4tiSQzpwBIkBJIsyxCmylQtDVivglSxBZu0SlYwS9vzDp94EcUg0wziWY0iFROlElcqkxrtW5OjWlKo31kmXp9hG9xrkty0ziG2jqQ42qek3CPqn6Qvk6I2FOZ41qn7mWNz2qZzGaV1nGOzHWY1Gqp3Wy93XOkx3W1x3i33G6z73nD+ZZIHL14KLB4N4FyWOsECesJFu0VCewUGvALCvACEfEcDfAcEusKJuoINuwYIuoXN+4jFPEjCvAgEPM3CfI5GfAxKuoRR+oaYustTus2cPRLE/NFJ/RMO/dfJ/VXNPVkNvFPTu5KcfdmQ/VuVvl5SPd4V/Nub4hVj49ol5RxoqZfl6x0mKp5q8Z+pu5NhuxXiu1YlvBdk/BZpu5pmvBsjfBilvR/jvF3lO5nq+1yre98ufBoqvBrtfB6p/B+uPF2yJiEc9aQMsSKQOibUvqKSPmEWPyfVfiQaOqkSfaqTfyhXvqwU+u7dfykZvqkdv+/bfy1fpGvvbiFnL+fjLGJqqekuYmTx4SqzJ2+2Yy36rGawrSwzpjG3YjB6ojG9YrU/5XI853U75bV/J3l/6PB6aDU76TZ+LHH6LHX7rDd+7Lh3KPl/bTo/bry/MGJm82VqsmkjtSptfWMj/KLsfu0je6vsNW1x/GIxPKXx/KX1ea8w/Wnx/Oo1/a3yPW42/S45fvFiv3IlP/anvzLp/fGu/3Xo/zZt//knP7iqP7qt//xpf/0uMTE3MPd1NXI3MXL5crS6cfe99fV6cXp/cj5/tbq+9j5/vbQy+bY5/bH6vbJ8vfV6ffY+f7px/3n2f/4yP742OPm8ef9//zp5vjn/f775/7+/gAAACwAAAAAkwBYAAAI/wD9CRxIsKDBgwgTKlzIsKHDhxAjSpxIsaLFixgzatzIsaPHjxD7YQrSyp09TCFSrQrxCqTLlzD9bUAAAMADfVkYwCIFoErMn0AvnlpAxR82A+tGWWgnLoCvoFCjOsxEopzRAUYwBFCQgEAvqWDDFgTVQJhRAVI2TUj3LUAusXDB4jsQxZ8WAMNCrW37NK7foN4u1HThD0sBWpoANPnL+GG/OV2gSUT24Yi/eltAcPAAooO+xqAVbkPT5VDo0zGzfemyqLE3a6hhmurSpRLjcGDI0ItdsROXSAn5dCGzTOC+d8j3gbzX5ky8g+BoTzq4706XL1/KzONdEBWXL3AS3v/5YubavU9fuKg/44jfQmbK4hdn+Jj2/ILRv0wv+MnLdezpweEed/i0YcYXkCQkB3h+tPEfgF3AsdtBzLSxGm1ftCHJQqhc54Y8B9UzxheJ8NfFgWakSF6EA57WTDN9kPdFJS+2ONAaKq6Whx88enFgeAYx892FJ66GyEHvvGggeMs0M01B9ajRRYkD1WMgF60JpAx5ZEgGWjZ44MHFdSkeSBsceIAoED5gqFgGbAMxQx4XlxjESRdcnFENcmmcGBlBfuDh4Ikq0kYGHoxUKSWVApmCnRsFCddlaEPSVuaFED7pDz5F5nGQJ9cJWFA/d1hSUCfYlSFQfdgRaqal6UH/epmUjRDUx3VHEtTPHp5SOuYyn5x4xiMv3jEmlgKNI+w1B/WTxhdnwLnQY2ZwEY1AeqgHRzN0/PiiMmh8x8Vu9YjRxX4CjYcgdwhhE6qNn8DBrD/5AXnQeF3ct1Ap1/VakB3YbThQgXEIVG4X1w7UyXUFs2tnvwq5+0XDBy38RZYMKQuejf7Yw4YZXVCjEHwFyQmyyA4TBPAXhiiUDcMJzfaFvwXdgWYbz/jTjxjgTTiQN2qYQca8DxV44KQpC7SyIi7DjJCcExeET7YAplcGNQvC8RxB3qS6XUTacHEgF7mmvHTTUT+Nnb06Ozi2emOWYeEZRAvUdXZfR/SJ2AdS/8zuymUf9HLaFGLnt3DkPTIQqTLSXRDQ2W0tETbYHSgru3eyjLbfJa9dpYEIG6QHdo4T5LHQdUfUjduas9vhxglJzLaJhKtGOEHdhKrm4gB3YapFdlznHLvhiB1tQtqEmpDFFL9umkH3hNGzQTF+8YZjzGi6uBgg58yuHH0nFM67CIH/xfP+OH9Q9LAXRHn3Du1NhuQCgY80dyZ/4caee58xocYSOgg+uOe7gWzDcwaRWMsOQocVLQI5bOBCggzSDzx8wQsTFEg4RnQ8h1nnVdchA8rucZ02+Iwg4xOaly4DOu8tbg4HogRC6uGfVx3oege5FbQ0VQ8Yts9hnxiUpf9qtapntYF+AxFFqE54qwPlYR772Mc2xpAiLqSOIPiwIG3OJC0ooQFAOVrNFbnTj/jEJ3U4MgPK/oUdmumMDUWCm6u6wDGDbMOMylhINli3IjO4MGkLqcMX7rc4B1nRIPboXdVUdLmNvExFGAMkQxZGHAHmYYXQ4xGPogGO1QBHkn/ZhhfIsDuL3IMLbjghKDECj3O40pWrjIk6XvkZj9hDCEKggAh26QAR9IAJsfzILXkpghj0RSPOYAEJdikCEjjTmczURTA3cgxmQlMEJbBFRlixAms+85vL3KUVpomRQOwSnMtUwTos8g4WnBOd8BTBCNxBzooA4p3oFAENKLL/Dx/g85neRCcEblDPifjzm/+UJz0jkgx35tMBSWDFCZqZTxWwo6AQYQVFwzkFh17zChG550YBKoJx9iMHIwVoCY6J0YVUk6K7TII/UEpSJRQNpSkNZy1WRdN8lgAXLWXIOyYKUIv2o5sklWlD7EHUfIrApsbxKDixqc2gJqQfOBipA4qwqRVMdQgNaWdOw2kD00kVodm0akL+MNJdfuYdbRWBUhVy1LGmc6ECEWs8S0AMtR4kGfjcJREEAliEPnUh9uipU1nqD8COVQQqwKtfBWIPXSJUBcEQCFsNO06F3BOe4ZzrQDQKWhHMYLIFEURKRVCDz5w0rlVFiEbtCtla/xLks/B0wBImAo98iJSZIrDBRTPSjqECd5c7hUgzElpSyjb1msNF0j+nCtJRaeCxIoiuQ2YhhF4el5cquIg9kJAD735Xt47RwWqzS9iEhjch/qTtaQ0C18fO1yHvQAFzmflTiwBiohv97n0bstzV3pcQCR0sQlQxXZLGliDVjGdzwxrfADvgBULo60WSEQHm8uAJE8EHUqfaWX8clKSMHViDAfoC2xJksxWVbEKSMWKSOgGvhOCBjlO8kPgi1AEqAMbifqDjsjLkpVNVZ15rvMwWI4SttBXBLQR41muWWCFQnuoLhquOCoNXxggRa1yVuo9Z6PK4okVklZdpZH8YY//MYWZykhFS4Io2JMsIjQE97cED814TstpFkgSY29lk4DTAMZ1xTncJVX+oF60aNgiMS8vVg4h0qiJ4MEJ8jNAX0FPMpR2wQaRRZUYLZBArDueVCXJdn0rzMgmttEHwYddr8riy603zQfBM0uE6o5u0dcCqB/IOyxq2zeasNWTBvNx4OtkfSL4mmE9d6yZPm8EVdfFBZovpRm/qzBJ+tq7WvEvtclvCw540QvepsxOH09u6UqxTdd3V1UZ2IY7FdAy0/drSrtQg7ibpsJsd6oLoNZ+vdsY7d9nmUT/XqcP2RyGYy+NxL9oB1TX4isVZkHxredq4zec8CXJuhI5guCH/L3dCLu3vYtD3rCpfCKoXPQJFl7bh/TC2YendbuwOg9WPZXd9ba2QgNtZ0ohWQaQTYo81L5PdzZI3QBse4XyS4NV/bfAusQ7X0ioVxrvUdEHsIeepQn0gdQ6nqBOCagmLneRah3rTH6sCbeuq7LvMeNUxPU69hn0hBAft0w0ycxEAORYI2YcrWJoBuq8zIdLQeps9PtWG73rRUh6I0aHZ3wqrAKiArzYJ0FsQbjjAASWIRTtkywIH3Hfo+RQ3ksjd5pCDU9gyx/zPN+V0EZiAGM3o5YVXP5Bk1OAgbxa8M3EfEXNUgJltnnk8bWB3i+dztzprfGkzTmfMDzftH8fH/w9igHWBBF8EuzBI8pUvAu43JNnLL7G6EWp5Na8X9GQXvAjKf5DAF3Ug0fZxCPFaIrB7BOF/8fR2COFYMFV3q7IDtFV/Y1dqniYQ3KBs/GcQhXV72OcPtpdn1eeBzBRo/tB1ysd8C+EMELhwIqBg/rAPUjd1IZhXMBdcaKdsCjgQbWdYx7R50KRn28ZM71UQ+6B9+gdvFMRp16RklOV01qYQARhOWLd3AoWEBfFoJCVuPrhM+6aB52SDllZt+pQQswAE3jVVpPeAUZaBBGF0pkUQJuhsCgF714R4mkdbTDhavRROoGcQUThVJQBmrLADZ4hpQzgQ87duCUGH4fRgIuOmfyXAhgLBctDkgHfob+UHf00Wgv1WWpDFC+qADuZwaNiVhwCYarvEY1gFZwURg9fUhV4YV0vnD+bkiS+ADurACoW4dQoBfk71XcFmA9NWD6mWTozVD+oVYBAge9SmfyIgAwbhDINmWEhIeZh2XNckgQVBicrHfrvkBFgmhsW0UC+FaMxIg8qGTZ3FD0r4bgfBVKKnbzM4EP1UjN64Sz1AgmOHU854eoUYTg4gjIqGirx0eoGFTVbYjN0IUMs4bc1yXfFoWIZHA/ngEGRnjxImVwwxWxFpWCPgclfVagtpeC9AfKIPwY3eGAM94JCehZGGFQOzuIj8uJDLhHrgKFRlh2k8xxCz8HwBFU4FaQOzwJIMQQ5mCFzXaHg28AsRUWbA9pNA2UtQ8HgNAQ8QuV6HdxHvkALudFwpAAMtEJMWMQgsAAPAyJVgxU47AANdCVwlAJaSuJEsAGDMBJYGiBH94Ap6uZdEiRGysJd7OY8S8Q6AqZe8kBHOUJiCiVqM2ZiO+ZgxERAAOw==");_x000D_
var byteNumbers = new Array(byteCharacters.length);_x000D_
for (var i = 0; i < byteCharacters.length; i++) {_x000D_
byteNumbers[i] = byteCharacters.charCodeAt(i);_x000D_
}_x000D_
var byteArray = new Uint8Array(byteNumbers);_x000D_
_x000D_
// now that we have the byte array, construct the blob from it_x000D_
var blob1 = new Blob([byteArray], {type: "application/octet-stream"});_x000D_
_x000D_
var fileName1 = "cool.gif";_x000D_
saveAs(blob1, fileName1);_x000D_
_x000D_
// saving text file_x000D_
var blob2 = new Blob(["cool"], {type: "text/plain"});_x000D_
var fileName2 = "cool.txt";_x000D_
saveAs(blob2, fileName2);_x000D_
})();
_x000D_
Tested on Chrome, Edge, Firefox, and IE 11 (use FileSaver.js
for supporting IE 11).
You can also save from a canvas
element. See https://github.com/eligrey/FileSaver.js#saving-a-canvas.
Demos: https://eligrey.com/demos/FileSaver.js/
Blog post by author of FileSaver.js
: http://eligrey.com/blog/post/saving-generated-files-on-the-client-side
Note 1: Browser support: https://github.com/eligrey/FileSaver.js#supported-browsers
Note 2: Failed to execute 'atob' on 'Window'
Note 3: Polyfill for browsers not supporting Blob: https://github.com/eligrey/Blob.js
See http://caniuse.com/#search=blob
Note 4: IE < 10 support (I've not tested this part):
https://github.com/eligrey/FileSaver.js#ie--10
https://github.com/eligrey/FileSaver.js/issues/56#issuecomment-30917476
Downloadify is a Flash-based polyfill for supporting IE6-9: https://github.com/dcneiner/downloadify (I don't recommend Flash-based solutions in general, though.)
Demo using Downloadify and FileSaver.js for supporting IE6-9 also: http://sheetjs.com/demos/table.html
Note 5: Creating a BLOB from a Base64 string in JavaScript
Note 6: FileSaver.js
examples: https://github.com/eligrey/FileSaver.js#examples
Just another possibility,
I replaced
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
with
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
and it started without any issues
Try to format your date with the Z
or z
timezone flags:
new SimpleDateFormat("MM/dd/yyyy KK:mm:ss a Z").format(dateObj);
To convert any date, for example utc:
moment( moment().utc().format( "YYYY-MM-DD HH:mm:ss" )).toDate()
Check against any long running queries in your database.
Increasing your pool size will only make your webapp live a little longer (and probably get a lot slower)
You can use sql server profiler and filter on duration / reads to see which querys need optimization.
I also see you're probably keeping a global connection?
blnMainConnectionIsCreatedLocal
Let .net do the pooling for you and open / close your connection with a using statement.
Suggestions:
Always open and close a connection like this, so .net can manage your connections and you won't run out of connections:
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
// do some stuff
} //conn disposed
As I mentioned, check your query with sql server profiler and see if you can optimize it. Having a slow query with many requests in a web app can give these timeouts too.
For my case, the exception was raised because I tried to mock a package-access
method. When I changed the method access level from package
to protected
the exception went away. E.g. inside below Java class,
public class Foo {
String getName(String id) {
return mMap.get(id);
}
}
the method String getName(String id)
has to be AT LEAST protected
level so that the mocking mechanism (sub-classing) can work.
The error seems to be thrown when you try and load they keystore from "C:/jakarta-tomcat/webapps/PlanB/Certs/my_pkcs12.p12" here:
ks.load( new FileInputStream(_privateKeyPath), _keyPass.toCharArray() );
Have you tried replaceing "/" with "\\" in your file path? If that doesn't help it probably has to do with Java's Unlimited Strength Jurisdiction Policy Files. You could check this by writing a little program that does AES encryption. Try encrypting with a 128 bit key, then if that works, try with a 256 bit key and see if it fails.
Code that does AES encyrption:
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class Test
{
final String ALGORITHM = "AES"; //symmetric algorithm for data encryption
final String PADDING_MODE = "/CBC/PKCS5Padding"; //Padding for symmetric algorithm
final String CHAR_ENCODING = "UTF-8"; //character encoding
//final String CRYPTO_PROVIDER = "SunMSCAPI"; //provider for the crypto
int AES_KEY_SIZE = 256; //symmetric key size (128, 192, 256) if using 256 you must have the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files installed
private String doCrypto(String plainText) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, UnsupportedEncodingException
{
byte[] dataToEncrypt = plainText.getBytes(CHAR_ENCODING);
//get the symmetric key generator
KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
keyGen.init(AES_KEY_SIZE); //set the key size
//generate the key
SecretKey skey = keyGen.generateKey();
//convert to binary
byte[] rawAesKey = skey.getEncoded();
//initialize the secret key with the appropriate algorithm
SecretKeySpec skeySpec = new SecretKeySpec(rawAesKey, ALGORITHM);
//get an instance of the symmetric cipher
Cipher aesCipher = Cipher.getInstance(ALGORITHM + PADDING_MODE);
//set it to encrypt mode, with the generated key
aesCipher.init(Cipher.ENCRYPT_MODE, skeySpec);
//get the initialization vector being used (to be returned)
byte[] aesIV = aesCipher.getIV();
//encrypt the data
byte[] encryptedData = aesCipher.doFinal(dataToEncrypt);
//initialize the secret key with the appropriate algorithm
SecretKeySpec skeySpecDec = new SecretKeySpec(rawAesKey, ALGORITHM);
//get an instance of the symmetric cipher
Cipher aesCipherDec = Cipher.getInstance(ALGORITHM +PADDING_MODE);
//set it to decrypt mode with the AES key, and IV
aesCipherDec.init(Cipher.DECRYPT_MODE, skeySpecDec, new IvParameterSpec(aesIV));
//decrypt and return the data
byte[] decryptedData = aesCipherDec.doFinal(encryptedData);
return new String(decryptedData, CHAR_ENCODING);
}
public static void main(String[] args)
{
String text = "Lets encrypt me";
Test test = new Test();
try {
System.out.println(test.doCrypto(text));
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Does this code work for you?
You might also want to try specifying your bouncy castle provider in this line:
Cipher.getInstance(ALGORITHM +PADDING_MODE, "YOUR PROVIDER");
And see if it could be an error associated with bouncy castle.
In the Hibernate mapping file for the id
property, if you use any generator class, for that property you should not set the value explicitly by using a setter method.
If you set the value of the Id property explicitly, it will lead the error above. Check this to avoid this error.
Check on yourCheckBox.Value
?
Use your bean class like this, if your JSON data starts with an an array object. it helps you.
Users[] bean = gson.fromJson(response,Users[].class);
Users is my bean class.
Response is my JSON data.
Note Slipstream's response, that base64.b64encode
and base64.b64decode
need bytes-like object, not string.
>>> import base64
>>> a = '{"name": "John", "age": 42}'
>>> base64.b64encode(a)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/usr/lib/python3.6/base64.py", line 58, in b64encode
encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'
static void InsertSettings(IEnumerable<Entry> settings) {
using (SqlConnection oConnection = new SqlConnection("Data Source=(local);Initial Catalog=Wip;Integrated Security=True")) {
oConnection.Open();
using (SqlTransaction oTransaction = oConnection.BeginTransaction()) {
using (SqlCommand oCommand = oConnection.CreateCommand()) {
oCommand.Transaction = oTransaction;
oCommand.CommandType = CommandType.Text;
oCommand.CommandText = "INSERT INTO [Setting] ([Key], [Value]) VALUES (@key, @value);";
oCommand.Parameters.Add(new SqlParameter("@key", SqlDbType.NChar));
oCommand.Parameters.Add(new SqlParameter("@value", SqlDbType.NChar));
try {
foreach (var oSetting in settings) {
oCommand.Parameters[0].Value = oSetting.Key;
oCommand.Parameters[1].Value = oSetting.Value;
if (oCommand.ExecuteNonQuery() != 1) {
//'handled as needed,
//' but this snippet will throw an exception to force a rollback
throw new InvalidProgramException();
}
}
oTransaction.Commit();
} catch (Exception) {
oTransaction.Rollback();
throw;
}
}
}
}
}
I think you are confused about how the compiler puts things together. When you use -c
flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o
files thus don't mix with -c
, and compiler warns you about that. Symbols from object file are not moved to other object files like that.
All object files should be on the final linker invocation, which is not the case here, so linker (called via g++
front-end) complains about missing symbols.
Here's a small example (calling g++
explicitly for clarity):
PROG ?= myprog
OBJS = worker.o main.o
all: $(PROG)
.cpp.o:
g++ -Wall -pedantic -ggdb -O2 -c -o $@ $<
$(PROG): $(OBJS)
g++ -Wall -pedantic -ggdb -O2 -o $@ $(OBJS)
There's also makedepend
utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the -M
gcc
option for building make
rules.
Is that a proper connection string?
Where is the SQL Server instance located?
You will need to verify that you are able to conenct to SQL Server using the connection string, you specified above.
EDIT: Look at the State property of the recordset to see if it is Open?
Also, change the CursorLocation property to adUseClient before opening the recordset.
This is a very interesting question and I hope my thought below could contribute an way of solution to it. This method do give a flat list without indexing, but it does have list and unlist to avoid the nesting structures. I'm not sure about the speed since I don't know how to benchmark it.
a_list<-list()
for(i in 1:3){
a_list<-list(unlist(list(unlist(a_list,recursive = FALSE),list(rnorm(2))),recursive = FALSE))
}
a_list
[[1]]
[[1]][[1]]
[1] -0.8098202 1.1035517
[[1]][[2]]
[1] 0.6804520 0.4664394
[[1]][[3]]
[1] 0.15592354 0.07424637
parseInt()
is just going to throw an exception if the parsing can't complete successfully. You can instead use Integers
, the corresponding object type, which makes things a little bit cleaner. So you probably want something closer to:
Integer s = null;
try {
s = Integer.valueOf(startField.getText());
}
catch (NumberFormatException e) {
// ...
}
if (s != null) { ... }
Beware if you do decide to use parseInt()
! parseInt()
doesn't support good internationalization, so you have to jump through even more hoops:
try {
NumberFormat nf = NumberFormat.getIntegerInstance(locale);
nf.setParseIntegerOnly(true);
nf.setMaximumIntegerDigits(9); // Or whatever you'd like to max out at.
// Start parsing from the beginning.
ParsePosition p = new ParsePosition(0);
int val = format.parse(str, p).intValue();
if (p.getIndex() != str.length()) {
// There's some stuff after all the digits are done being processed.
}
// Work with the processed value here.
} catch (java.text.ParseFormatException exc) {
// Something blew up in the parsing.
}
Read about Window.location
and the Location
interface:
var url = [location.protocol, '//', location.host, location.pathname].join('');
There is also another straight and more clear way
git commit -m "Title" -m "Description ..........";
Perhaps use information_schema:
SELECT EXISTS(
SELECT *
FROM information_schema.tables
WHERE
table_schema = 'company3' AND
table_name = 'tableincompany3schema'
);
Obviously, it would be easier simply to surround with double quotes, but where's the challenge in that? Here is the answer using only single quotes. I'm using a variable instead of alias
so that's it's easier to print for proof, but it's the same as using alias
.
$ rxvt='urxvt -fg '\''#111111'\'' -bg '\''#111111'\'
$ echo $rxvt
urxvt -fg '#111111' -bg '#111111'
Explanation
The key is that you can close the single quote and re-open it as many times as you want. For example foo='a''b'
is the same as foo='ab'
. So you can close the single quote, throw in a literal single quote \'
, then reopen the next single quote.
Breakdown diagram
This diagram makes it clear by using brackets to show where the single quotes are opened and closed. Quotes are not "nested" like parentheses can be. You can also pay attention to the color highlighting, which is correctly applied. The quoted strings are maroon, whereas the \'
is black.
'urxvt -fg '\''#111111'\'' -bg '\''#111111'\' # original
[^^^^^^^^^^] ^[^^^^^^^] ^[^^^^^] ^[^^^^^^^] ^ # show open/close quotes
urxvt -fg ' #111111 ' -bg ' #111111 ' # literal characters remaining
(This is essentially the same answer as Adrian's, but I feel this explains it better. Also his answer has 2 superfluous single quotes at the end.)
try this
from StringIO import StringIO
x="1 3\n 4.5 8"
numpy.genfromtxt(StringIO(x))
These steps worked for me when the error showed that the Filter class was missing (as reported in this false-diplicated question: JUnit: NoClassDefFoundError: org/junit/runner/manipulation/Filter ):
Thanks to these answers for giving me the hint for this solution: https://stackoverflow.com/a/34067333/5538923 and https://stackoverflow.com/a/39987979/5538923).
$a="some text =keep this,but not this"
$a.split('=')[1].split(',')[0]
returns
keep this
Is your type really arbitrary? If you know it is just going to be a int float or string you could just do
if val.dtype == float and np.isnan(val):
assuming it is wrapped in numpy , it will always have a dtype and only float and complex can be NaN
Since bit wise operations work on bits that are either 0 or 1, each bit represents a power of 2, so if I have the bits
1010
that value is 10.
Each bit is a power of two, so if we shift the bits to the right, we divide by 2
1010 --> 0101
0101 is 5
so, in general if you want to divide by some power of 2, you need to shift right by the exponent you raise two to, to get that value
so for instance, to divide by 16, you would shift by 4, as 2^^4 = 16.
Firstly, a Java double
cannot be null, and cannot be compared with a Java null
. (The double
type is a primitive (non-reference) type and primitive types cannot be null.)
Next, if you call ResultSet.getDouble(...)
, that returns a double
not a Double
, the documented behaviour is that a NULL (from the database) will be returned as zero. (See javadoc linked above.) That is no help if zero is a legitimate value for that column.
So your options are:
use ResultSet.wasNull()
to test for a (database) NULL ... immediately after the getDouble(...)
call, or
use ResultSet.getObject(...)
, and type cast the result to Double
.
The getObject
method will deliver the value as a Double
(assuming that the column type is double
), and is documented to return null
for a NULL. (For more information, this page documents the default mappings of SQL types to Java types, and therefore what actual type you should expect getObject
to deliver.)
@Kwang-Chun Kang Thanks Kang a lot! I found the solution is working and very helpful, it really save my day. For me I am trying to create a React.js component that convert *.xlsx to json object when user upload the excel file to a html input tag. First I need to install XLSX package with:
npm install xlsx --save
Then in my component code, import with:
import XLSX from 'xlsx'
The component UI should look like this:
<input
accept=".xlsx"
type="file"
onChange={this.fileReader}
/>
It calls a function fileReader(), which is exactly same as the solution provided. To learn more about fileReader API, I found this blog to be helpful: https://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api
Will it be faster in terms of throughput? Probably. But it also potentially locks more database objects at a time (depending on your database and your schema) and thereby decreases concurrency. In my experience people are often mislead by the "fewer database round-trips" argument when in reality on most OLTP systems where the database is on the same LAN, the real bottleneck is rarely the network.
You can download visual studio community edition with /layout
switch.
But I prefer to use /layout
with /NoRefresh
for my low-speed internet connection that downloading long more than a day.
vs_community.exe /layout /NoRefresh
Every time that you run the installer it searches for new updates and if it finds updates, start downloading them and consume more time and more bandwidth!
You can try the trim() method.
String newString = oldString.trim();
Take a look at javadocs
You can omit window
and just use location.href
. For example:
location.href = 'http://google.im/';
When in doubt, read the documentation:
filename = "C:\Temp\vblist.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)
Do Until f.AtEndOfStream
WScript.Echo f.ReadLine
Loop
f.Close
In addition to the other options, in at least IntelliJ IDEA 2017 Ultimate, WebStorm 2020.2, and probably a ton of other versions, you can do it in a single shortcut.
Edit preferences, search for Select in Project View
, and under Keymap, view the mapped shortcut or map one of your choice.
On the Mac, Ctrl + Option + L is not already used, and is the same shortcut as Visual Studio for Windows uses natively (Ctrl + Alt + L, so that could be a good choice.
When you write .class
after a class name, it references the class literal -
java.lang.Class
object that represents information about given class.
For example, if your class is Print
, then Print.class
is an object that represents the class Print
on runtime. It is the same object that is returned by the getClass()
method of any (direct) instance of Print
.
Print myPrint = new Print();
System.out.println(Print.class.getName());
System.out.println(myPrint.getClass().getName());
$this->db->where('(a = 1 or a = 2)');
You can use like this
let nsRange = NSRange(location: someInt, length: someInt)
as in
let myNSString = bigTOTPCode as NSString //12345678
let firstDigit = myNSString.substringWithRange(NSRange(location: 0, length: 1)) //1
let secondDigit = myNSString.substringWithRange(NSRange(location: 1, length: 1)) //2
let thirdDigit = myNSString.substringWithRange(NSRange(location: 2, length: 4)) //3456
indexPathForRow
is a class method!
The code should read:
NSIndexPath *myIP = [NSIndexPath indexPathForRow:0 inSection:0] ;
Another way, without regex
import string
punc = string.punctuation
thestring = "Hey, you - what are you doing here!?"
s = list(thestring)
''.join([o for o in s if not o in punc]).split()
Wouldn't it just be:
SELECT CURRENT_DATE - CHDLM FROM CHCART00 WHERE CHSTAT = '05';
That should return the number of days between the two dates, if I understand how date arithmetic works in DB2 correctly.
If CHDLM isn't a date you'll have to convert it to one. According to IBM the DATE() function would not be sufficient for the yyyymmdd format, but it would work if you can format like this: yyyy-mm-dd.
To show $message in your input:
<?php
if(isset($_POST['insert'])){
$message= "The insert function is called.";
}
if(isset($_POST['select'])){
$message="The select function is called.";
}
?>
<form method="post">
<input type="text" name="txt" value="<?php if(isset($message)){ echo $message;}?>" >
<input type="submit" name="insert" value="insert">
<input type="submit" name="select" value="select" >
</form>
To use functioncalling.php as an external file you have to include it somehow in your HTML document.
Get the Method Names:
var getMethodNames = function (obj) {
return (Object.getOwnPropertyNames(obj).filter(function (key) {
return obj[key] && (typeof obj[key] === "function");
}));
};
Or, Get the Methods:
var getMethods = function (obj) {
return (Object.getOwnPropertyNames(obj).filter(function (key) {
return obj[key] && (typeof obj[key] === "function");
})).map(function (key) {
return obj[key];
});
};
Well, it's just a javascript object, so you can manipulate data.items
just like you would an ordinary array. If you do:
data.items.pop();
your items
array will be 1 item shorter.
You should always use .equals()
when comparing Strings
in Java.
JUnit calls the .equals()
method to determine equality in the method assertEquals(Object o1, Object o2)
.
So, you are definitely safe using assertEquals(string1, string2)
. (Because String
s are Object
s)
Here is a link to a great Stackoverflow question regarding some of the differences between ==
and .equals()
.
The following option seems to be the perfect combination when dealing with recursive download:
wget -nd -np -P /dest/dir --recursive http://url/dir1/dir2
Relevant snippets from man pages for convenience:
-nd
--no-directories
Do not create a hierarchy of directories when retrieving recursively. With this option turned on, all files will get saved to the current directory, without clobbering (if a name shows up more than once, the
filenames will get extensions .n).
-np
--no-parent
Do not ever ascend to the parent directory when retrieving recursively. This is a useful option, since it guarantees that only the files below a certain hierarchy will be downloaded.
Just to add my configuration to the mix, I'm using MySQL 5.7.8 which has the same strict sql_mode rules by default.
I finally figured the following working in my /etc/mysql/my.conf:
[mysqld]
sql-mode="STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION"
i.e. dash, not underscore and quotes around the value.
I have NO other my.conf files other than /etc/mysql/my.conf
There are some extra config includes being loaded from /etc/mysql/conf.d/ but they are blank.
And that seems to work for me.
first fetch all the tags in that specific remote
git fetch <remote> 'refs/tags/*:refs/tags/*'
or just simply type
git fetch <remote>
Then check for the available tags
git tag -l
then switch to that specific tag using below command
git checkout tags/<tag_name>
Hope this will helps you!
There is a customization that went into Boto3 recently which helps with this (among other things). It is currently exposed on the low-level S3 client, and can be used like this:
s3_client = boto3.client('s3')
open('hello.txt').write('Hello, world!')
# Upload the file to S3
s3_client.upload_file('hello.txt', 'MyBucket', 'hello-remote.txt')
# Download the file from S3
s3_client.download_file('MyBucket', 'hello-remote.txt', 'hello2.txt')
print(open('hello2.txt').read())
These functions will automatically handle reading/writing files as well as doing multipart uploads in parallel for large files.
Note that s3_client.download_file
won't create a directory. It can be created as pathlib.Path('/path/to/file.txt').parent.mkdir(parents=True, exist_ok=True)
.
const fs = require('fs');
check in the function like below,
if(fs.existsSync(<path_that_need_to_be_checked>)){
// enter the code to excecute after the folder is there.
}
else{
// Below code to create the folder, if its not there
fs.mkdir('<folder_name>', cb function);
}
I think the traditional way is flexible and fairly easy to understand:
Markup
<div class="flex-grid">
<div class="col-4">.col-4</div>
<div class="col-4">.col-4</div>
<div class="col-4">.col-4</div>
<div class="col-4">.col-4</div>
<div class="col-4">.col-4</div>
<div class="col-4">.col-4</div>
<div class="col-3">.col-3</div>
<div class="col-9">.col-9</div>
<div class="col-6">.col-6</div>
<div class="col-6">.col-6</div>
</div>
Create grid.css file:
.flex-grid {
display: flex;
flex-flow: wrap;
}
.col-1 {flex: 0 0 8.3333%}
.col-2 {flex: 0 0 16.6666%}
.col-3 {flex: 0 0 25%}
.col-4 {flex: 0 0 33.3333%}
.col-5 {flex: 0 0 41.6666%}
.col-6 {flex: 0 0 50%}
.col-7 {flex: 0 0 58.3333%}
.col-8 {flex: 0 0 66.6666%}
.col-9 {flex: 0 0 75%}
.col-10 {flex: 0 0 83.3333%}
.col-11 {flex: 0 0 91.6666%}
.col-12 {flex: 0 0 100%}
[class*="col-"] {
margin: 0 0 10px 0;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
@media (max-width: 400px) {
.flex-grid {
display: block;
}
}
I've created an example (jsfiddle)
Try to resize the window under 400px, it's responsive!!
for item in array: array2.append (item)
Or, in this case:
array2 += array
You have to use getStackTrace ()
method instead of printStackTrace()
. Here is a good example:
import java.io.*;
/**
* Simple utilities to return the stack trace of an
* exception as a String.
*/
public final class StackTraceUtil {
public static String getStackTrace(Throwable aThrowable) {
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
aThrowable.printStackTrace(printWriter);
return result.toString();
}
/**
* Defines a custom format for the stack trace as String.
*/
public static String getCustomStackTrace(Throwable aThrowable) {
//add the class name and any message passed to constructor
final StringBuilder result = new StringBuilder( "BOO-BOO: " );
result.append(aThrowable.toString());
final String NEW_LINE = System.getProperty("line.separator");
result.append(NEW_LINE);
//add each element of the stack trace
for (StackTraceElement element : aThrowable.getStackTrace() ){
result.append( element );
result.append( NEW_LINE );
}
return result.toString();
}
/** Demonstrate output. */
public static void main (String... aArguments){
final Throwable throwable = new IllegalArgumentException("Blah");
System.out.println( getStackTrace(throwable) );
System.out.println( getCustomStackTrace(throwable) );
}
}
You could use this recursive function for generate necessary T-SQL script.
CREATE FUNCTION dbo.Update_Delete_PrimaryKey
(
@TableName NVARCHAR(255),
@ColumnName NVARCHAR(255),
@OldValue NVARCHAR(MAX),
@NewValue NVARCHAR(MAX),
@Del BIT
)
RETURNS NVARCHAR
(
MAX
)
AS
BEGIN
DECLARE @fks TABLE
(
constraint_name NVARCHAR(255),
table_name NVARCHAR(255),
col NVARCHAR(255)
);
DECLARE @Sql NVARCHAR(MAX),
@EnableConstraints NVARCHAR(MAX);
SET @Sql = '';
SET @EnableConstraints = '';
INSERT INTO @fks
(
constraint_name,
table_name,
col
)
SELECT oConstraint.name constraint_name,
oParent.name table_name,
oParentCol.name col
FROM sys.foreign_key_columns sfkc
--INNER JOIN sys.foreign_keys sfk
-- ON sfk.[object_id] = sfkc.constraint_object_id
INNER JOIN sys.sysobjects oConstraint
ON sfkc.constraint_object_id = oConstraint.id
INNER JOIN sys.sysobjects oParent
ON sfkc.parent_object_id = oParent.id
INNER JOIN sys.all_columns oParentCol
ON sfkc.parent_object_id = oParentCol.object_id
AND sfkc.parent_column_id = oParentCol.column_id
INNER JOIN sys.sysobjects oReference
ON sfkc.referenced_object_id = oReference.id
INNER JOIN sys.all_columns oReferenceCol
ON sfkc.referenced_object_id = oReferenceCol.object_id
AND sfkc.referenced_column_id = oReferenceCol.column_id
WHERE oReference.name = @TableName
AND oReferenceCol.name = @ColumnName
--AND (@Del <> 1 OR sfk.delete_referential_action = 0)
--AND (@Del = 1 OR sfk.update_referential_action = 0)
IF EXISTS(
SELECT 1
FROM @fks
)
BEGIN
DECLARE @Constraint NVARCHAR(255),
@Table NVARCHAR(255),
@Col NVARCHAR(255)
DECLARE Table_Cursor CURSOR LOCAL
FOR
SELECT f.constraint_name,
f.table_name,
f.col
FROM @fks AS f
OPEN Table_Cursor FETCH NEXT FROM Table_Cursor INTO @Constraint, @Table,@Col
WHILE (@@FETCH_STATUS = 0)
BEGIN
IF @Del <> 1
BEGIN
SET @Sql = @Sql + 'ALTER TABLE ' + @Table + ' NOCHECK CONSTRAINT ' + @Constraint + CHAR(13) + CHAR(10);
SET @EnableConstraints = @EnableConstraints + 'ALTER TABLE ' + @Table + ' CHECK CONSTRAINT ' + @Constraint
+ CHAR(13) + CHAR(10);
END
SET @Sql = @Sql + dbo.Update_Delete_PrimaryKey(@Table, @Col, @OldValue, @NewValue, @Del);
FETCH NEXT FROM Table_Cursor INTO @Constraint, @Table,@Col
END
CLOSE Table_Cursor DEALLOCATE Table_Cursor
END
DECLARE @DataType NVARCHAR(30);
SELECT @DataType = t.name +
CASE
WHEN t.name IN ('char', 'varchar', 'nchar', 'nvarchar') THEN '(' +
CASE
WHEN c.max_length = -1 THEN 'MAX'
ELSE CONVERT(
VARCHAR(4),
CASE
WHEN t.name IN ('nchar', 'nvarchar') THEN c.max_length / 2
ELSE c.max_length
END
)
END + ')'
WHEN t.name IN ('decimal', 'numeric') THEN '(' + CONVERT(VARCHAR(4), c.precision) + ','
+ CONVERT(VARCHAR(4), c.Scale) + ')'
ELSE ''
END
FROM sys.columns c
INNER JOIN sys.types t
ON c.user_type_id = t.user_type_id
WHERE c.object_id = OBJECT_ID(@TableName)
AND c.name = @ColumnName
IF @Del <> 1
BEGIN
SET @Sql = @Sql + 'UPDATE [' + @TableName + '] SET [' + @ColumnName + '] = CONVERT(' + @DataType + ', ' + ISNULL('N''' + @NewValue + '''', 'NULL')
+ ') WHERE [' + @ColumnName + '] = CONVERT(' + @DataType + ', ' + ISNULL('N''' + @OldValue + '''', 'NULL') +
');' + CHAR(13) + CHAR(10);
SET @Sql = @Sql + @EnableConstraints;
END
ELSE
SET @Sql = @Sql + 'DELETE [' + @TableName + '] WHERE [' + @ColumnName + '] = CONVERT(' + @DataType + ', N''' + @OldValue
+ ''');' + CHAR(13) + CHAR(10);
RETURN @Sql;
END
GO
DECLARE @Result NVARCHAR(MAX);
SET @Result = dbo.Update_Delete_PrimaryKey('@TableName', '@ColumnName', '@OldValue', '@NewValue', 0);/*Update*/
EXEC (@Result)
SET @Result = dbo.Update_Delete_PrimaryKey('@TableName', '@ColumnName', '@OldValue', NULL, 1);/*Delete*/
EXEC (@Result)
GO
DROP FUNCTION Update_Delete_PrimaryKey;
You got your answer, but why iterate over the tr when you can go straight for the inputs? That way you can store them easier into an array and it reduce the number of CSS queries. Depends what you want to do of course, but for collecting data it is a more flexible approach.
var array = [];
$("tr.item input").each(function() {
array.push({
name: $(this).attr('class'),
value: $(this).val()
});
});
console.log(array);?
Congrats to the previous answers... But I realised if the icons are in a row (say three icons as represented in the image above), you need to play around with columns and rows.
Here is the code
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
FlatButton(
onPressed: () {},
child: Icon(
Icons.call,
)),
FlatButton(
onPressed: () {},
child: Icon(
Icons.message,
)),
FlatButton(
onPressed: () {},
child: Icon(
Icons.block,
color: Colors.red,
)),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Text(
' Call',
),
Text(
'Message',
),
Text(
'Block',
style: TextStyle(letterSpacing: 2.0, color: Colors.red),
),
],
),
],
),
You need to to use FileAPI. It is available in the latest FF & Chrome, but not IE9. Grab any md5 JS implementation suggested above. I've tried this and abandoned it because JS was too slow (minutes on large image files). Might revisit it if someone rewrites MD5 using typed arrays.
Code would look something like this:
HTML:
<input type="file" id="file-dialog" multiple="true" accept="image/*">
JS (w JQuery)
$("#file-dialog").change(function() {
handleFiles(this.files);
});
function handleFiles(files) {
for (var i=0; i<files.length; i++) {
var reader = new FileReader();
reader.onload = function() {
var md5 = binl_md5(reader.result, reader.result.length);
console.log("MD5 is " + md5);
};
reader.onerror = function() {
console.error("Could not read the file");
};
reader.readAsBinaryString(files.item(i));
}
}
The order in which you use middleware in Express matters: middleware declared earlier will get called first, and if it can handle a request, any middleware declared later will not get called.
If express.static
is handling the request, you need to move your middleware up:
// need cookieParser middleware before we can do anything with cookies
app.use(express.cookieParser());
// set a cookie
app.use(function (req, res, next) {
// check if client sent cookie
var cookie = req.cookies.cookieName;
if (cookie === undefined) {
// no: set a new cookie
var randomNumber=Math.random().toString();
randomNumber=randomNumber.substring(2,randomNumber.length);
res.cookie('cookieName',randomNumber, { maxAge: 900000, httpOnly: true });
console.log('cookie created successfully');
} else {
// yes, cookie was already present
console.log('cookie exists', cookie);
}
next(); // <-- important!
});
// let static middleware do its job
app.use(express.static(__dirname + '/public'));
Also, middleware needs to either end a request (by sending back a response), or pass the request to the next middleware. In this case, I've done the latter by calling next()
when the cookie has been set.
Update
As of now the cookie parser is a seperate npm package, so instead of using
app.use(express.cookieParser());
you need to install it separately using npm i cookie-parser
and then use it as:
const cookieParser = require('cookie-parser');
app.use(cookieParser());
The standard way is to use audio/mpeg
which is something like this in your PHP header function ...
header('Content-Type: audio/mpeg');
You need to make the second element a 1-tuple, eg:
a = ('2',)
b = 'z'
new = a + (b,)
You should use
<tbody>
<tr>
first page content here
</tr>
<tr>
..
</tr>
</tbody>
<tbody>
next page content...
</tbody>
And CSS:
tbody { display: block; page-break-before: avoid; }
tbody { display: block; page-break-after: always; }
Because the PermGen space was removed. Memory management has changed a bit.
simple way to use modals is with eModal!
Ex from github:
<script src="//rawgit.com/saribe/eModal/master/dist/eModal.min.js"></script>
var options = {_x000D_
message: "The famouse question?",_x000D_
title: 'Header title',_x000D_
size: 'sm',_x000D_
callback: function(result) { result ? doActionTrue(result) : doActionFalse(); },_x000D_
subtitle: 'smaller text header',_x000D_
label: "True" // use the possitive lable as key_x000D_
//..._x000D_
};_x000D_
_x000D_
eModal.confirm(options);
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script>_x000D_
<script src="//rawgit.com/saribe/eModal/master/dist/eModal.min.js"></script>
_x000D_
Tip: You can use change the default label name! { label: 'Yes' | 'True'| 'OK' }
Its late, yet it's worth your time nothing that, there are some differences in browser level implementation of focusin and focusout events and react synthetic onFocus and onBlur. focusin and focusout actually bubble, while onFocus and onBlur dont. So there is no exact same implementation for focusin and focusout as of now for react. Anyway most cases will be covered in onFocus and onBlur.
You can always abuse type juggling:
function zpad(int $value, int $pad): string {
return substr(1, $value + 10 ** $pad);
}
This wont work as expected if either 10 ** pad > INT_MAX
or value >= 10 * pad
.
Edit: For a better approximation of Alejandro's answer, see below.
I know this is an old question, but wanted to add something to Alejandro's anwser: If you want a nice smoothed image without using py-sphviewer you can instead use np.histogram2d
and apply a gaussian filter (from scipy.ndimage.filters
) to the heatmap:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from scipy.ndimage.filters import gaussian_filter
def myplot(x, y, s, bins=1000):
heatmap, xedges, yedges = np.histogram2d(x, y, bins=bins)
heatmap = gaussian_filter(heatmap, sigma=s)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
return heatmap.T, extent
fig, axs = plt.subplots(2, 2)
# Generate some test data
x = np.random.randn(1000)
y = np.random.randn(1000)
sigmas = [0, 16, 32, 64]
for ax, s in zip(axs.flatten(), sigmas):
if s == 0:
ax.plot(x, y, 'k.', markersize=5)
ax.set_title("Scatter plot")
else:
img, extent = myplot(x, y, s)
ax.imshow(img, extent=extent, origin='lower', cmap=cm.jet)
ax.set_title("Smoothing with $\sigma$ = %d" % s)
plt.show()
Produces:
The scatter plot and s=16 plotted on top of eachother for Agape Gal'lo (click for better view):
One difference I noticed with my gaussian filter approach and Alejandro's approach was that his method shows local structures much better than mine. Therefore I implemented a simple nearest neighbour method at pixel level. This method calculates for each pixel the inverse sum of the distances of the n
closest points in the data. This method is at a high resolution pretty computationally expensive and I think there's a quicker way, so let me know if you have any improvements.
Update: As I suspected, there's a much faster method using Scipy's scipy.cKDTree
. See Gabriel's answer for the implementation.
Anyway, here's my code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
def data_coord2view_coord(p, vlen, pmin, pmax):
dp = pmax - pmin
dv = (p - pmin) / dp * vlen
return dv
def nearest_neighbours(xs, ys, reso, n_neighbours):
im = np.zeros([reso, reso])
extent = [np.min(xs), np.max(xs), np.min(ys), np.max(ys)]
xv = data_coord2view_coord(xs, reso, extent[0], extent[1])
yv = data_coord2view_coord(ys, reso, extent[2], extent[3])
for x in range(reso):
for y in range(reso):
xp = (xv - x)
yp = (yv - y)
d = np.sqrt(xp**2 + yp**2)
im[y][x] = 1 / np.sum(d[np.argpartition(d.ravel(), n_neighbours)[:n_neighbours]])
return im, extent
n = 1000
xs = np.random.randn(n)
ys = np.random.randn(n)
resolution = 250
fig, axes = plt.subplots(2, 2)
for ax, neighbours in zip(axes.flatten(), [0, 16, 32, 64]):
if neighbours == 0:
ax.plot(xs, ys, 'k.', markersize=2)
ax.set_aspect('equal')
ax.set_title("Scatter Plot")
else:
im, extent = nearest_neighbours(xs, ys, resolution, neighbours)
ax.imshow(im, origin='lower', extent=extent, cmap=cm.jet)
ax.set_title("Smoothing over %d neighbours" % neighbours)
ax.set_xlim(extent[0], extent[1])
ax.set_ylim(extent[2], extent[3])
plt.show()
Result:
This is an activity you can subclass to force the connecting to a specific wifi: https://github.com/zoltanersek/android-wifi-activity/blob/master/app/src/main/java/com/zoltanersek/androidwifiactivity/WifiActivity.java
You will need to subclass this activity and implement its methods:
public class SampleActivity extends WifiBaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected int getSecondsTimeout() {
return 10;
}
@Override
protected String getWifiSSID() {
return "WifiNetwork";
}
@Override
protected String getWifiPass() {
return "123456";
}
}
private File convertMultiPartToFile(MultipartFile file ) throws IOException
{
File convFile = new File( file.getOriginalFilename() );
FileOutputStream fos = new FileOutputStream( convFile );
fos.write( file.getBytes() );
fos.close();
return convFile;
}
Use jq -s add
:
$ echo '{"a":"foo","b":"bar"} {"c":"baz","a":0}' | jq -s add
{
"a": 0,
"b": "bar",
"c": "baz"
}
This reads all JSON texts from stdin into an array (jq -s
does that) then it "reduces" them.
(add
is defined as def add: reduce .[] as $x (null; . + $x);
, which iterates over the input array's/object's values and adds them. Object addition == merge.)
class myClass { protected $foo;
public function __construct(&$var)
{
$this->foo = &$var;
}
public function foo()
{
return ++$this->foo;
}
}
I had the same problem, and solved by simply doing this at the command line:
mongodump -d databasename
echo 'db.dropDatabase()' | mongo databasename
mongorestore dump/databasename
You'd be surprised to find out that 80/20 is quite a commonly occurring ratio, often referred to as the Pareto principle. It's usually a safe bet if you use that ratio.
However, depending on the training/validation methodology you employ, the ratio may change. For example: if you use 10-fold cross validation, then you would end up with a validation set of 10% at each fold.
There has been some research into what is the proper ratio between the training set and the validation set:
The fraction of patterns reserved for the validation set should be inversely proportional to the square root of the number of free adjustable parameters.
In their conclusion they specify a formula:
Validation set (v) to training set (t) size ratio, v/t, scales like ln(N/h-max), where N is the number of families of recognizers and h-max is the largest complexity of those families.
What they mean by complexity is:
Each family of recognizer is characterized by its complexity, which may or may not be related to the VC-dimension, the description length, the number of adjustable parameters, or other measures of complexity.
Taking the first rule of thumb (i.e.validation set should be inversely proportional to the square root of the number of free adjustable parameters), you can conclude that if you have 32 adjustable parameters, the square root of 32 is ~5.65, the fraction should be 1/5.65 or 0.177 (v/t). Roughly 17.7% should be reserved for validation and 82.3% for training.
The right answer (using Python 2.7 and later, since check_output()
was introduced then) is:
py2output = subprocess.check_output(['python','py2.py','-i', 'test.txt'])
To demonstrate, here are my two programs:
py2.py:
import sys
print sys.argv
py3.py:
import subprocess
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'])
print('py2 said:', py2output)
Running it:
$ python3 py3.py
py2 said: b"['py2.py', '-i', 'test.txt']\n"
Here's what's wrong with each of your versions:
py2output = subprocess.check_output([str('python py2.py '),'-i', 'test.txt'])
First, str('python py2.py')
is exactly the same thing as 'python py2.py'
—you're taking a str
, and calling str
to convert it to an str
. This makes the code harder to read, longer, and even slower, without adding any benefit.
More seriously, python py2.py
can't be a single argument, unless you're actually trying to run a program named, say, /usr/bin/python\ py2.py
. Which you're not; you're trying to run, say, /usr/bin/python
with first argument py2.py
. So, you need to make them separate elements in the list.
Your second version fixes that, but you're missing the '
before test.txt'
. This should give you a SyntaxError
, probably saying EOL while scanning string literal
.
Meanwhile, I'm not sure how you found documentation but couldn't find any examples with arguments. The very first example is:
>>> subprocess.check_output(["echo", "Hello World!"])
b'Hello World!\n'
That calls the "echo"
command with an additional argument, "Hello World!"
.
Also:
-i is a positional argument for argparse, test.txt is what the -i is
I'm pretty sure -i
is not a positional argument, but an optional argument. Otherwise, the second half of the sentence makes no sense.
UPDATE: Keep in mind, at the time the answer was initially written in 2010, the bellow function toFixed() worked slightly different. toFixed() seems to do some rounding now, but not in the strictly mathematical manner. So be careful with it. Do your tests... The method described bellow will do rounding well, as mathematician would expect.
toFixed()
- method converts a number into a string, keeping a specified number of decimals. It does not actually rounds up a number, it truncates the number.Math.round(n)
- rounds a number to the nearest integer. Thus turning:0.5 -> 1; 0.05 -> 0
so if you want to round, say number 0.55555, only to the second decimal place; you can do the following(this is step-by-step concept):
0.55555 * 100
= 55.555 Math.Round(55.555)
-> 56.00056.000 / 100
= 0.56000 (0.56000).toFixed(2)
-> 0.56and this is the code:
(Math.round(number * 100)/100).toFixed(2);
The easiest way to match both
^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$
and
^[0-9]{3}-[0-9]{3}-[0-9]{4}$
is to use alternation ((...|...)
): specify them as two mostly-separate options:
^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$
By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234
, not (123)123-1234
. So you might want to write:
^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$
(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)
In this scenario, since you are working with inline
-level elements, you could add vertical-align: middle
to the span
elements for vertical centering:
.nav-text {
vertical-align: middle;
}
Alternatively, you could set the display
of the parent element to flex
and set align-items
to center
for vertical centering:
.menu {
display: flex;
align-items: center;
}
Open Project References, I had lots of yellow warning triangles on the various packages. Click Add Reference, just doing that seems to get VS to refresh it references, and the yellow triangles disappeared and the errors from the code also.
You might have to do this in a few projects if your solution reference to other projects
Check out this jQuery page for some interesting examples of how to play with the value attribute, and how to call it:
Otherwise - if you want to use jQuery rather than javascript in passing variables to an input of any kind, use the following to set the value of the input on an event click()
, submit()
et al:
on some event; assign or set the value of the input:
$('#inputid').val($('#idB').text());
where:
<input id = "inputid" type = "hidden" />
<div id = "idB">This text will be passed to the input</div>
Using such an approach, make sure the html input does not already specify a value, or a disabled attribute, obviously.
Beware the differences betwen .html()
and .text()
when dealing with html forms.
try this,
NSString *string = @"test Data";
if ([[string lowercaseString] rangeOfString:@"data"].location == NSNotFound)
{
NSLog(@"string does not contain Data");
}
else
{
NSLog(@"string contains data!");
}
If you don't have an id on the image but have a parent div this is also a technique you can use.
<div id="myDiv"><img src="http://www.example.com/image.png"></div>
var myVar = document.querySelectorAll('#myDiv img')[0].src
None of the above solutions don't work for me.
Flutter suggests this - Put your widget inside new GestureDetector() on which tap will hide keyboard and onTap use FocusScope.of(context).requestFocus(new FocusNode())
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
var widget = new MaterialApp(
home: new Scaffold(
body: new Container(
height:500.0,
child: new GestureDetector(
onTap: () {
FocusScope.of(context).requestFocus(new FocusNode());
},
child: new Container(
color: Colors.white,
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
new TextField( ),
new Text("Test"),
],
)
)
)
)
),
);
return widget;
}}
No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<xsl:variable name="mapping">
<item key="1" v1="A" v2="B" />
<item key="2" v1="X" v2="Y" />
</xsl:variable>
<xsl:variable name="mappingNode"
select="document('')//xsl:variable[@name = 'mapping']" />
<xsl:template match="....">
<xsl:variable name="testVariable" select="'1'" />
<xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />
<xsl:variable name="variable1" select="$values/@v1" />
<xsl:variable name="variable2" select="$values/@v2" />
</xsl:template>
</xsl:stylesheet>
In fact, once you've got the values
variable, you may not even need separate variable1
and variable2
variables. You could just use $values/@v1
and $values/@v2
instead.
Step 1:
select object_name, s.sid, s.serial#, p.spid
from v$locked_object l, dba_objects o, v$session s, v$process p
where l.object_id = o.object_id and l.session_id = s.sid and s.paddr = p.addr;
Step 2:
alter system kill session 'sid,serial#'; --`sid` and `serial#` get from step 1
More info: http://www.oracle-base.com/articles/misc/killing-oracle-sessions.php
Just use:
$output = array_merge($array1, $array2);
That should solve it. Because you use string keys if one key occurs more than one time (like '44'
in your example) one key will overwrite proceding ones with the same name. Because in your case they both have the same value anyway it doesn't matter and it will also remove duplicates.
Update: I just realised, that PHP treats the numeric string-keys as numbers (integers) and so will behave like this, what means, that it renumbers the keys too...
A workaround is to recreate the keys.
$output = array_combine($output, $output);
Update 2: I always forget, that there is also an operator (in bold, because this is really what you are looking for! :D)
$output = $array1 + $array2;
All of this can be seen in: http://php.net/manual/en/function.array-merge.php
I you only want to see what was printed in the console you could simple add the "printed" part somewhere in your HTML so it will appear in on the webpage. You could do it for yourself, but there is a javascript file that does this for you. You can read about it here:
http://www.hnldesign.nl/work/code/mobileconsole-javascript-console-for-mobile-devices/
The code is available from Github; you can download it and paste it into a javascipt file and add it in to your HTML
Although an old question, here is another (imho the cleanest and best) solution as all the previous answeres didn't work for me since I deeplinked Activity B from a Widget.
public void navigateUp() {
final Intent upIntent = NavUtils.getParentActivityIntent(this);
if (NavUtils.shouldUpRecreateTask(this, upIntent) || isTaskRoot()) {
Log.v(logTag, "Recreate back stack");
TaskStackBuilder.create(this).addNextIntentWithParentStack(upIntent).startActivities();
} else {
NavUtils.navigateUpTo(this, upIntent);
}
}
[https://stackoverflow.com/a/31350642/570168 ]
But also see: https://speakerdeck.com/jgilfelt/this-way-up-implementing-effective-navigation-on-android
Create a div that is the line with the code like this:
CSS
div#lineHorizontal {
background-color: #000;
width: //the width of the line or how far it goes sidewards;
height: 2px;
display: inline-block;
margin: 0px;
}
div#block {
background-color: #777;
display: inline-block;
margin: 0px;
}
HTML
<div id="block">
</div>
<div id="lineHorizontal">
</div>
<div id="block">
</div>
This will display a block with a horizontal line to another block.
On mobile devices you could use (caniuse.com/transforms2d)
File.expand_path File.dirname(__FILE__)
will return the directory relative to the file this command is called from.
But Dir.pwd
returns the working directory (results identical to executing pwd
in your terminal)
It looks like you're just missing an opening double-quote. Try:
if Verbose:
print("Building internam Index for %d tile(s) ..." % len(inputTiles), end=' ')
And now for something completely different. The following assumes arial font, and makes a wild guess based on a linear interpolation of character vs width.
// Returns the size in PICA of the string, given space is 200 and 'W' is 1000.
// see https://p2p.wrox.com/access/32197-calculate-character-widths.html
static int picaSize(String s)
{
// the following characters are sorted by width in Arial font
String lookup = " .:,;'^`!|jl/\\i-()JfIt[]?{}sr*a\"ce_gFzLxkP+0123456789<=>~qvy$SbduEphonTBCXY#VRKZN%GUAHD@OQ&wmMW";
int result = 0;
for (int i = 0; i < s.length(); ++i)
{
int c = lookup.indexOf(s.charAt(i));
result += (c < 0 ? 60 : c) * 7 + 200;
}
return result;
}
Interesting, but perhaps not very practical.
First of all you can look here for a list of the various operations the individual iterator types need to support.
Next, when you have made your iterator class you need to either specialize std::iterator_traits
for it and provide some necessary typedef
s (like iterator_category
or value_type
) or alternatively derive it from std::iterator
, which defines the needed typedef
s for you and can therefore be used with the default std::iterator_traits
.
disclaimer: I know some people don't like cplusplus.com
that much, but they provide some really useful information on this.
Turns out that to copy a complete directory structure gulp
needs to be provided with a base for your gulp.src()
method.
So gulp.src( [ files ], { "base" : "." })
can be used in the structure above to copy all the directories recursively.
If, like me, you may forget this then try:
gulp.copy=function(src,dest){
return gulp.src(src, {base:"."})
.pipe(gulp.dest(dest));
};
You can use that for string Enum
public enum EnumTest {
NAME_ONE("Name 1"),
NAME_TWO("Name 2");
private final String name;
/**
* @param name
*/
private EnumTest(final String name) {
this.name = name;
}
public String getName() {
return name;
}
}
And call from main method
public class Test {
public static void main (String args[]){
System.out.println(EnumTest.NAME_ONE.getName());
System.out.println(EnumTest.NAME_TWO.getName());
}
}
Do you have a bean declared in your context file that has an id of "articleService"? I believe that autowiring matches the id of a bean in your context files with the variable name that you are attempting to Autowire.
use inline-block
instead of inline
. Read more information here about the difference between inline and inline-block.
.inline {
display: inline-block;
border: 1px solid red;
margin:10px;
}
In my case the path of MySQL data folder had a special character "ç" and it make me get...
Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist.
I'm have removed all special characters and everything works.
<FilesMatch "\.(js|css)$">
ExpiresActive On
ExpiresDefault A1
Header append Cache-Control must-revalidate
</FilesMatch>
As a workaround, you could use the timestamp (old and new) for checking though, that one is not updated when there are no changes to the row. (Possibly that is the source for confusion? Because that one is also called 'on update' but is not executed when no change occurs) Changes within one second will then not execute that part of the trigger, but in some cases that could be fine (like when you have an application that rejects fast changes anyway.)
For example, rather than
IF NEW.a <> OLD.a or NEW.b <> OLD.b /* etc, all the way to NEW.z <> OLD.z */
THEN
INSERT INTO bar (a, b) VALUES(NEW.a, NEW.b) ;
END IF
you could use
IF NEW.ts <> OLD.ts
THEN
INSERT INTO bar (a, b) VALUES(NEW.a, NEW.b) ;
END IF
Then you don't have to change your trigger every time you update the scheme (the issue you mentioned in the question.)
EDIT: Added full example
create table foo (a INT, b INT, ts TIMESTAMP);
create table bar (a INT, b INT);
INSERT INTO foo (a,b) VALUES(1,1);
INSERT INTO foo (a,b) VALUES(2,2);
INSERT INTO foo (a,b) VALUES(3,3);
DELIMITER ///
CREATE TRIGGER ins_sum AFTER UPDATE ON foo
FOR EACH ROW
BEGIN
IF NEW.ts <> OLD.ts THEN
INSERT INTO bar (a, b) VALUES(NEW.a, NEW.b);
END IF;
END;
///
DELIMITER ;
select * from foo;
+------+------+---------------------+
| a | b | ts |
+------+------+---------------------+
| 1 | 1 | 2011-06-14 09:29:46 |
| 2 | 2 | 2011-06-14 09:29:46 |
| 3 | 3 | 2011-06-14 09:29:46 |
+------+------+---------------------+
3 rows in set (0.00 sec)
-- UPDATE without change
UPDATE foo SET b = 3 WHERE a = 3;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 1 Changed: 0 Warnings: 0
-- the timestamo didnt change
select * from foo WHERE a = 3;
+------+------+---------------------+
| a | b | ts |
+------+------+---------------------+
| 3 | 3 | 2011-06-14 09:29:46 |
+------+------+---------------------+
1 rows in set (0.00 sec)
-- the trigger didn't run
select * from bar;
Empty set (0.00 sec)
-- UPDATE with change
UPDATE foo SET b = 4 WHERE a=3;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
-- the timestamp changed
select * from foo;
+------+------+---------------------+
| a | b | ts |
+------+------+---------------------+
| 1 | 1 | 2011-06-14 09:29:46 |
| 2 | 2 | 2011-06-14 09:29:46 |
| 3 | 4 | 2011-06-14 09:34:59 |
+------+------+---------------------+
3 rows in set (0.00 sec)
-- and the trigger ran
select * from bar;
+------+------+---------------------+
| a | b | ts |
+------+------+---------------------+
| 3 | 4 | 2011-06-14 09:34:59 |
+------+------+---------------------+
1 row in set (0.00 sec)
It is working because of mysql's behavior on handling timestamps. The time stamp is only updated if a change occured in the updates.
Documentation is here:
https://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html
desc foo;
+-------+-----------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-----------+------+-----+-------------------+-----------------------------+
| a | int(11) | YES | | NULL | |
| b | int(11) | YES | | NULL | |
| ts | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+-------+-----------+------+-----+-------------------+-----------------------------+
Use ORACLE equivalent of getdate()
which is sysdate
. Read about here.
Getdate() belongs to SQL Server , will not work on Oracle.
Other option is current_date
import os
#Your path here e.g. "C:\Program Files\text.txt"
#For access purposes: "C:\\Program Files\\text.txt"
if os.path.exists("C:\..."):
print "File found!"
else:
print "File not found!"
Importing os
makes it easier to navigate and perform standard actions with your operating system.
For reference also see How to check whether a file exists using Python?
If you need high-level operations, use shutil
.
NATIVE is Non access modifier.it can be applied only to METHOD. It indicates the PLATFORM-DEPENDENT implementation of method or code.
For Button and TextView this is the easiest way:
Button:
Button button = (Button) findViewById(R.id.btton1);
button.setPaintFlags(button.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
Textview:
TextView textView = (TextView) findViewById(R.id.textview1);
textView.setPaintFlags(textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
If this problem occurs on a mac, then type the following commands:
source <path to conda>/bin/activate
conda init zsh
This will modify your zshrc accordingly (or create it if it does not exist).
This solution comes from the official anaconda doc.
Ross, you can use Arrays.copyof() or Arrays.copyOfRange() too.
Integer[] integerArray = Arrays.copyOf(a, a.length, Integer[].class);
Integer[] integerArray = Arrays.copyOfRange(a, 0, a.length, Integer[].class);
Here the reason to hitting an ClassCastException
is you can't treat an array of Integer
as an array of Object
. Integer[]
is a subtype of Object[]
but Object[]
is not a Integer[]
.
And the following also will not give an ClassCastException
.
Object[] a = new Integer[1];
Integer b=1;
a[0]=b;
Integer[] c = (Integer[]) a;
java.exe is the command where it waits for application to complete untill it takes the next command. javaw.exe is the command which will not wait for the application to complete. you can go ahead with another commands.
I believe the only way to do this it to add the style as a new CSS declaration with the '!important' suffix. The easiest way to do this is to append a new <style> element to the head of document:
function addNewStyle(newStyle) {
var styleElement = document.getElementById('styles_js');
if (!styleElement) {
styleElement = document.createElement('style');
styleElement.type = 'text/css';
styleElement.id = 'styles_js';
document.getElementsByTagName('head')[0].appendChild(styleElement);
}
styleElement.appendChild(document.createTextNode(newStyle));
}
addNewStyle('td.EvenRow a {display:inline !important;}')
The rules added with the above method will (if you use the !important suffix) override other previously set styling. If you're not using the suffix then make sure to take concepts like 'specificity' into account.
Complete guide : https://developer.android.com/studio/build/application-id.html
As per Android official Blogs : https://android-developers.googleblog.com/2011/06/things-that-cannot-change.html
We can say that:
If the manifest package name has changed, the new application will be installed alongside the old application, so they both co-exist on the user’s device at the same time.
If the signing certificate changes, trying to install the new application on to the device will fail until the old version is uninstalled.
As per Google App Update check list : https://support.google.com/googleplay/android-developer/answer/113476?hl=en
Update your apps
Prepare your APK
When you're ready to make changes to your APK, make sure to update your app’s version code as well so that existing users will receive your update.
Use the following checklist to make sure your new APK is ready to update your existing users:
To verify that your APK is using the same certification as the previous version, you can run the following command on both APKs and compare the results:
$ jarsigner -verify -verbose -certs my_application.apk
If the results are identical, you’re using the same key and are ready to continue. If the results are different, you will need to re-sign the APK with the correct key.
Learn more about signing your applications
Upload your APK Once your APK is ready, you can create a new release.
Native browser smooth scrolling in JavaScript is like this:
// scroll to specific values,
// same as window.scroll() method.
// for scrolling a particular distance, use window.scrollBy().
window.scroll({
top: 2500,
left: 0,
behavior: 'smooth'
});
// scroll certain amounts from current position
window.scrollBy({
top: 100, // negative value acceptable
left: 0,
behavior: 'smooth'
});
// scroll to a certain element
document.querySelector('.hello').scrollIntoView({
behavior: 'smooth'
});
Go to File->Import Settings... and select the jar settings file
Update as of IntelliJ 2020:
Go to File -> Manage IDE Settings -> Import Settings...
Update @Paul Grimshaw answer, use includes
insteed of indexOf
for more readable
let found = arr1.some(r=> arr2.indexOf(r) >= 0)
let found = arr1.some(r=> arr2.includes(r))
Manually add it when you build the query:
SELECT 'Site1' AS SiteName, t1.column, t1.column2
FROM t1
UNION ALL
SELECT 'Site2' AS SiteName, t2.column, t2.column2
FROM t2
UNION ALL
...
EXAMPLE:
DECLARE @t1 TABLE (column1 int, column2 nvarchar(1))
DECLARE @t2 TABLE (column1 int, column2 nvarchar(1))
INSERT INTO @t1
SELECT 1, 'a'
UNION SELECT 2, 'b'
INSERT INTO @t2
SELECT 3, 'c'
UNION SELECT 4, 'd'
SELECT 'Site1' AS SiteName, t1.column1, t1.column2
FROM @t1 t1
UNION ALL
SELECT 'Site2' AS SiteName, t2.column1, t2.column2
FROM @t2 t2
RESULT:
SiteName column1 column2
Site1 1 a
Site1 2 b
Site2 3 c
Site2 4 d
I've found that including the library as a pod install directly helps dynamic libraries. For example, for Firebase:
pod 'RNFirebase', :path => 'path/to/node_modules/react-native-firebase/ios'
Or for ASLogger:
pod 'ASLogger', :path => 'path/to/node_modules/aslogger/ios' // path to header files
Changing or hardcoding HEADER_SEARCH_PATHS
did not help me. If the error ever recurs, it's not necessary to rm -rf node_modules
nor delete the pod file etc, I found it useful to clear the cache.
For react-native, I run
rm -rf $TMPDIR/react-native-packager-cache-*
rm -rf $TMPDIR/metro-bundler-cache-*
rm -rf $TMPDIR/metro-*
rm -rf $TMPDIR/react-*
rm -rf $TMPDIR/haste-*
rm -rf "$(getconf DARWIN_USER_CACHE_DIR)/org.llvm.clang/ModuleCache"
npm start -- --reset-cache
For Xcode I remove folders in ~/Library/Developer/Xcode/DerivedData
What about a solution with only date functions, not math, not worries about leap year
CREATE FUNCTION dbo.getAge(@dt datetime)
RETURNS int
AS
BEGIN
RETURN
DATEDIFF(yy, @dt, getdate())
- CASE
WHEN
MONTH(@dt) > MONTH(GETDATE()) OR
(MONTH(@dt) = MONTH(GETDATE()) AND DAY(@dt) > DAY(GETDATE()))
THEN 1
ELSE 0
END
END
I'll give an example (in JavaScript):
function makeCounter () {
var count = 0;
return function () {
count += 1;
return count;
}
}
var x = makeCounter();
x(); returns 1
x(); returns 2
...etc...
What this function, makeCounter, does is it returns a function, which we've called x, that will count up by one each time its called. Since we're not providing any parameters to x it must somehow remember the count. It knows where to find it based on what's called lexical scoping - it must look to the spot where it's defined to find the value. This "hidden" value is what is called a closure.
Here is my currying example again:
function add (a) {
return function (b) {
return a + b;
}
}
var add3 = add(3);
add3(4); returns 7
What you can see is that when you call add with the parameter a (which is 3), that value is contained in the closure of the returned function that we're defining to be add3. That way, when we call add3 it knows where to find the a value to perform the addition.
This is a slightly modified version that lets you specify the name of the attribute in the scope, just as you would do with ng-model, usage:
<myUpload key="file"></myUpload>
Directive:
.directive('myUpload', function() {
return {
link: function postLink(scope, element, attrs) {
element.find("input").bind("change", function(changeEvent) {
var reader = new FileReader();
reader.onload = function(loadEvent) {
scope.$apply(function() {
scope[attrs.key] = loadEvent.target.result;
});
}
if (typeof(changeEvent.target.files[0]) === 'object') {
reader.readAsDataURL(changeEvent.target.files[0]);
};
});
},
controller: 'FileUploadCtrl',
template:
'<span class="btn btn-success fileinput-button">' +
'<i class="glyphicon glyphicon-plus"></i>' +
'<span>Replace Image</span>' +
'<input type="file" accept="image/*" name="files[]" multiple="">' +
'</span>',
restrict: 'E'
};
});
Consider having multiple matlab sessions. Keep the main session window (the pretty one with all the colours, file manager, command history, workspace, editor etc.) for running stuff that you know will terminate.
Stuff that you are experimenting with, say you are messing with ode suite and you get lots of warnings: matrix singular, because you altered some parameter and didn't predict what would happen, run in a separate session:
dos('matlab -automation -r &')
You can kill that without having to restart the whole of Matlab.
You can do
window.close();
window.open("index.html");
and it worked successfully on my website.
There are lot of answers here, and all of them are based on two methods:
Personally, I would use these two methods in different cases. Let me explain.
@FabioPhms: Your method was the one I initially used and I was afraid that it is bad on string with lots of characters. However, question is what's a lot of characters? I tested it on 10 "lorem ipsum" paragraphs and it took a few milliseconds. Then I tested it on 10 times larger string - there was really no big difference. Hm.
@vsync, @Cory Mawhorter: Your comments are unambiguous; however, again, what is a large string? I agree that for 32...100kb performance should better and one should use substring-variant for this one operation of character replacement.
But what will happen if I have to make quite a few replacements?
I needed to perform my own tests to prove what is faster in that case. Let's say we have an algorithm that will manipulate a relatively short string that consists of 1000 characters. We expect that in average each character in that string will be replaced ~100 times. So, the code to test something like this is:
var str = "... {A LARGE STRING HERE} ...";
for(var i=0; i<100000; i++)
{
var n = '' + Math.floor(Math.random() * 10);
var p = Math.floor(Math.random() * 1000);
// replace character *n* on position *p*
}
I created a fiddle for this, and it's here. There are two tests, TEST1 (substring) and TEST2 (array conversion).
Results:
It seems that array conversion beats substring by 2 orders of magnitude! So - what the hell happened here???
What actually happens is that all operations in TEST2 are done on array itself, using assignment expression like strarr2[p] = n
. Assignment is really fast compared to substring on a large string, and its clear that it's going to win.
So, it's all about choosing the right tool for the job. Again.
You might want to consider refactoring that query instead of adding an arbitrarily long list of ids... You could use a range if the ids indeed follow the pattern in your example:
SELECT * FROM user WHERE id >= minValue AND id <= maxValue;
Another option is to add an inner select:
SELECT *
FROM user
WHERE id IN (
SELECT userId
FROM ForumThreads ft
WHERE ft.id = X
);
Pyspark does include a dropDuplicates()
method, which was introduced in 1.4. https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrame.dropDuplicates
>>> from pyspark.sql import Row
>>> df = sc.parallelize([ \
... Row(name='Alice', age=5, height=80), \
... Row(name='Alice', age=5, height=80), \
... Row(name='Alice', age=10, height=80)]).toDF()
>>> df.dropDuplicates().show()
+---+------+-----+
|age|height| name|
+---+------+-----+
| 5| 80|Alice|
| 10| 80|Alice|
+---+------+-----+
>>> df.dropDuplicates(['name', 'height']).show()
+---+------+-----+
|age|height| name|
+---+------+-----+
| 5| 80|Alice|
+---+------+-----+
Here is a simple PHP way that I use.
If a page is requested with the .php extension then a new request is made without the .php extension. The .php extension is then no longer shown in the browser's address field.
I came up with this solution because none of the many .htaccess suggestions worked for me and it was quicker to implement this in PHP than trying to find out why the .htaccess did not work on my server.
Put this at the beginning of each PHP file (preferrably before anything else):
include_once('scripts.php');
strip_php_extension();
Then put these functions in the file 'scripts.php':
//==== Strip .php extension from requested URI
function strip_php_extension()
{
$uri = $_SERVER['REQUEST_URI'];
$ext = substr(strrchr($uri, '.'), 1);
if ($ext == 'php')
{
$url = substr($uri, 0, strrpos($uri, '.'));
redirect($url);
}
}
//==== Redirect. Try PHP header redirect, then Java, then http redirect
function redirect($url)
{
if (!headers_sent())
{
/* If headers not yet sent => do php redirect */
header('Location: '.$url);
exit;
}
else
{
/* If headers already sent => do javaScript redirect */
echo '<script type="text/javascript">';
echo 'window.location.href="'.$url.'";';
echo '</script>';
/* If javaScript is disabled => do html redirect */
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0; url='.$url.'" />';
echo '</noscript>';
exit;
}
}
Obviously you still need to have setup Apache to redirect any request without extension to the file with the extension. The above solution simply checks if the requested URI has an extension, if it does it requests the URI without the extension. Then Apache does the redirect to the file with the extension, but only the requested URI (without the extension) is shown in the browser's address field. The advantage is that all your "href" links in your code can still have the full filename, i.e. including the .php extension.
a = 2
x = 0
Do Until Cells(a, 1).Value = ""
If Rows(a).Hidden = False Then
x = Cells(a, 1).Value + x
End If
a = a + 1
Loop
End Sub
Other answers rightly point out that there is no need to use jQuery in order to navigate to another URL; that's why there's no jQuery function which does so!
If you're asking how to click a link via jQuery then assuming you have markup which looks like:
<a id="my-link" href="/relative/path.html">Click Me!</a>
You could click()
it by executing:
$('#my-link').click();
Just remove old APK android/app/build/outputs/apk/debug/app-debug.apk in the folder. that's all. enjoy your coding...
Fiddler is great when you are only interested in the http(s) side of the communications. It is also very useful when you are trying to inspect inside a https stream.
I've tried http://jqueryui.com/demos/autocomplete/#combobox and the problems faced were:
As a result I've tweaked it a bit and it worked fine for me in ASP.NET MVC. My version of CSS and widget script can be found here http://saplin.blogspot.com/2011/12/html-combobox-control-and-aspnet-mvc.html
Sample on binding MVC model to custom value is also there.
/([0-9]+[.,]*)+/
matches any number with or without coma or dots
it can match
122
122,354
122.88
112,262,123.7678
bug: it also matches 262.4377,3883 ( but it doesn't matter parctically)
A nice solution that I've found is to do on UI something like:
<div *ngIf="isDataLoaded">
...Your page...
</div
Only when: isDataLoaded is true the page is rendered.
Everybody seems to be suggesting that adding
using System.Configuration;
which is true.
But might I suggest that you think about installing ReSharper's Visual Studio extension?
With it installed, instead of seeing an error that a class isn't defined, you'll see a prompt that tells you which assembly it is in, asking you if you want it to add the needed using statement.
Have you seen this post on the subversion site? You could also potentially try validating and "fixing" the database directly as described here. (Note that I'm no expert, I just did a quick google search. May not be related to your issues at all).
Personally, I'd try checking out the repo again and reapplying your changes. Not sure if this is possible though in your case?
I was finding same but lastly i found an answer. I hope this answer help you so much.
when your array is empty then you can send empty array just like
if(!empty($result))
{
echo json_encode($result);
}
else
{
echo json_encode(array('data'=>''));
}
Thank you
For MVC developers,
Based on solution You've already found How to apply CSS to iframe?:
var cssLink = document.createElement("link")
cssLink.href = "file://path/to/style.css";
cssLink .rel = "stylesheet";
cssLink .type = "text/css";
frames['iframe'].document.body.appendChild(cssLink);
or more jqueryish (from Append a stylesheet to an iframe with jQuery):
var $head = $("iframe").contents().find("head");
$head.append($("<link/>",
{ rel: "stylesheet", href: "file://path/to/style.css", type: "text/css" }));
as for security issues: Disabling same-origin policy in Safari
You could specify the title (and also the title of the axes via xlab
and ylab
) with the main
option. E.g.:
plot(data[,i], main=names(data)[i])
And if you want to plot (and save) each variable of a dataframe, you should use png
, pdf
or any other graphics driver you need, and after that issue a dev.off()
command. E.g.:
data <- read.csv("sample.csv",header=T,sep=",")
for (i in 1:length(data)) {
pdf(paste('fileprefix_', names(data)[i], '.pdf', sep='')
plot(data[,i], ylab=names(data[i]), type="l")
dev.off()
}
Or draw all plots to the same image with the mfrow
paramater of par()
. E.g.: use par(mfrow=c(2,2)
to include the next 4 plots in the same "image".
You can use a Dictionary to keep track of the keys and values.
For instance...
dictOfStuff = {} ##Make a Dictionary
x = "Buffalo" ##OR it can equal the input of something, up to you.
dictOfStuff[x] = 4 ##Get the dict spot that has the same key ("name") as what X is equal to. In this case "Buffalo". and set it to 4. Or you can set it to what ever you like
print(dictOfStuff[x]) ##print out the value of the spot in the dict that same key ("name") as the dictionary.
A dictionary is very similar to a real life dictionary. You have a word and you have a definition. You can look up the word and get the definition. So in this case, you have the word "Buffalo" and it's definition is 4. It can work with any other word and definition. Just make sure you put them into the dictionary first.
For versions less than 5:
Change the cell type to raw then back to code: EscRY will discard the output.
For this, you need to edit the custom.js
file which is typically located at ~/.jupyter/custom/custom.js
(if it doesn't exist, create it).
In there, you have to add
require(['base/js/namespace']) {
// setup 'ctrl-l' as shortcut for clearing current output
Jupyter.keyboard_manager.command_shortcuts
.add_shortcut('ctrl-l', 'jupyter-notebook:clear-cell-output');
}
You can add shortcut there for all the fancy things you like, since the 2nd argument can be a function (docs)
If you want mappings for other standard commands, you can dump a list of all available commands by running the following in your notebook:
from IPython.core.display import Javascript
js = """
var jc_html = "";
var jc_array = Object.keys(IPython.notebook.keyboard_manager.command_shortcuts.actions._actions);
for (var i=0;i<jc_array.length;i++) {
jc_html = jc_html + jc_array[i] + "<br >";
}
element.html(jc_html);
"""
Javascript(data=js, lib=None, css=None)
View code online on: WebCrafts.org
HTML code:
<body id="body"> <div id="navigation"> <h2> Pure CSS Drop-down Menu </h2> <div id="nav" class="nav"> <ul> <li><a href="#">Menu1</a></li> <li> <a href="#">Menu2</a> <ul> <li><a href="#">Sub-Menu1</a></li> <li> <a href="#">Sub-Menu2</a> <ul> <li><a href="#">Demo1</a></li> <li><a href="#">Demo2</a></li> </ul> </li> <li><a href="#">Sub-Menu3</a></li> <li><a href="#">Sub-Menu4</a></li> </ul> </li> <li><a href="#">Menu3</a></li> <li><a href="#">Menu4</a></li> </ul> </div> </div> </body>
Css code:
body{
background-color:#111;
}
#navigation{
text-align:center;
}
#navigation h2{
color:#DDD;
}
.nav{
display:inline-block;
z-index:5;
font-weight:bold;
}
.nav ul{
width:auto;
list-style:none;
}
.nav ul li{
display:inline-block;
}
.nav ul li a{
text-decoration:none;
text-align:center;
color:#222;
display:block;
width:120px;
line-height:30px;
background-color:gray;
}
.nav ul li a:hover{
background-color:#EEC;
}
.nav ul li ul{
margin-top:0px;
padding-left:0px;
position:absolute;
display:none;
}
.nav ul li:hover ul{
display:block;
}
.nav ul li ul li{
display:block;
}
.nav ul li ul li ul{
margin-left:100%;
margin-top:-30px;
visibility:hidden;
}
.nav ul li ul li:hover ul{
margin-left:100%;
visibility:visible;
}
It is clear from the error.
The HtmlHelpers appended with "For" expects lambda expression as a parameter.
If you are passing the value directly, better use Normal one.
e.g.
Instead of TextboxFor(....) use Textbox()
syntax for TextboxFor will be like Html.TextBoxFor(m=>m.Property)
In your scenario you can use basic for loop, as it will give you index to use.
@for(int i=0;i<Model.Theme.Count;i++)
{
@Html.LabelFor(m=>m.Theme[i].name)
@for(int j=0;j<Model.Theme[i].Products.Count;j++) )
{
@Html.LabelFor(m=>m.Theme[i].Products[j].name)
@for(int k=0;k<Model.Theme[i].Products[j].Orders.Count;k++)
{
@Html.TextBoxFor(m=>Model.Theme[i].Products[j].Orders[k].Quantity)
@Html.TextAreaFor(m=>Model.Theme[i].Products[j].Orders[k].Note)
@Html.EditorFor(m=>Model.Theme[i].Products[j].Orders[k].DateRequestedDeliveryFor)
}
}
}
As I needed something like this -without any plug-in- for script-generated checkboxes in a table... I ended up with this solution:
<!DOCTYPE html>
<html>
<body>
Toto <input type="checkbox" id="myCheck1" onclick="updateChkBx(this)" /><br />
Tutu <input type="checkbox" id="myCheck2" onclick="updateChkBx(this)" /><br />
Tata <input type="checkbox" id="myCheck3" onclick="updateChkBx(this)" /><br />
Tete <input type="checkbox" id="myCheck4" onclick="updateChkBx(this)" /><br />
<script>
var chkBoxState = [];
function updateChkBx(src) {
var idx = Number(src.id.substring(7)); // 7 to bypass the "myCheck" part in each checkbox id
if(typeof chkBoxState[idx] == "undefined") chkBoxState[idx] = false; // make sure we can use stored state at first call
// the problem comes from a click on a checkbox both toggles checked attribute and turns inderminate attribute to false
if(chkBoxState[idx]) {
src.indeterminate = false;
src.checked = false;
chkBoxState[idx] = false;
}
else if (!src.checked) { // passing from checked to unchecked
src.indeterminate = true;
src.checked = true; // force considering we are in a checked state
chkBoxState[idx] = true;
}
}
// to know box state, just test indeterminate, and if not indeterminate, test checked
</script>
</body>
</html>
var cors = new EnableCorsAttribute("*","*","*");
config.EnableCors(cors);
var constraints = new {httpMethod = new HttpMethodConstraint(HttpMethod.Options)};
config.Routes.IgnoreRoute("OPTIONS", "*pathInfo",constraints);
You can try with this:
WITH CTE_A As (SELECT COUNT(*) as articleNumber,A.UserID as UserID FROM Articles A
Inner Join Users U
on A.userId = U.userId
Group By A.userId , U.userId ),
B as (Select us.registrationDate,
CASE
WHEN CTE_A.articleNumber < 2 THEN 'Ama'
WHEN CTE_A.articleNumber < 5 THEN 'SemiAma'
WHEN CTE_A.articleNumber < 7 THEN 'Good'
WHEN CTE_A.articleNumber < 9 THEN 'Better'
WHEN CTE_A.articleNumber < 12 THEN 'Best'
ELSE 'Outstanding'
END as Ranking,
us.hobbies, etc...
FROM USERS Us Inner Join CTE_A
on CTE_A.UserID=us.UserID)
Select * from B
There are plenty of examples of this which can be found via Google
However, users can turn off Javascript to stop this highly annoying "feature". I think you should really think about this before implementing it. It isn't really going to protect your content (if that is what you are trying achieve).
There is an article here that illustrates just how annoying and pointless it is.
In my experience, to use wmic
in a script, you need to get the nested quoting right:
wmic product where "name = 'Windows Azure Authoring Tools - v2.3'" call uninstall /nointeractive
quoting both the query and the name. But wmic will only uninstall things installed via windows installer.
The <select>
element does support the required
attribute, as per the spec:
Which browser doesn’t honour this?
(Of course, you have to validate on the server anyway, as you can’t guarantee that users will have JavaScript enabled.)
Date td = new Date();
String b = new String("");
SimpleDateFormat format = new SimpleDateFormat("YYYY/MM/dd");
b = format.format(td);
out.println(b);
Try to avoid using null
in Scala. It's really there only for interoperability with Java. In Scala, use Option
for things that might be empty. If you're calling a Java API method that might return null
, wrap it in an Option
immediately.
def getObject : Option[QueueObject] = {
// Wrap the Java result in an Option (this will become a Some or a None)
Option(someJavaObject.getResponse)
}
Note: You don't need to put it in a val
or use an explicit
return
statement in Scala; the result will be the value of
the last expression in the block (in fact, since there's only one statement, you don't even need a block).
def getObject : Option[QueueObject] = Option(someJavaObject.getResponse)
Besides what the others have already shown (for example calling foreach
on the Option
, which might be slightly confusing), you could also call map
on it (and ignore the result of the map operation if you don't need it):
getObject map QueueManager.add
This will do nothing if the Option
is a None
, and call QueueManager.add
if it is a Some
.
I find using a regular if
however clearer and simpler than using any of these "tricks" just to avoid an indentation level. You could also just write it on one line:
if (getObject.isDefined) QueueManager.add(getObject.get)
or, if you want to deal with null
instead of using Option
:
if (getObject != null) QueueManager.add(getObject)
edit - Ben is right, be careful to not call getObject
more than once if it has side-effects; better write it like this:
val result = getObject
if (result.isDefined) QueueManager.add(result.get)
or:
val result = getObject
if (result != null) QueueManager.add(result)
This is a message for me in the future:
Just use: (unsigned)!((int)0)
It creates the largest possible number in any machine by assigning all bits to 1s (ones) and then casts it to unsigned
Even better
#define INF (unsigned)!((int)0)
And then just use INF in your code
The API was designed to support a solution that matches closely to business requirements
import static java.time.temporal.TemporalAdjusters.*;
LocalDate initial = LocalDate.of(2014, 2, 13);
LocalDate start = initial.with(firstDayOfMonth());
LocalDate end = initial.with(lastDayOfMonth());
However, Jon's solutions are also fine.
Below function can be used to check for a value in any level in a JSON
function _isContains(json, value) {
let contains = false;
Object.keys(json).some(key => {
contains = typeof json[key] === 'object' ? _isContains(json[key], value) : json[key] === value;
return contains;
});
return contains;
}
then to check if JSON contains the value
_isContains(JSONObject, "dog")
See this fiddle: https://jsfiddle.net/ponmudi/uykaacLw/
Most of the answers mentioned here compares by 'name' key. But no need to care about the key, can just checks if JSON contains the given value. So that the function can be used to find any value irrespective of the key.
put this line in parent construct : $this->load->database();
function __construct() {
parent::__construct();
$this->load->library('lib_name');
$model=array('model_name');
$this->load->model($model);
$this->load->database();
}
this way.. it should work..
I cross over the same problem
I put the following code in the folder ~/.gvimrc
and it works.
set guifont=Monaco:h20
Use np.where
to get the indices where a given condition is True
.
Examples:
For a 2D np.ndarray
called a
:
i, j = np.where(a == value) # when comparing arrays of integers
i, j = np.where(np.isclose(a, value)) # when comparing floating-point arrays
For a 1D array:
i, = np.where(a == value) # integers
i, = np.where(np.isclose(a, value)) # floating-point
Note that this also works for conditions like >=
, <=
, !=
and so forth...
You can also create a subclass of np.ndarray
with an index()
method:
class myarray(np.ndarray):
def __new__(cls, *args, **kwargs):
return np.array(*args, **kwargs).view(myarray)
def index(self, value):
return np.where(self == value)
Testing:
a = myarray([1,2,3,4,4,4,5,6,4,4,4])
a.index(4)
#(array([ 3, 4, 5, 8, 9, 10]),)
I believe Quassnoi has answered your direct question. Just a side note: Maybe this is just some awkward wording on your part, but you seem to be under the impression that you have three primary keys, one on each field. This is not the case. By definition, you can only have one primary key. What you have here is a primary key that is a composite of three fields. Thus, you cannot "drop the primary key on a column". You can drop the primary key, or not drop the primary key. If you want a primary key that only includes one column, you can drop the existing primary key on 3 columns and create a new primary key on 1 column.
SELECT
category,
COUNT(*) AS `num`
FROM
posts
GROUP BY
category
The reason i could not delete some of the users via 'drop' statement was that there is a bug in Mysql http://bugs.mysql.com/bug.php?id=62255 with hostname containing upper case letters. The solution was running following query:
DELETE FROM mysql.user where host='Some_Host_With_UpperCase_Letters';
I am still trying to figure the other issue where the root user with all permissions are unable to grant privileges to new user for particular database
Yes, but when argument matching for a reference, the implicit array to pointer isn't automatic, so you need something like:
void foo( double (&array)[42] );
or
void foo( double (&array)[] );
Be aware, however, that when matching, double [42]
and double []
are
distinct types. If you have an array of an unknown dimension, it will
match the second, but not the first, and if you have an array with 42
elements, it will match the first but not the second. (The latter is,
IMHO, very counter-intuitive.)
In the second case, you'll also have to pass the dimension, since there's no way to recover it once you're inside the function.
Following link may help you http://angrytools.com/gradient/ .This will create custom gradient background in android as like in photoshop.
You may checkout this library for the same purpose also:
http://angular-route-segment.com
It looks like what you are looking for, and it is much simpler to use than ui-router. From the demo site:
JS:
$routeSegmentProvider.
when('/section1', 's1.home').
when('/section1/:id', 's1.itemInfo.overview').
when('/section2', 's2').
segment('s1', {
templateUrl: 'templates/section1.html',
controller: MainCtrl}).
within().
segment('home', {
templateUrl: 'templates/section1/home.html'}).
segment('itemInfo', {
templateUrl: 'templates/section1/item.html',
controller: Section1ItemCtrl,
dependencies: ['id']}).
within().
segment('overview', {
templateUrl: 'templates/section1/item/overview.html'}).
Top-level HTML:
<ul>
<li ng-class="{active: $routeSegment.startsWith('s1')}">
<a href="/section1">Section 1</a>
</li>
<li ng-class="{active: $routeSegment.startsWith('s2')}">
<a href="/section2">Section 2</a>
</li>
</ul>
<div id="contents" app-view-segment="0"></div>
Nested HTML:
<h4>Section 1</h4>
Section 1 contents.
<div app-view-segment="1"></div>
If both "document.ready" variants are used they will both fire, in the order of appearance
$(function(){
alert('shorthand document.ready');
});
//try changing places
$(document).ready(function(){
alert('document.ready');
});
If you want to do it with a Windows Store App, following by @Hans Kesting and @Jink answer:
string colorcode = "#FFEEDDCC";
int argb = Int32.Parse(colorcode.Replace("#", ""), NumberStyles.HexNumber);
tData.DefaultData = Color.FromArgb((byte)((argb & -16777216) >> 0x18),
(byte)((argb & 0xff0000) >> 0x10),
(byte)((argb & 0xff00) >> 8),
(byte)(argb & 0xff));
This error was caused for me because of the path where my project was located. There was a blank space in one folder, for example,
Folder\Another Folder\MyAndroidProjects\...
Changing it to Folder\AnotherFolder\MyAndroidProjects\...
and resynchronising Gradle resolved this for me.
Use encodeURIComponent()
to encode the string.
Eg.:
var product_list = encodeURIComponent(JSON.stringify(product_list));
You don't need to decode it since the web server automatically do the same.
Use the following to evaluate an expression (constant 0 evaluates to false).
#if 0
...
#endif
assuming all keys are always present in all dicts:
ds = [d1, d2]
d = {}
for k in d1.iterkeys():
d[k] = tuple(d[k] for d in ds)
Note: In Python 3.x use below code:
ds = [d1, d2]
d = {}
for k in d1.keys():
d[k] = tuple(d[k] for d in ds)
and if the dic contain numpy arrays:
ds = [d1, d2]
d = {}
for k in d1.keys():
d[k] = np.concatenate(list(d[k] for d in ds))
Extending @Ryogi answer above, you can take advantage of the lower.tail
parameter like so:
qt(0.25/2, 40, lower.tail = FALSE)
# 75% confidence
qt(0.01/2, 40, lower.tail = FALSE)
# 99% confidence
For App Engine in 2019, googles has made it easier to set up a custom domain.
Google App Engine -> Settings -> Custom Domains
Reminder: Use TXT Record with the value Google provides without a existing CNAME record, otherwise TXT Record will be override
I have come to this question and the one below several times.
how to call scalar function in sql server 2008
Each time, I try entering the Function using the syntax shown here in SQL Server Management Studio, or SSMS, to see the results, and each time I get the errors.
For me, that is because my result set is in tabular data format. Therefore, to see the results in SSMS, I have to call it like this:
SELECT * FROM dbo.Afisho_rankimin_TABLE(5);
I understand that the author's question involved a scalar function, so this answer is only to help others who come to StackOverflow often when they have a problem with a query (like me).
I hope this helps others.
You can check out this post on SuperUser.
Word starts page numbering over for each new section by default.
I do it slightly differently than the post above that goes through the ribbon menus, but in both methods you have to go through the document to each section's beginning.
My method:
Format Page Numbers
Continue from Previous Section
radio button under Page numbering
I find this right-click method to be a little faster. Also, usually if I insert the page numbers first before I start making any new sections, this problem doesn't happen in the first place.
Maybe you can try this:
void foo(const char* str)
{
// Do something
}
foo("Hello")
It works for me
For just reading the last element of a slice:
sl[len(sl)-1]
For removing it:
sl = sl[:len(sl)-1]
See this page about slice tricks
Here's a great method I recently found on a different stack overflow post regarding multi-dimensional arrays, but the answer works beautifully for single dimensional arrays as well:
# Create an 8 x 5 matrix of 0's:
w, h = 8, 5;
MyMatrix = [ [0 for x in range( w )] for y in range( h ) ]
# Create an array of objects:
MyList = [ {} for x in range( n ) ]
I love this because you can specify the contents and size dynamically, in one line!
One more for the road:
# Dynamic content initialization:
MyFunkyArray = [ x * a + b for x in range ( n ) ]
Lets start with 3. That wouldnt work. public getMyProperty()
has no return typ.
And number 1 and 2 are actually same things. 2 is what number 1 becomes after compilation.
So 1 and 2 are same things. with two you can have some validation or caching in your model.
other than that they become same.
In addition to what provided in the other answers, the keyword "zorder" allows one to decide the order in which different objects are plotted vertically. E.g.:
plt.plot(x,y,zorder=1)
plt.scatter(x,y,zorder=2)
plots the scatter symbols on top of the line, while
plt.plot(x,y,zorder=2)
plt.scatter(x,y,zorder=1)
plots the line over the scatter symbols.
See, e.g., the zorder demo
I'm surprised no one mentioned the implicit style above. My preference is to use parens to wrap the string while lining the string lines up visually. Personally I think this looks cleaner and more compact than starting the beginning of the string on a tabbed new line.
Note that these parens are not part of a method call — they're only implicit string literal concatenation.
Python 2:
def fun():
print ('{0} Here is a really '
'long sentence with {1}').format(3, 5)
Python 3 (with parens for print function):
def fun():
print(('{0} Here is a really '
'long sentence with {1}').format(3, 5))
Personally I think it's cleanest to separate concatenating the long string literal from printing it:
def fun():
s = ('{0} Here is a really '
'long sentence with {1}').format(3, 5)
print(s)
For reference from SQL Server 2016 SP1+
you could use CREATE OR ALTER VIEW
syntax.
CREATE [ OR ALTER ] VIEW [ schema_name . ] view_name [ (column [ ,...n ] ) ] [ WITH <view_attribute> [ ,...n ] ] AS select_statement [ WITH CHECK OPTION ] [ ; ]
OR ALTER
Conditionally alters the view only if it already exists.
The following does not return a response:
You must return anything like return afunction()
or return 'a string'
.
This can solve the issue
Adding this piece of code after the val() seems to work:
$(":input#single").trigger('change');
Same principle as the solutions above. But I had issues with Firefox 52.0 (32 bit) where large files (>40 MBytes) are truncated at random positions. Re-scheduling the call of revokeObjectUrl() fixes this issue.
function saveFile(blob, filename) {
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, filename);
} else {
const a = document.createElement('a');
document.body.appendChild(a);
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = filename;
a.click();
setTimeout(() => {
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
}, 0)
}
}
ln -s /mnt/usr/lib/* /usr/lib/
This is working code:
<html>
<body bgcolor=cyan>
<img src ="backgr1.JPG" id="my" width="310" height="392" style="position: absolute; top:92px; left:375px; visibility:hidden"/>
<script type="text/javascript">
function tend() {
document.getElementById('my').style.visibility='visible';
}
function tn() {
document.getElementById('my').style.visibility='hidden';
}
</script>
<input type="button" onclick="tend()" value="back">
<input type="button" onclick="tn()" value="close">
</body>
</html>
This code example that follows shows a basic UILabel
configuration.
let lbl = UILabel(frame: CGRectMake(0, 0, 300, 200))
lbl.text = "yourString"
// Enum type, two variations:
lbl.textAlignment = NSTextAlignment.Right
lbl.textAlignment = .Right
lbl.textColor = UIColor.red
lbl.shadowColor = UIColor.black
lbl.font = UIFont(name: "HelveticaNeue", size: CGFloat(22))
self.view.addSubview(lbl)
This can be caused by not using the same version clients all over.
Using a version 1.5 client and a version 1.6 client towards the same repository can create this kind of problem. (I was just bitten myself.)
As suggested by @The Berga You can add android:layoutDirection="rtl"
but it's only available with API 17.
for dynamic implementation, here it goes
chkBox.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
This error is caused when you have enabled paging in Grid view. If you want to delete a record from grid then you have to do something like this.
int index = Convert.ToInt32(e.CommandArgument);
int i = index % 20;
// Here 20 is my GridView's Page Size.
GridViewRow row = gvMainGrid.Rows[i];
int id = Convert.ToInt32(gvMainGrid.DataKeys[i].Value);
new GetData().DeleteRecord(id);
GridView1.DataSource = RefreshGrid();
GridView1.DataBind();
Hope this answers the question.
To move a file or set of files using Tortoise SVN
, right-click-and-drag the target files to their destination and release the right mouse button. The popup menu will have a SVN move versioned files here
option.
Note that the destination folder must have already been added to the repository for the SVN move versioned files here
option to appear.
Use of this directive mitigates the possibility of denial of service attacks which use hash collisions. If there are more input variables than specified by this directive, an E_WARNING is issued, and further input variables are truncated from the request.
I can suggest not to extend the default value which is 1000 and extend the application functionality by serialising the request or send the request by blocks. Otherwise, you can extend this to configuration needed.
It definitely needs to set up in the php.ini
The accepted answer here indeed makes a json from a form, but the json contents is really a string with url-encoded contents.
To make a more realistic json POST, use some solution from Serialize form data to JSON to make formToJson
function and add contentType: 'application/json;charset=UTF-8'
to the jQuery ajax call parameters.
$.ajax({
url: 'test.php',
type: "POST",
dataType: 'json',
data: formToJson($("form")),
contentType: 'application/json;charset=UTF-8',
...
})
For Apache 2.4, you would use the Require IP directive. So to only allow machines from the 192.168.0.0/24 network (range 192.168.0.0 - 192.168.0.255)
<VirtualHost *:80>
<Location />
Require ip 192.168.0.0/24
</Location>
...
</VirtualHost>
And if you just want the localhost machine to have access, then there's a special Require local directive.
The local provider allows access to the server if any of the following conditions is true:
- the client address matches 127.0.0.0/8
- the client address is ::1
- both the client and the server address of the connection are the same
This allows a convenient way to match connections that originate from the local host:
<VirtualHost *:80>
<Location />
Require local
</Location>
...
</VirtualHost>
Not sure if helpful, but I leave my solution here:
class Solution:
# @param A : string
# @param B : string
# @return a strings
def addBinary(self, A, B):
num1 = bin(int(A, 2))
num2 = bin(int(B, 2))
bin_str = bin(int(num1, 2)+int(num2, 2))
b_index = bin_str.index('b')
return bin_str[b_index+1:]
s = Solution()
print(s.addBinary("11", "100"))
I ran into a similar issue when migrating from babel 5 to babel 6.
I was just running babel to compile the src to lib folder babel src --out-dir lib
I will share my setup for babel 6:
Ensure you have the following babel 6 devDependencies installed
"babel-core": "^6.7.6",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.5.0",
"babel-preset-stage-0": "^6.5.0"
Add your .babelrc file to the project:
{
"presets": ["es2015", "stage-0", "react"]
}
Here is Xamarin.Android
version:
From @Jason Robinson's answer:
Bitmap rotate(Bitmap bitmap, int angle)
{
var matrix = new Matrix();
matrix.PostRotate(angle);
return Bitmap.CreateBitmap(bitmap, 0, 0, bitmap.Width, bitmap.Height, matrix, true);
}
Bitmap rotateIfRequired(Bitmap bitmap, string imagePath)
{
var ei = new ExifInterface(imagePath);
var orientation = ei.GetAttributeInt(ExifInterface.TagOrientation, (int)Android.Media.Orientation.Undefined);
switch (orientation)
{
case (int)Android.Media.Orientation.Rotate90: return rotate(bitmap, 90);
case (int)Android.Media.Orientation.Rotate180: return rotate(bitmap, 180);
case (int)Android.Media.Orientation.Rotate270: return rotate(bitmap, 270);
default: return bitmap;
}
}
Then calculateInSampleSize
method:
int calculateInSampleSize(BitmapFactory.Options options, int reqW, int reqH)
{
float h = options.OutHeight;
float w = options.OutWidth;
var inSampleSize = 1;
if (h > reqH || w > reqW)
{
if (reqH == 0) inSampleSize = (int)Math.Floor(w / reqW);
else if (reqW == 0) inSampleSize = (int)Math.Floor(h / reqH);
else
{
var hRatio = (int)Math.Floor(h / reqH);
var wRatio = (int)Math.Floor(w / reqW);
inSampleSize = false ? Math.Max(hRatio, wRatio) : Math.Min(hRatio, wRatio);
}
}
return inSampleSize;
}
From @Sami Eltamawy's answer:
Bitmap handleSamplingAndRotationBitmap(string imagePath)
{
var maxHeight = 1024;
var maxWidth = 1024;
var options = new BitmapFactory.Options();
options.InJustDecodeBounds = true;
BitmapFactory.DecodeFile(imagePath, options);
options.InSampleSize = calculateInSampleSize(options, maxWidth, maxHeight);
options.InJustDecodeBounds = false;
var bitmap = BitmapFactory.DecodeFile(imagePath, options);
bitmap = rotateIfRequired(bitmap, imagePath);
return bitmap;
}
I solved this problem with custom annotations. This is my "SkipSerialisation" Annotation class:
@Target (ElementType.FIELD)
public @interface SkipSerialisation {
}
and this is my GsonBuilder:
gsonBuilder.addSerializationExclusionStrategy(new ExclusionStrategy() {
@Override public boolean shouldSkipField (FieldAttributes f) {
return f.getAnnotation(SkipSerialisation.class) != null;
}
@Override public boolean shouldSkipClass (Class<?> clazz) {
return false;
}
});
Example :
public class User implements Serializable {
public String firstName;
public String lastName;
@SkipSerialisation
public String email;
}
Package organization or package structuring is usually a heated discussion. Below are some simple guidelines for package naming and structuring:
com.company.product.modulea
com.company.product.module.web
or com.company.product.module.util
etc.com.company.product.model
and com.company.product.util
, etc.After a few experiments and trials you should be able to come up with a structuring that you are comfortable with. Don't be fixated on one convention, be open to changes.
Just put this code in KeyTyped event:
if ((jtextField.getText() + evt.getKeyChar()).length() > 20) {
evt.consume();
}
Where "20" is the maximum number of characters that you want.
When you press back and then you finish your current activity(say A), you see a blank activity with your app logo(say B), this simply means that activity B which is shown after finishing A is still in backstack, and also activity A was started from activity B, so in activity, You should start activity A with flags as
Intent launchNextActivity;
launchNextActivity = new Intent(B.class, A.class);
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(launchNextActivity);
Now your activity A is top on stack with no other activities of your application on the backstack.
Now in the activity A where you want to implement onBackPressed to close the app, you may do something like this,
private Boolean exit = false;
@Override
public void onBackPressed() {
if (exit) {
finish(); // finish activity
} else {
Toast.makeText(this, "Press Back again to Exit.",
Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
exit = false;
}
}, 3 * 1000);
}
}
The Handler here handles accidental back presses, it simply shows a Toast
, and if there is another back press within 3 seconds, it closes the application.
A few considerations on the subject:
The parenthesis:
The browser (engine/parser) associates the keyword function with
[optional name]([optional parameters]){...code...}
So in an expression like function(){}() the last parenthesis makes no sense.
Now think at
name=function(){} ; name() !?
Yes, the first pair of parenthesis force the anonymous function to turn into a variable (stored expression) and the second launches evaluation/execution, so ( function(){} )() makes sense.
The utility: ?
For executing some code on load and isolate the used variables from the rest of the page especially when name conflicts are possible;
Replace eval("string") with
(new Function("string"))()
Wrap long code for " =?: " operator like:
result = exp_to_test ? (function(){... long_code ...})() : (function(){...})();
in "String.xml" you can notice any String or value you want to use, here are two examples:
<string name="app_name">My Calculator App
</string>
<color name="color_menu_home">#ffcccccc</color>
Used for the layout.xml: android:text="@string/app_name"
The advantage: you can use them as often you want, you only need to link them in your Layout-xml, and you can change the String-Content easily in the strings.xml, without searching in your source-code for the right position. Important for changing language, you only need to replace the strings.xml - file
@using (Html.BeginForm()) {
<p>Do you like pizza?
@Html.DropDownListFor(x => x.likesPizza, new[] {
new SelectListItem() {Text = "Yes", Value = bool.TrueString},
new SelectListItem() {Text = "No", Value = bool.FalseString}
}, "Choose an option")
</p>
<input type = "submit" value = "Submit my answer" />
}
I think this answer is similar to Berat's, in that you put all the code for your DropDownList directly in the view. But I think this is an efficient way of creating a y/n (boolean) drop down list, so I wanted to share it.
Some notes for beginners:
Hope this helps someone,
You can find the number of members in a Javascript array by using its length
property:
var number = $scope.names.length;
Docs - Array.prototype.length
Doing password checks on client side is unsafe especially when the password is hard coded.
The safest way is password checking on server side, but even then the password should not be transmitted plain text.
Checking the password client side is possible in a "secure way":
Say "abc" is your password so your md5 would be "900150983cd24fb0d6963f7d28e17f72" (consider salting!). Now build a url containing the hash (like http://yourdomain.com/90015...f72.html).
Just in case anybody else lands here from Google, I was bitten by this error message when using XDocument.Load(Stream) method.
XDocument xDoc = XDocument.Load(xmlStream);
Make sure the stream position is set to 0 (zero) before you try and load the Stream, its an easy mistake I always overlook!
if (xmlStream.Position > 0)
{
xmlStream.Position = 0;
}
XDocument xDoc = XDocument.Load(xmlStream);
In my case there was missing <RestorePackages>true</RestorePackages>
in *.csproj file. It was not necessary to delete snippets of code I see in previous answers.
You'll want something like this:
$("#next").click(function(){
var currentElement = currentElement.next();
$('html, body').animate({scrollLeft: $(currentElement).offset().left}, 800);
return false;
});
I believe this should work, it's adopted from a scrollTop
function.
No, no, no.
These answers are all wrong. There is a fundamental absence of knowledge in your brain that I'm going to remedy right now.
Your major issue here is your naming scheme. It's verbose, contains undesirable characters, and is horribly inconsistent.
First: A table that is called Salesperson
does not need to have each field in the table called Salesperson.Salesperson number
, Salesperson.Salesperson email
. You're already in the table Salesperson
. Everything in this table relates to Salesperson
. You don't have to keep saying it.
Instead use ID
, Email
. Don't use Number
because that's probably a reserved word. Do you really endeavour to type [] around every field name for the lifespan of your database?
Primary keys on a table called Student
can either be ID
or StudentID
but be consistent. Foreign keys should only be named by the table it points to followed by ID
. For example: Student.ID
and Appointment.StudentID
. ID
is always capitalized. I don't care if your IDE tells you not to because everywhere but your IDE will be ID
. Even Access likes ID
.
Second: Name all your fields without spaces or special characters and keep them as short as possible and if they conflict with a reserved word, find another word.
Instead of: phone number
use PhoneNumber
or even better, simply, Phone
. If you choose what time user made the withdrawal
, you're going to have to type that in every single time.
Third: And this one is the most important one: Always be consistent in whatever naming scheme you choose. You should be able to say, "I need the postal code from that table; its name is going to be PostalCode." You should know that without even having to look it up because you were consistent in your naming convention.
Recap: Terse, not verbose. Keep names short with no spaces, don't repeat the table name, don't use reserved words, and capitalize each word. Above all, be consistent.
I hope you take my advice. This is the right way to do it. My answer is the right one. You should be extremely pedantic with your naming scheme to the point of absolute obsession for the rest of your lives on this planet.
NOTE:You actually have to change the field name in the design view of the table and in the query.
I use the following folder structure:
application
system
static
admin
js
css
images
public
js
css
images
uploads
original
thumbs
&
, |
and ~
, and parentheses (...)
is important!Python's and
, or
and not
logical operators are designed to work with scalars. So Pandas had to do one better and override the bitwise operators to achieve vectorized (element-wise) version of this functionality.
So the following in python (exp1
and exp2
are expressions which evaluate to a boolean result)...
exp1 and exp2 # Logical AND
exp1 or exp2 # Logical OR
not exp1 # Logical NOT
...will translate to...
exp1 & exp2 # Element-wise logical AND
exp1 | exp2 # Element-wise logical OR
~exp1 # Element-wise logical NOT
for pandas.
If in the process of performing logical operation you get a ValueError
, then you need to use parentheses for grouping:
(exp1) op (exp2)
For example,
(df['col1'] == x) & (df['col2'] == y)
And so on.
Boolean Indexing: A common operation is to compute boolean masks through logical conditions to filter the data. Pandas provides three operators: &
for logical AND, |
for logical OR, and ~
for logical NOT.
Consider the following setup:
np.random.seed(0)
df = pd.DataFrame(np.random.choice(10, (5, 3)), columns=list('ABC'))
df
A B C
0 5 0 3
1 3 7 9
2 3 5 2
3 4 7 6
4 8 8 1
For df
above, say you'd like to return all rows where A < 5 and B > 5. This is done by computing masks for each condition separately, and ANDing them.
Overloaded Bitwise &
Operator
Before continuing, please take note of this particular excerpt of the docs, which state
Another common operation is the use of boolean vectors to filter the data. The operators are:
|
foror
,&
forand
, and~
fornot
. These must be grouped by using parentheses, since by default Python will evaluate an expression such asdf.A > 2 & df.B < 3
asdf.A > (2 & df.B) < 3
, while the desired evaluation order is(df.A > 2) & (df.B < 3)
.
So, with this in mind, element wise logical AND can be implemented with the bitwise operator &
:
df['A'] < 5
0 False
1 True
2 True
3 True
4 False
Name: A, dtype: bool
df['B'] > 5
0 False
1 True
2 False
3 True
4 True
Name: B, dtype: bool
(df['A'] < 5) & (df['B'] > 5)
0 False
1 True
2 False
3 True
4 False
dtype: bool
And the subsequent filtering step is simply,
df[(df['A'] < 5) & (df['B'] > 5)]
A B C
1 3 7 9
3 4 7 6
The parentheses are used to override the default precedence order of bitwise operators, which have higher precedence over the conditional operators <
and >
. See the section of Operator Precedence in the python docs.
If you do not use parentheses, the expression is evaluated incorrectly. For example, if you accidentally attempt something such as
df['A'] < 5 & df['B'] > 5
It is parsed as
df['A'] < (5 & df['B']) > 5
Which becomes,
df['A'] < something_you_dont_want > 5
Which becomes (see the python docs on chained operator comparison),
(df['A'] < something_you_dont_want) and (something_you_dont_want > 5)
Which becomes,
# Both operands are Series...
something_else_you_dont_want1 and something_else_you_dont_want2
Which throws
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
So, don't make that mistake!1
Avoiding Parentheses Grouping
The fix is actually quite simple. Most operators have a corresponding bound method for DataFrames. If the individual masks are built up using functions instead of conditional operators, you will no longer need to group by parens to specify evaluation order:
df['A'].lt(5)
0 True
1 True
2 True
3 True
4 False
Name: A, dtype: bool
df['B'].gt(5)
0 False
1 True
2 False
3 True
4 True
Name: B, dtype: bool
df['A'].lt(5) & df['B'].gt(5)
0 False
1 True
2 False
3 True
4 False
dtype: bool
See the section on Flexible Comparisons.. To summarise, we have
+------------------------------+
¦ ¦ Operator ¦ Function ¦
¦----+------------+------------¦
¦ 0 ¦ > ¦ gt ¦
+----+------------+------------¦
¦ 1 ¦ >= ¦ ge ¦
+----+------------+------------¦
¦ 2 ¦ < ¦ lt ¦
+----+------------+------------¦
¦ 3 ¦ <= ¦ le ¦
+----+------------+------------¦
¦ 4 ¦ == ¦ eq ¦
+----+------------+------------¦
¦ 5 ¦ != ¦ ne ¦
+------------------------------+
Another option for avoiding parentheses is to use DataFrame.query
(or eval
):
df.query('A < 5 and B > 5')
A B C
1 3 7 9
3 4 7 6
I have extensively documented query
and eval
in Dynamic Expression Evaluation in pandas using pd.eval().
operator.and_
Allows you to perform this operation in a functional manner. Internally calls Series.__and__
which corresponds to the bitwise operator.
import operator
operator.and_(df['A'] < 5, df['B'] > 5)
# Same as,
# (df['A'] < 5).__and__(df['B'] > 5)
0 False
1 True
2 False
3 True
4 False
dtype: bool
df[operator.and_(df['A'] < 5, df['B'] > 5)]
A B C
1 3 7 9
3 4 7 6
You won't usually need this, but it is useful to know.
Generalizing: np.logical_and
(and logical_and.reduce
)
Another alternative is using np.logical_and
, which also does not need parentheses grouping:
np.logical_and(df['A'] < 5, df['B'] > 5)
0 False
1 True
2 False
3 True
4 False
Name: A, dtype: bool
df[np.logical_and(df['A'] < 5, df['B'] > 5)]
A B C
1 3 7 9
3 4 7 6
np.logical_and
is a ufunc (Universal Functions), and most ufuncs have a reduce
method. This means it is easier to generalise with logical_and
if you have multiple masks to AND. For example, to AND masks m1
and m2
and m3
with &
, you would have to do
m1 & m2 & m3
However, an easier option is
np.logical_and.reduce([m1, m2, m3])
This is powerful, because it lets you build on top of this with more complex logic (for example, dynamically generating masks in a list comprehension and adding all of them):
import operator
cols = ['A', 'B']
ops = [np.less, np.greater]
values = [5, 5]
m = np.logical_and.reduce([op(df[c], v) for op, c, v in zip(ops, cols, values)])
m
# array([False, True, False, True, False])
df[m]
A B C
1 3 7 9
3 4 7 6
1 - I know I'm harping on this point, but please bear with me. This is a very, very common beginner's mistake, and must be explained very thoroughly.
For the df
above, say you'd like to return all rows where A == 3 or B == 7.
Overloaded Bitwise |
df['A'] == 3
0 False
1 True
2 True
3 False
4 False
Name: A, dtype: bool
df['B'] == 7
0 False
1 True
2 False
3 True
4 False
Name: B, dtype: bool
(df['A'] == 3) | (df['B'] == 7)
0 False
1 True
2 True
3 True
4 False
dtype: bool
df[(df['A'] == 3) | (df['B'] == 7)]
A B C
1 3 7 9
2 3 5 2
3 4 7 6
If you haven't yet, please also read the section on Logical AND above, all caveats apply here.
Alternatively, this operation can be specified with
df[df['A'].eq(3) | df['B'].eq(7)]
A B C
1 3 7 9
2 3 5 2
3 4 7 6
operator.or_
Calls Series.__or__
under the hood.
operator.or_(df['A'] == 3, df['B'] == 7)
# Same as,
# (df['A'] == 3).__or__(df['B'] == 7)
0 False
1 True
2 True
3 True
4 False
dtype: bool
df[operator.or_(df['A'] == 3, df['B'] == 7)]
A B C
1 3 7 9
2 3 5 2
3 4 7 6
np.logical_or
For two conditions, use logical_or
:
np.logical_or(df['A'] == 3, df['B'] == 7)
0 False
1 True
2 True
3 True
4 False
Name: A, dtype: bool
df[np.logical_or(df['A'] == 3, df['B'] == 7)]
A B C
1 3 7 9
2 3 5 2
3 4 7 6
For multiple masks, use logical_or.reduce
:
np.logical_or.reduce([df['A'] == 3, df['B'] == 7])
# array([False, True, True, True, False])
df[np.logical_or.reduce([df['A'] == 3, df['B'] == 7])]
A B C
1 3 7 9
2 3 5 2
3 4 7 6
Given a mask, such as
mask = pd.Series([True, True, False])
If you need to invert every boolean value (so that the end result is [False, False, True]
), then you can use any of the methods below.
Bitwise ~
~mask
0 False
1 False
2 True
dtype: bool
Again, expressions need to be parenthesised.
~(df['A'] == 3)
0 True
1 False
2 False
3 True
4 True
Name: A, dtype: bool
This internally calls
mask.__invert__()
0 False
1 False
2 True
dtype: bool
But don't use it directly.
operator.inv
Internally calls __invert__
on the Series.
operator.inv(mask)
0 False
1 False
2 True
dtype: bool
np.logical_not
This is the numpy variant.
np.logical_not(mask)
0 False
1 False
2 True
dtype: bool
Note, np.logical_and
can be substituted for np.bitwise_and
, logical_or
with bitwise_or
, and logical_not
with invert
.
You can remove the BOM using:
//Create a character to compare BOM
char byteOrderMark = (char)65279;
if (sourceString.ToCharArray()[0].Equals(byteOrderMark))
{
targetString = sourceString.Remove(0, 1);
}
.NET 4.5 is an in place replacement for 4.0 - you will find the assemblies in the 4.0 directory.
See the blogs by Rick Strahl and Scott Hanselman on this topic.
You can also find the specific versions in:
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework
Did you check the small Mousetrap library?
Mousetrap is a simple library for handling keyboard shortcuts in JavaScript.
For me, the following hack worked; Go to IIS -> Application Pools -> Advance Settings -> Process Model -> Identity Changed from Built-in Account (ApplicationPoolIdentity) to Custom Account (My Domain User)
Within your click
handler, the mistake is the .validate()
method; it only initializes the plugin, it does not validate the form
.
To eliminate the need to have a submit
button within the form
, use .valid()
to trigger a validation check...
$('#btn').on('click', function() {
$("#form1").valid();
});
.validate()
- to initialize the plugin (with options) once on DOM ready.
.valid()
- to check validation state (boolean value) or to trigger a validation test on the form
at any time.
Otherwise, if you had a type="submit"
button within the form
container, you would not need a special click
handler and the .valid()
method, as the plugin would capture that automatically.
EDIT:
You also have two issues within your HTML...
<input id="field1" type="text" class="required">
You don't need class="required"
when declaring rules within .validate()
. It's redundant and superfluous.
The name
attribute is missing. Rules are declared within .validate()
by their name
. The plugin depends upon unique name
attributes to keep track of the inputs.
Should be...
<input name="field1" id="field1" type="text" />
Logs rotate for a reason, so that you only keep so many log files around. In log4j.xml you can add this to your node:
<param name="MaxBackupIndex" value="20"/>
The value tells log4j.xml to only keep 20 rotated log files around. You can limit this to 5 if you want or even 1. If your application isn't logging that much data, and you have 20 log files spanning the last 8 months, but you only need a weeks worth of logs, then I think you need to tweak your log4j.xml "MaxBackupIndex" and "MaxFileSize" params.
Alternatively, if you are using a properties file (instead of the xml) and wish to save 15 files (for example)
log4j.appender.[appenderName].MaxBackupIndex = 15
Take a look at the FormBorderStyle property
form1.FormBorderStyle = FormBorderStyle.FixedSingle;
You may also want to remove the minimize and maximize buttons:
form1.MaximizeBox = false;
form1.MinimizeBox = false;
Here an answer for those who'd like to have preinitialized lists of lists. Needs Java 8+.
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
class Scratch {
public static void main(String[] args) {
int M = 4;
int N = 3;
// preinitialized array (== list of lists) of strings, sizes not fixed
List<List<String>> listOfListsOfString = initializeListOfListsOfT(M, N, "-");
System.out.println(listOfListsOfString);
// preinitialized array (== list of lists) of int (primitive type), sizes not fixed
List<List<Integer>> listOfListsOfInt = initializeListOfListsOfInt(M, N, 7);
System.out.println(listOfListsOfInt);
}
public static <T> List<List<T>> initializeListOfListsOfT(int m, int n, T initValue) {
return IntStream
.range(0, m)
.boxed()
.map(i -> new ArrayList<T>(IntStream
.range(0, n)
.boxed()
.map(j -> initValue)
.collect(Collectors.toList()))
)
.collect(Collectors.toList());
}
public static List<List<Integer>> initializeListOfListsOfInt(int m, int n, int initValue) {
return IntStream
.range(0, m)
.boxed()
.map(i -> new ArrayList<>(IntStream
.range(0, n)
.map(j -> initValue)
.boxed()
.collect(Collectors.toList()))
)
.collect(Collectors.toList());
}
}
Output:
[[-, -, -], [-, -, -], [-, -, -], [-, -, -]]
[[7, 7, 7], [7, 7, 7], [7, 7, 7], [7, 7, 7]]
Side note for those wondering about IntStream
:
IntStream
.range(0, m)
.boxed()
is equivalent to
Stream
.iterate(0, j -> j + 1)
.limit(n)
The sound of the french fou, (like: amour fou) [crazy] written in english, would be foo, wouldn't it. Else furchtbar -> foobar -> foo, bar -> barfoo -> barfuß (barefoot). Just fou. A foot without teeth.
I agree with all, who mentioned it means: nothing interesting, just something, usually needed to complete a statement/expression.