In html5 you can do using the full expression:
<select required="required">
I don't know why the short expression doesn't work, but try this one. It will solve.
Given a radius length r and an angle t in radians and a circle's center (h,k), you can calculate the coordinates of a point on the circumference as follows (this is pseudo-code, you'll have to adapt it to your language):
float x = r*cos(t) + h;
float y = r*sin(t) + k;
would this work? (leaving action blank submits form back to itself too, right?)
<form action="">
<select name="memberid" onchange="this.form.submit();">
<option value="1">member 1</option>
<option value="2">member 2</option>
</select>
"this" would be the select element, .form would be its parent form. Right?
//VC6.0 (386 & better)
__int64 my_qw_var = 0x1234567890abcdef;
__int32 v_dw_h;
__int32 v_dw_l;
__asm
{
mov eax,[dword ptr my_qw_var + 4] //dwh
mov [dword ptr v_dw_h],eax
mov eax,[dword ptr my_qw_var] //dwl
mov [dword ptr v_dw_l],eax
}
//Oops 0.8 format
printf("val = 0x%0.8x%0.8x\n", (__int32)v_dw_h, (__int32)v_dw_l);
Regards.
Given that you want a 100% client side solution, in theory you could probably do this:
Via XmlHttpRequest, get the directory listing page for that directory (most web servers return a listing of files if there is no index.html file in the directory).
Parse that file with javascript, pulling out all the .js files. This will of course be sensitive to the format of the directory listing on your web server / web host.
Add the script tags dynamically, with something like this:
function loadScript (dir, file) {
var scr = document.createElement("script");
scr.src = dir + file;
document.body.appendChild(scr);
}
One has exactly space for 11 bytes, the other for exactly 11 characters. Some charsets such as Unicode variants may use more than one byte per char, therefore the 11 byte field might have space for less than 11 chars depending on the encoding.
See also http://www.joelonsoftware.com/articles/Unicode.html
Sometimes, you need to list the variables of an object and not for debugging purposes. The right way to do it is using get_object_vars($object). It returns an array that has all the class variables and their value. You can then loop through them in a foreach loop. If used within the object itself, simply do get_object_vars($this)
An ioctl
, which means "input-output control" is a kind of device-specific system call. There are only a few system calls in Linux (300-400), which are not enough to express all the unique functions devices may have. So a driver can define an ioctl which allows a userspace application to send it orders. However, ioctls are not very flexible and tend to get a bit cluttered (dozens of "magic numbers" which just work... or not), and can also be insecure, as you pass a buffer into the kernel - bad handling can break things easily.
An alternative is the sysfs
interface, where you set up a file under /sys/
and read/write that to get information from and to the driver. An example of how to set this up:
static ssize_t mydrvr_version_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%s\n", DRIVER_RELEASE);
}
static DEVICE_ATTR(version, S_IRUGO, mydrvr_version_show, NULL);
And during driver setup:
device_create_file(dev, &dev_attr_version);
You would then have a file for your device in /sys/
, for example, /sys/block/myblk/version
for a block driver.
Another method for heavier use is netlink, which is an IPC (inter-process communication) method to talk to your driver over a BSD socket interface. This is used, for example, by the WiFi drivers. You then communicate with it from userspace using the libnl
or libnl3
libraries.
Uninstall the plugins first. And then try this. This uninstaller worked like a charm (I didn't even uninstall 2015 myself, it did everything on its own)!
We can also use logging to print data on the console.
Example:
import logging
from flask import Flask
app = Flask(__name__)
@app.route('/print')
def printMsg():
app.logger.warning('testing warning log')
app.logger.error('testing error log')
app.logger.info('testing info log')
return "Check your console"
if __name__ == '__main__':
app.run(debug=True)
Use \x
Example from postgres manual:
postgres=# \x
postgres=# SELECT * FROM pg_stat_statements ORDER BY total_time DESC LIMIT 3;
-[ RECORD 1 ]------------------------------------------------------------
userid | 10
dbid | 63781
query | UPDATE branches SET bbalance = bbalance + $1 WHERE bid = $2;
calls | 3000
total_time | 20.716706
rows | 3000
-[ RECORD 2 ]------------------------------------------------------------
userid | 10
dbid | 63781
query | UPDATE tellers SET tbalance = tbalance + $1 WHERE tid = $2;
calls | 3000
total_time | 17.1107649999999
rows | 3000
-[ RECORD 3 ]------------------------------------------------------------
userid | 10
dbid | 63781
query | UPDATE accounts SET abalance = abalance + $1 WHERE aid = $2;
calls | 3000
total_time | 0.645601
rows | 3000
You can use the .indexOf()
and .substring()
, like this:
var url = "www.aaa.com/task1/1.3.html#a_1";
var hash = url.substring(url.indexOf("#")+1);
You can give it a try here, if it may not have a #
in it, do an if(url.indexOf("#") != -1)
check like this:
var url = "www.aaa.com/task1/1.3.html#a_1", idx = url.indexOf("#");
var hash = idx != -1 ? url.substring(idx+1) : "";
If this is the current page URL, you can just use window.location.hash
to get it, and replace the #
if you wish.
This one works for me (use "Default" instead of "UTF8"):
$MyFile = Get-Content $MyPath
$MyFile | Out-File -Encoding "Default" $MyPath
The result is ASCII without BOM.
You can, but you should not https://web.archive.org/web/20151009224806/http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/
Each object in mongo already has an id, and they are sortable in insertion order. What is wrong with getting collection of user objects, iterating over it and use this as incremented ID? Er go for kind of map-reduce job entirely
MyClass
and YourClass
could both be derived from SomeonesClass
which has an abstract (virtual) Callback
method. Your addHandler
would accept objects of type SomeonesClass
and MyClass
and YourClass
can override Callback
to provide their specific implementation of callback behavior.
New in Chrome 50+ and Firefox 39+ (resp. 44+):
formdata.entries()
(combine with Array.from()
for debugability)formdata.get(key)
Original answer:
What I usually do to 'debug' a FormData
object, is just send it (anywhere!) and check the browser logs (eg. Chrome devtools' Network tab).
You don't need a/the same Ajax framework. You don't need any details. Just send it:
var xhr = new XMLHttpRequest;
xhr.open('POST', '/', true);
xhr.send(data);
Easy.
Check out your php.ini, you can set these values there.
Here's the description in the php manual: http://php.net/manual/en/mail.configuration.php
If you want to use several different SMTP servers in your application, I recommend using a "bigger" mailing framework, p.e. Swiftmailer
Objective-C code for copy Table from a Database to another Database
-(void) createCopyDatabase{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *maindbPath = [documentsDir stringByAppendingPathComponent:@"User.sqlite"];;
NSString *newdbPath = [documentsDir stringByAppendingPathComponent:@"User_copy.sqlite"];
NSFileManager *fileManager = [NSFileManager defaultManager];
char *error;
if ([fileManager fileExistsAtPath:newdbPath]) {
[fileManager removeItemAtPath:newdbPath error:nil];
}
sqlite3 *database;
//open database
if (sqlite3_open([newdbPath UTF8String], &database)!=SQLITE_OK) {
NSLog(@"Error to open database");
}
NSString *attachQuery = [NSString stringWithFormat:@"ATTACH DATABASE \"%@\" AS aDB",maindbPath];
sqlite3_exec(database, [attachQuery UTF8String], NULL, NULL, &error);
if (error) {
NSLog(@"Error to Attach = %s",error);
}
//Query for copy Table
NSString *sqlString = @"CREATE TABLE Info AS SELECT * FROM aDB.Info";
sqlite3_exec(database, [sqlString UTF8String], NULL, NULL, &error);
if (error) {
NSLog(@"Error to copy database = %s",error);
}
//Query for copy Table with Where Clause
sqlString = @"CREATE TABLE comments AS SELECT * FROM aDB.comments Where user_name = 'XYZ'";
sqlite3_exec(database, [sqlString UTF8String], NULL, NULL, &error);
if (error) {
NSLog(@"Error to copy database = %s",error);
}
}
My promisify version of a callback
function is the P
function:
var P = function() {_x000D_
var self = this;_x000D_
var method = arguments[0];_x000D_
var params = Array.prototype.slice.call(arguments, 1);_x000D_
return new Promise((resolve, reject) => {_x000D_
if (method && typeof(method) == 'function') {_x000D_
params.push(function(err, state) {_x000D_
if (!err) return resolve(state)_x000D_
else return reject(err);_x000D_
});_x000D_
method.apply(self, params);_x000D_
} else return reject(new Error('not a function'));_x000D_
});_x000D_
}_x000D_
var callback = function(par, callback) {_x000D_
var rnd = Math.floor(Math.random() * 2) + 1;_x000D_
return rnd > 1 ? callback(null, par) : callback(new Error("trap"));_x000D_
}_x000D_
_x000D_
callback("callback", (err, state) => err ? console.error(err) : console.log(state))_x000D_
callback("callback", (err, state) => err ? console.error(err) : console.log(state))_x000D_
callback("callback", (err, state) => err ? console.error(err) : console.log(state))_x000D_
callback("callback", (err, state) => err ? console.error(err) : console.log(state))_x000D_
_x000D_
P(callback, "promise").then(v => console.log(v)).catch(e => console.error(e))_x000D_
P(callback, "promise").then(v => console.log(v)).catch(e => console.error(e))_x000D_
P(callback, "promise").then(v => console.log(v)).catch(e => console.error(e))_x000D_
P(callback, "promise").then(v => console.log(v)).catch(e => console.error(e))
_x000D_
The P
function requires that the callback signature must be callback(error,result)
.
Hopefully people will find this answer as there are many, many posts about this on the web. Many people suggested it was an .htaccess problem, and for me it was. However, I had been looking in the .htaccess in the root, not in the .htaccess in the wp-admin folder. Normally, I work on this site in particular through terminal services, so when it booted me and I couldn't log back in, I was trying to access it from my home computer (and it's IP).
Silly me forgot the IP restriction I had placed in the wp-admin .htaccess file.
AuthName "Protected"
AuthType Basic
<Limit GET POST>
order deny,allow
deny from all
allow from 11.11.11.11
</Limit>
If you have something like this in your wp-admin .htaccess files, that would easily explain why all the sites you work on ceased to function at the same time. Internet providers occasionally rotate IPs so that nobody is running a server from home without paying for it.
you could utilize bootstrap events:: as
//when modal opens
$('#yourModal').on('shown.bs.modal', function (e) {
$("#pageContent").css({ opacity: 0.5 });
})
//when modal closes
$('#yourModal').on('hidden.bs.modal', function (e) {
$("#pageContent").css({ opacity: 1 });
})
I got the same error from having two references to different versions of jQuery.
In my master page:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
And also on the page:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script>
If your server certificated file is not trusted, (for example, you may generate the keystore by yourself with keytool command in java), you should add the extra option rejectUnauthorized
var socket = io.connect('https://localhost', {rejectUnauthorized: false});
Two ways:
use the argument -uno
to git-status
. Here's an example:
[jenny@jenny_vmware:ft]$ git status
# On branch ft
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
#
# foo
nothing added to commit but untracked files present (use "git add" to track)
[jenny@jenny_vmware:ft]$ git status -uno
# On branch ft
nothing to commit (working directory clean)
Or you can add the files and directories to .gitignore
, in which case they will never show up.
name is used for form submission in DOM (Document Object Model).
ID is used to unique name of html controls in DOM specially for Javascript & CSS
In order to create the drawable directory structure for different image densities, You need to:
\res
foldernew >
android resource directory
In the New Resource Directory
window, under Available qualifiers
resource type section, select drawable
.
Add density and choose the appropriate size.
Starting in version 0.7.9 you can use the filter operator .isnot
instead of comparing constraints, like this:
query.filter(User.name.isnot(None))
This method is only necessary if pep8 is a concern.
source: sqlalchemy documentation
In addition to the answer of BalusC, use the following Java RegExp to replace &&
with and
:
Search: (#\{[^\}]*)(&&)([^\}]*\})
Replace: $1and$3
You have run this regular expression replacement multiple times to find all occurences in case you are using >2 literals in your EL expressions. Mind to replace the leading # by $ if your EL expression syntax differs.
from pyspark.sql import SparkSession
spark = SparkSession \
.builder \
.appName("Python Spark SQL basic example") \
.config("spark.some.config.option", "some-value") \
.getOrCreate()
df = spark.read.csv("/home/stp/test1.csv",header=True,sep="|")
print(df.collect())
just goto
Tools > Options > Keymaps
than searchzoom
click on three (...
) dot and click Edit
press
your_shortcut_keys
( what ever shortcut you want to set)
Finally I got some answer,
::test::GTEST_FLAG(list_tests) = true;
//From your program, not w.r.t console.
If you would like to use --gtest_filter =*;
/* =*, =xyz*... etc*/
// You need to use them in Console.
So, my requirement is to use them from the program not from the console.
Updated:-
Finally I got the answer for updating the same in from the program.
::testing::GTEST_FLAG(filter) = "*Counter*:*IsPrime*:*ListenersTest.DoesNotLeak*";//":-:*Counter*";
InitGoogleTest(&argc, argv);
RUN_ALL_TEST();
So, Thanks for all the answers.
You people are great.
You can try also using below script
<html>
<head>
<script>
function load()
{
document.frm1.submit()
}
</script>
</head>
<body onload="load()">
<form action="http://www.google.com" id="frm1" name="frm1">
<input type="text" value="" />
</form>
</body>
</html>
I tried this code and it works for me. I call this function every time I move to another page
public static void waitForPageToBeReady()
{
JavascriptExecutor js = (JavascriptExecutor)driver;
//This loop will rotate for 100 times to check If page Is ready after every 1 second.
//You can replace your if you wants to Increase or decrease wait time.
for (int i=0; i<400; i++)
{
try
{
Thread.sleep(1000);
}catch (InterruptedException e) {}
//To check page ready state.
if (js.executeScript("return document.readyState").toString().equals("complete"))
{
break;
}
}
}
git format-patch commit_Id~1..commit_Id
git apply patch-file-name
Fast and simple solution.
To iterate through all the inputs in a form you can do this:
$("form#formID :input").each(function(){
var input = $(this); // This is the jquery object of the input, do what you will
});
This uses the jquery :input selector to get ALL types of inputs, if you just want text you can do :
$("form#formID input[type=text]")//...
etc.
Everyone here did a great job of explaining how the code works and showing how you can construct your own examples, but here's an information theoretical answer showing why we can reasonably expect a solution to exist that the brute force search will eventually find.
The 26 different lower-case letters form our alphabet S
. To allow generating words of different lengths, we further add a terminator symbol ?
to yield an extended alphabet S' := S ? {?}
.
Let a
be a symbol and X a uniformly distributed random variable over S'
. The probability of obtaining that symbol, P(X = a)
, and its information content, I(a)
, are given by:
P(X = a) = 1/|S'| = 1/27
I(a) = -log2[P(X = a)] = -log2(1/27) = log2(27)
For a word ? ? S*
and its ?-
terminated counterpart ?' := ? · ? ? (S')*
, we have
I(?) := I(?') = |?'| * log2(27) = (|?| + 1) * log2(27)
Since the Pseudorandom Number Generator (PRNG) is initialized with a 32-bit seed, we can expect most words of length up to
? = floor[32/log2(27)] - 1 = 5
to be generated by at least one seed. Even if we were to search for a 6-character word, we would still be successful about 41.06% of the time. Not too shabby.
For 7 letters we're looking at closer to 1.52%, but I hadn't realized that before giving it a try:
#include <iostream>
#include <random>
int main()
{
std::mt19937 rng(631647094);
std::uniform_int_distribution<char> dist('a', 'z' + 1);
char alpha;
while ((alpha = dist(rng)) != 'z' + 1)
{
std::cout << alpha;
}
}
See the output: http://ideone.com/JRGb3l
to see changes that are not merged, I did this:
git checkout experiment
git merge --no-commit master
git diff --cached
Note: This shows changes in master
that are not in experiment
.
Don't forget to:
git merge --abort
When you're done lookin.
actually, follow @Nick T's answer doesn't work for me, i try apt-get install python-mysqldb
work for me
root@2fb0da64a933:/home/test_scrapy# apt-get install python-mysqldb
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
libmariadbclient18 mysql-common
Suggested packages:
default-mysql-server | virtual-mysql-server python-egenix-mxdatetime python-mysqldb-dbg
The following NEW packages will be installed:
libmariadbclient18 mysql-common python-mysqldb
0 upgraded, 3 newly installed, 0 to remove and 29 not upgraded.
Need to get 843 kB of archives.
After this operation, 4611 kB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://deb.debian.org/debian stretch/main amd64 mysql-common all 5.8+1.0.2 [5608 B]
Get:2 http://deb.debian.org/debian stretch/main amd64 libmariadbclient18 amd64 10.1.38-0+deb9u1 [785 kB]
Get:3 http://deb.debian.org/debian stretch/main amd64 python-mysqldb amd64 1.3.7-1.1 [52.1 kB]
Fetched 843 kB in 23s (35.8 kB/s)
debconf: delaying package configuration, since apt-utils is not installed
Selecting previously unselected package mysql-common.
(Reading database ... 13223 files and directories currently installed.)
Preparing to unpack .../mysql-common_5.8+1.0.2_all.deb ...
Unpacking mysql-common (5.8+1.0.2) ...
Selecting previously unselected package libmariadbclient18:amd64.
Preparing to unpack .../libmariadbclient18_10.1.38-0+deb9u1_amd64.deb ...
Unpacking libmariadbclient18:amd64 (10.1.38-0+deb9u1) ...
Selecting previously unselected package python-mysqldb.
Preparing to unpack .../python-mysqldb_1.3.7-1.1_amd64.deb ...
Unpacking python-mysqldb (1.3.7-1.1) ...
Setting up mysql-common (5.8+1.0.2) ...
update-alternatives: using /etc/mysql/my.cnf.fallback to provide /etc/mysql/my.cnf (my.cnf) in auto mode
Setting up libmariadbclient18:amd64 (10.1.38-0+deb9u1) ...
Processing triggers for libc-bin (2.24-11+deb9u3) ...
Setting up python-mysqldb (1.3.7-1.1) ...
root@2fb0da64a933:/home/test_scrapy# python
Python 2.7.13 (default, Nov 24 2017, 17:33:09)
[GCC 6.3.0 20170516] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
>>>
When you use a function ...
<p onclick="update_url('/en/step2');">Link</p>
<script>
function update_url(url) {
history.pushState(null, null, url);
}
</script>
You can try https://rubygems.org/gems/dates_from_string:
Find date in structure:
text = "get car from repair 2015-02-02 23:00:10"
dates_from_string = DatesFromString.new
dates_from_string.find_date(text)
=> ["2015-02-02 23:00:10"]
CMake produces Visual Studio Projects and Solutions seamlessly. You can even produce projects/solutions for different Visual Studio versions without making any changes to the CMake files.
Adding and removing source files is just a matter of modifying the CMakeLists.txt
which has the list of source files and regenerating the projects/solutions. There is even a globbing function to find all the sources in a directory (though it should be used with caution).
The following link explains CMake and Visual Studio specific behavior very well.
You can use re.escape():
re.escape(string) Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.
>>> import re
>>> re.escape('^a.*$')
'\\^a\\.\\*\\$'
If you are using a Python version < 3.7, this will escape non-alphanumerics that are not part of regular expression syntax as well.
If you are using a Python version < 3.7 but >= 3.3, this will escape non-alphanumerics that are not part of regular expression syntax, except for specifically underscore (_
).
Set-ExecutionPolicy Unrestricted -Scope CurrentUser
This will set the execution policy for the current user (stored in HKEY_CURRENT_USER) rather than the local machine (HKEY_LOCAL_MACHINE). This is useful if you don't have administrative control over the computer.
Style is an attribute so css
won't work for it.U can use attr
Change:
$('.handle').css({'style':'left: 300px'});
T0:
$('.handle').attr('style','left: 300px');//Use `,` Comma instead of `:` colon
X-code is primarily made for OS-X or iPhone development on Mac systems. Versions for Windows are not available. However this might help!
There is no way to get Xcode on Windows; however you can use a different SDK like Corona instead although it will not use Objective-C (I believe it uses Lua). I have however heard that it is horrible to use.
Source: classroomm.com
To get the day from any given date, just pass the date into a new Date object:
let date = new Date("01/05/2020");
let day = date.toLocaleString('en-us', {weekday: 'long'});
console.log(day);
// expected result = tuesday
To read more, go to mdn-date.prototype.toLocaleString()(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString)
You can replace the certificate by just running the certbot again with ./certbot-auto certonly
You will be prompted with this message if you try to generate a certificate for a domain that you have already covered by an existing certificate:
-------------------------------------------------------------------------------
You have an existing certificate that contains a portion of the domains you
requested (ref: /etc/letsencrypt/renewal/<domain>.conf)
It contains these names: <domain>
You requested these names for the new certificate: <domain>,
<the domain you want to add to the cert>.
Do you want to expand and replace this existing certificate with the new
certificate?
-------------------------------------------------------------------------------
Just chose Expand
and replace it.
I actually ran into this same prob trying to install Scrapy which depends on cryptography being installed first. I'm on Win764-bit with Python 2.7 64-bit installed. @jsonm's answer eventually worked for me, but first I had to Copy C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin\vcvarsx86_amd64.bat
to the x86_amd64
subdir within that bin dir so the vcvarsall.bat
would stop throwing an error saying it was missing the config. If you need to configure env vars for a different setup, be sure to copy to corresponding vcvars bat file to the corresponding subdir or the first command below might not work.
Then I ran the following from a commandline as per @jsonm's instructions (tweaked for my config)...
C:\> "C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\vcvarsall.bat" x86_amd64
C:\> set LIB=C:\OpenSSL-Win64\lib;%LIB%
C:\> set INCLUDE=C:\OpenSSL-Win64\include;%INCLUDE%
C:\> pip install cryptography
And it worked.
You can use this:
SELECT COUNT(*) FROM (SELECT DISTINCT column_name FROM table_name) AS temp;
This is much faster than:
COUNT(DISTINCT column_name)
In his paper, Memory Optimization, Christer Ericson says that while restrict
is not part of the C++ standard yet, that it is supported by many compilers and he recommends it's usage when available:
restrict keyword
! New to 1999 ANSI/ISO C standard
! Not in C++ standard yet, but supported by many C++ compilers
! A hint only, so may do nothing and still be conforming
A restrict-qualified pointer (or reference)...
! ...is basically a promise to the compiler that for the scope of the pointer, the target of the pointer will only be accessed through that pointer (and pointers copied from it).
In C++ compilers that support it it should probably behave the same as in C.
See this SO post for details: Realistic usage of the C99 ‘restrict’ keyword?
Take half an hour to skim through Ericson's paper, it's interesting and worth the time.
Edit
I also found that IBM's AIX C/C++ compiler supports the __restrict__
keyword.
g++ also seems to support this as the following program compiles cleanly on g++:
#include <stdio.h>
int foo(int * __restrict__ a, int * __restrict__ b) {
return *a + *b;
}
int main(void) {
int a = 1, b = 1, c;
c = foo(&a, &b);
printf("c == %d\n", c);
return 0;
}
I also found a nice article on the use of restrict
:
Demystifying The Restrict Keyword
Edit2
I ran across an article which specifically discusses the use of restrict in C++ programs:
Load-hit-stores and the __restrict keyword
Also, Microsoft Visual C++ also supports the __restrict
keyword.
The documentation for css() says that setting the style property to the empty string will remove that property if it does not reside in a stylesheet:
Setting the value of a style property to an empty string — e.g.
$('#mydiv').css('color', '')
— removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's.css()
method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or<style>
element.
Since your styles are inline, you can write:
$(selector).css("-moz-user-select", "");
You can do this, you just need to circumvent the launcher.
In %appdata%\.minecraft\bin
(or ~/.minecraft/bin
on unixy systems), there is a minecraft.jar file. This is the actual game - the launcher runs this.
Invoke it like so:
java -Xms512m -Xmx1g -Djava.library.path=natives/ -cp "minecraft.jar;lwjgl.jar;lwjgl_util.jar" net.minecraft.client.Minecraft <username> <sessionID>
Set the working directory to .minecraft/bin
.
To get the session ID, POST (request this page):
https://login.minecraft.net?user=<username>&password=<password>&version=13
You'll get a response like this:
1343825972000:deprecated:SirCmpwn:7ae9007b9909de05ea58e94199a33b30c310c69c:dba0c48e1c584963b9e93a038a66bb98
The fourth field is the session ID. More details here. Read those details, this answer is outdated
Here's an example of logging in to minecraft.net in C#.
For C++ .so
files, the ultimate nm
command is nm --demangle --dynamic --defined-only --extern-only <my.so>
# nm --demangle --dynamic --defined-only --extern-only /usr/lib64/libqpid-proton-cpp.so | grep work | grep add
0000000000049500 T proton::work_queue::add(proton::internal::v03::work)
0000000000049580 T proton::work_queue::add(proton::void_function0&)
000000000002e7b0 W proton::work_queue::impl::add_void(proton::internal::v03::work)
000000000002b1f0 T proton::container::impl::add_work_queue()
000000000002dc50 T proton::container::impl::container_work_queue::add(proton::internal::v03::work)
000000000002db60 T proton::container::impl::connection_work_queue::add(proton::internal::v03::work)
Clickatell is a popular SMS gateway. It works in 200+ countries.
Their API offers a choice of connection options via: HTTP/S, SMPP, SMTP, FTP, XML, SOAP. Any of these options can be used from php.
The HTTP/S method is as simple as this:
http://api.clickatell.com/http/sendmsg?to=NUMBER&msg=Message+Body+Here
The SMTP method consists of sending a plain-text e-mail to: [email protected]
, with the following body:
user: xxxxx
password: xxxxx
api_id: xxxxx
to: 448311234567
text: Meet me at home
You can also test the gateway (incoming and outgoing) for free from your browser
You need to finish writing the memory stream then read the buffer back.
using (var memoryStream = new MemoryStream())
{
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create))
{
var demoFile = archive.CreateEntry("foo.txt");
using (var entryStream = demoFile.Open())
using (var streamWriter = new StreamWriter(entryStream))
{
streamWriter.Write("Bar!");
}
}
using (var fileStream = new FileStream(@"C:\Temp\test.zip", FileMode.Create))
{
var bytes = memoryStream.GetBuffer();
fileStream.Write(bytes,0,bytes.Length );
}
}
Enable USB Debugging into your emulator
That's it enjoy
using $localStorage
app.controller('ProductController', function($scope, $localStorage) {
$scope.setSelectedProduct = function(selectedObj){
$localStorage.selectedObj= selectedObj;
};
});
app.controller('CartController', function($scope,$localStorage) {
$scope.selectedProducts = $localStorage.selectedObj;
$localStorage.$reset();//to remove
});
On click you can call method that invokes broadcast:
$rootScope.$broadcast('SOME_TAG', 'your value');
and the second controller will listen on this tag like:
$scope.$on('SOME_TAG', function(response) {
// ....
})
using $rootScope:
window.sessionStorage.setItem("Mydata",data);
$scope.data = $window.sessionStorage.getItem("Mydata");
One way using angular service:
var app = angular.module("home", []);
app.controller('one', function($scope, ser1){
$scope.inputText = ser1;
});
app.controller('two',function($scope, ser1){
$scope.inputTextTwo = ser1;
});
app.factory('ser1', function(){
return {o: ''};
});
You can run a bash inside the container with this:
$ docker run -it ubuntu /bin/bash
You'd better not transpose the data.frame while the name column is in it - all numeric values will then be turned into strings!
Here's a solution that keeps numbers as numbers:
# first remember the names
n <- df.aree$name
# transpose all but the first column (name)
df.aree <- as.data.frame(t(df.aree[,-1]))
colnames(df.aree) <- n
df.aree$myfactor <- factor(row.names(df.aree))
str(df.aree) # Check the column types
A const member is considered static by the compiler, as well as implying constant value semantics, which means references to the constant might be compiled into the using code as the value of the constant member, instead of a reference to the member.
In other words, a const member containing the value 10, might get compiled into code that uses it as the number 10, instead of a reference to the const member.
This is different from a static readonly field, which will always be compiled as a reference to the field.
Note, this is pre-JIT. When the JIT'ter comes into play, it might compile both these into the target code as values.
try
pip3 install --user --upgrade pandas
Old question, but the following might offer some more detail.
null
represents no value or an unknown value. It doesn’t specify why there is no value, which can lead to some ambiguity.
Suppose you run a query like this:
SELECT *
FROM orders
WHERE delivered=ordered;
that is, you are looking for rows where the ordered
and delivered
dates are the same.
What is to be expected when one or both columns are null?
Because at least one of the dates is unknown, you cannot expect to say that the 2 dates are the same. This is also the case when both dates are unknown: how can they be the same if we don’t even know what they are?
For this reason, any expression treating null
as a value must fail. In this case, it will not match. This is also the case if you try the following:
SELECT *
FROM orders
WHERE delivered<>ordered;
Again, how can we say that two values are not the same if we don’t know what they are.
SQL has a specific test for missing values:
IS NULL
Specifically it is not comparing values, but rather it seeks out missing values.
Finally, as regards the !=
operator, as far as I am aware, it is not actually in any of the standards, but it is very widely supported. It was added to make programmers from some languages feel more at home. Frankly, if a programmer has difficulty remembering what language they’re using, they’re off to a bad start.
I used to think that the var keyword was a great invention but I put a a limit on it this was
I came to realise this then gave me no benefit whatsoever and removed all var keywords from my code (unless they were specifically required), for now I think that they make the code less readable, especially to others reading your code.
It hides intent and in at least one instance lead to a runtime bug in some code because of assumption of type.
In Typescript 1.5 and later, you can use for..of
as opposed to for..in
var numbers = [1, 2, 3];
for (var number of numbers) {
console.log(number);
}
Here is working solution:
Output:
public class XmlTest {
private static final Logger log = LoggerFactory.getLogger(XmlTest.class);
@Test
public void createDefaultBook() throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);
Marshaller marshaller = jaxbContext.createMarshaller();
StringWriter writer = new StringWriter();
marshaller.marshal(new Book(), writer);
log.debug("Book xml:\n {}", writer.toString());
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "book")
public static class Book {
@XmlElementRef(name = "price")
private Price price = new Price();
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "price")
public static class Price {
@XmlAttribute(name = "drawable")
private Boolean drawable = true; //you may want to set default value here
@XmlValue
private int priceValue = 1234;
public Boolean getDrawable() {
return drawable;
}
public void setDrawable(Boolean drawable) {
this.drawable = drawable;
}
public int getPriceValue() {
return priceValue;
}
public void setPriceValue(int priceValue) {
this.priceValue = priceValue;
}
}
}
Output:
22:00:18.471 [main] DEBUG com.grebski.stack.XmlTest - Book xml:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book>
<price drawable="true">1234</price>
</book>
You can backup the git repo with git-copy . git-copy saved new project as a bare repo, it means minimum storage cost.
git copy /path/to/project /backup/project.backup
Then you can restore your project with git clone
git clone /backup/project.backup project
//where [1] - column number which you want to make text
ExcelWorksheet.Columns[1].NumberFormat = "@";
//If you want to format a particular column in all sheets in a workbook - use below code. Remove loop for single sheet along with slight changes.
//path were excel file is kept
string ResultsFilePath = @"C:\\Users\\krakhil\\Desktop\\TGUW EXCEL\\TEST";
Excel.Application ExcelApp = new Excel.Application();
Excel.Workbook ExcelWorkbook = ExcelApp.Workbooks.Open(ResultsFilePath);
ExcelApp.Visible = true;
//Looping through all available sheets
foreach (Excel.Worksheet ExcelWorksheet in ExcelWorkbook.Sheets)
{
//Selecting the worksheet where we want to perform action
ExcelWorksheet.Select(Type.Missing);
ExcelWorksheet.Columns[1].NumberFormat = "@";
}
//saving excel file using Interop
ExcelWorkbook.Save();
//closing file and releasing resources
ExcelWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(ExcelWorkbook);
ExcelApp.Quit();
Marshal.FinalReleaseComObject(ExcelApp);
In the ideal case we should have enough memory to read the file in one read operation. That would be the best performer because we let the system manage File System , allocation units and HDD at will. In practice you are fortunate to know the file sizes in advance, just use the average file size rounded up to 4K (default allocation unit on NTFS). And best of all : create a benchmark to test multiple options.
For capital letters:
i=67
letters=({A..Z})
echo "${letters[$i-65]}"
Output:
C
In Python, to represent the absence of a value, you can use the None value (types.NoneType.None) for objects and "" (or len() == 0) for strings. Therefore:
if yourObject is None: # if yourObject == None:
...
if yourString == "": # if yourString.len() == 0:
...
Regarding the difference between "==" and "is", testing for object identity using "==" should be sufficient. However, since the operation "is" is defined as the object identity operation, it is probably more correct to use it, rather than "==". Not sure if there is even a speed difference.
Anyway, you can have a look at:
'So from this discussion i am thinking this should be the code then.
Sub Button1_Click()
Dim excel As excel.Application
Dim wb As excel.Workbook
Dim sht As excel.Worksheet
Dim f As Object
Set f = Application.FileDialog(3)
f.AllowMultiSelect = False
f.Show
Set excel = CreateObject("excel.Application")
Set wb = excel.Workbooks.Open(f.SelectedItems(1))
Set sht = wb.Worksheets("Data")
sht.Activate
sht.Columns("A:G").Copy
Range("A1").PasteSpecial Paste:=xlPasteValues
wb.Close
End Sub
'Let me know if this is correct or a step was missed. Thx.
This part of PowerShell is probably the most stupid aspect. Any extraneous output generated during a function will pollute the result. Sometimes there isn't any output, and then under some conditions there is some other unplanned output, in addition to your planned return value.
So, I remove the assignment from the original function call, so the output ends up on the screen, and then step through until something I didn't plan for pops out in the debugger window (using the PowerShell ISE).
Even things like reserving variables in outer scopes cause output, like [boolean]$isEnabled
which will annoyingly spit a False out unless you make it [boolean]$isEnabled = $false
.
Another good one is $someCollection.Add("thing")
which spits out the new collection count.
You can try creating a css for your font with font-face (like explained here)
Step #1
Create a css file with font face and place it somewhere, like in assets/fonts
customfont.css
@font-face {
font-family: YourFontFamily;
src: url("/assets/font/yourFont.otf") format("truetype");
}
Step #2
Add the css to your .angular-cli.json in the styles
config
"styles":[
//...your other styles
"assets/fonts/customFonts.css"
]
Do not forget to restart ng serve
after doing this
Step #3
Use the font in your code
component.css
span {font-family: YourFontFamily; }
Try the below code if you're Using Python3:
import sys
if not sys.warnoptions:
import warnings
warnings.simplefilter("ignore")
or try this...
import warnings
def fxn():
warnings.warn("deprecated", DeprecationWarning)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
fxn()
or try this...
import warnings
warnings.filterwarnings("ignore")
Simplest definition of the Coalesce() function could be:
Coalesce() function evaluates all passed arguments then returns the value of the first instance of the argument that did not evaluate to a NULL.
Note: it evaluates ALL parameters, i.e. does not skip evaluation of the argument(s) on the right side of the returned/NOT NULL parameter.
Syntax:
Coalesce(arg1, arg2, argN...)
Beware: Apart from the arguments that evaluate to NULL, all other (NOT-NULL) arguments must either be of same datatype or must be of matching-types (that can be "implicitly auto-converted" into a compatible datatype), see examples below:
PRINT COALESCE(NULL, ('str-'+'1'), 'x') --returns 'str-1, works as all args (excluding NULLs) are of same VARCHAR type.
--PRINT COALESCE(NULL, 'text', '3', 3) --ERROR: passed args are NOT matching type / can't be implicitly converted.
PRINT COALESCE(NULL, 3, 7.0/2, 1.99) --returns 3.0, works fine as implicit conversion into FLOAT type takes place.
PRINT COALESCE(NULL, '1995-01-31', 'str') --returns '2018-11-16', works fine as implicit conversion into VARCHAR occurs.
DECLARE @dt DATE = getdate()
PRINT COALESCE(NULL, @dt, '1995-01-31') --returns today's date, works fine as implicit conversion into DATE type occurs.
--DATE comes before VARCHAR (works):
PRINT COALESCE(NULL, @dt, 'str') --returns '2018-11-16', works fine as implicit conversion of Date into VARCHAR occurs.
--VARCHAR comes before DATE (does NOT work):
PRINT COALESCE(NULL, 'str', @dt) --ERROR: passed args are NOT matching type, can't auto-cast 'str' into Date type.
HTH
If Git prompts you for a username and password every time you try to interact with GitHub, you're probably using the HTTPS clone URL for your repository.
Using an HTTPS remote URL has some advantages: it's easier to set up than SSH, and usually works through strict firewalls and proxies. However, it also prompts you to enter your GitHub credentials every time you pull or push a repository.
You can configure Git to store your password for you. For Windows:
git config --global credential.helper wincred
%1 refers to the first argument passed in and can't be used in an iterator.
Try this:
@echo off
for %%i in (*.*) do echo %%i
Nothing but plain Javascript (you don't even need a controller):
<div ng-repeat="n in [].constructor(10) track by $index">
{{ $index }}
</div>
Very useful when mockuping
This is what I ended up using inside my .bat file. Windows only of course.
set CURRENT_DIR=%cd%
mkdir ./directoryToExtractTo
cd ./directoryToExtractTo
jar xvf %CURRENT_DIR%\myJar.jar
cd %CURRENT_DIR%
Python is a case-sensitive language. All Python keywords are lowercase. Use if
, not If
.
Also, don't put a colon after the call to print()
. Also, indent the print()
and exit()
calls, as Python uses indentation rather than brackets to represent code blocks.
And also, proceed = "y" or "Y"
won't do what you want. Use proceed = "y"
and if answer.lower() == proceed:
, or something similar.
There's also the fact that your program will exit as long as the input value is not the single character "y" or "Y", which contradicts the prompting of "N" for the alternate case. Instead of your else
clause there, use elif answer.lower() == info_incorrect:
, with info_incorrect = "n"
somewhere beforehand. Then just reprompt for the response or something if the input value was something else.
I'd recommend going through the tutorial in the Python documentation if you're having this much trouble the way you're learning now. http://docs.python.org/tutorial/index.html
This query will use index if you have it for signup_date
field
SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d')
FROM users
WHERE signup_date >= CURDATE() && signup_date < (CURDATE() + INTERVAL 1 DAY)
use this code for set value in input tag by another id.
$(".formdata").val(document.getElementById("fsd").innerHTML);
or use this code for set value in input tag using classname="formdata"
$(".formdata").val("hello");
var mask = /^\d+$/;
if ( myString.exec(mask) ){
/* That's a number */
}
Why complicate the situation? this is simple write some function like this:
function findBySpecField(data, reqField, value, resField) {
var container = data;
for (var i = 0; i < container.length; i++) {
if (container[i][reqField] == value) {
return(container[i][resField]);
}
}
return '';
}
Use Case:
var data=[{
"id": 502100,
"name": "B?rd? filiali"
},
{
"id": 502122
"name": "10 sayli filiali"
},
{
"id": 503176
"name": "5 sayli filiali"
}]
console.log('Result is '+findBySpecField(data,'id','502100','name'));
output:
Result is B?rd? filiali
Just try this in Javascript:
$previous = "javascript:history.go(-1)";
Or you can try it in PHP:
if(isset($_SERVER['HTTP_REFERER'])) {
$previous = $_SERVER['HTTP_REFERER'];
}
Pass your arguments in constructor itself.
Process process = new ProcessBuilder("C:\\PathToExe\\MyExe.exe","param1","param2").start();
You need a root node
<?xml version="1.0" encoding="ISO-8859-1"?>
<documents>
<document>
<name>Sample Document</name>
<type>document</type>
<url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&titletype=Title&fontsize=9&fontface=Arial&spacing=1.0&text=&wordcount3=0</url>
</document>
<document>
<name>Sample</name>
<type>document</type>
<url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&titletype=Title&fontsize=9&fontface=Arial&spacing=1.0&text=&</url>
</document>
</documents>
I had the same issue, all I did was add a setTimeout
of about 10 seconds before trying to connect to the Mongo server and it solved the issue right up. I dont know why I had to add a delay but it worked...
Assuming you're in the Object Explorer Details (F7) showing the list of Stored Procedures, click the Filters button and enter the name (or partial name).
On Windows you can include the windows library and use "Sleep(0);" to sleep the program. It takes a value that represents milliseconds.
var anchor = angular.element('<a/>');
anchor.css({display: 'none'}); // Make sure it's not visible
angular.element(document.body).append(anchor); // Attach to document
anchor.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURI(data),
target: '_blank',
download: 'filename.csv'
})[0].click();
anchor.remove(); // Clean it up afterwards
This code works both Mozilla and chrome
switch(position) {
case 0:
...
break;
case 1:
...
break;
default:
...
}
Did you mean that?
Besides Manuel's way, you can still use the Manifest.
In Android Studio stable, you have to add the following 2 lines to application
in the AndroidManifest
file:
android:debuggable="true"
tools:ignore="HardcodedDebugMode"
The first one will enable debugging of signed APK, and the second one will prevent compile-time error.
After this, you can attach to the process via "Attach debugger to Android process" button.
As Scobal's post implies, the datepicker is looking for a Date object - not just a string! So, to modify your example code to do what you want:
var queryDate = new Date('2009/11/01'); // Dashes won't work
$('#datePicker').datepicker('setDate', queryDate);
For Kotlin users:
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?) : View?
{
// Inflate the layout for this fragment
var myView = inflater.inflate(R.layout.fragment_home, container, false)
var btn_test = myView.btn_test as Button
btn_test.setOnClickListener {
textView.text = "hunny home fragment"
}
return myView
}
Just add these two line in your css id #some_div
display: block;
overflow: auto;
After that you will get what your are looking for !
Here it goes.
// Select by value_x000D_
$('select[name="options"]').find('option[value="3"]').attr("selected",true);_x000D_
_x000D_
// Select by text_x000D_
//$('select[name="options"]').find('option:contains("Third")').attr("selected",true);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<html>_x000D_
<body>_x000D_
<select name="options">_x000D_
<option value="1">First</option>_x000D_
<option value="2">Second</option>_x000D_
<option value="3">Third</option>_x000D_
</select>_x000D_
</body>_x000D_
</html>
_x000D_
You really want to use at
. It is exactly made for this purpose.
echo /usr/bin/the_command options | at now + 1 day
However if you don't have at
, or your hosting company doesn't provide access to it, you can have a cron job include code that makes sure it only runs once.
Set up a cron entry with a very specific time:
0 0 2 12 * /home/adm/bin/the_command options
Next /home/adm/bin/the_command needs to either make sure it only runs once.
#! /bin/bash
COMMAND=/home/adm/bin/the_command
DONEYET="${COMMAND}.alreadyrun"
export PATH=/usr/bin:$PATH
if [[ -f $DONEYET ]]; then
exit 1
fi
touch "$DONEYET"
# Put the command you want to run exactly once here:
echo 'You will only get this once!' | mail -s 'Greetings!' [email protected]
There is a bot that echoes your chat id upon starting a conversation.
Just search for @chatid_echo_bot
and tap /start
. It will echo your chat id.
Another option is @getidsbot
which gives you much more information. This bot also gives information about a forwarded message (from user, to user, chad ids, etc) if you forward the message to the bot.
I just came up with this. It may not be the fastest, but I'm not using anything other than straight additions and comparisons. Of course, what stops you here is the recursion limit.
def nondivsby2():
j = 1
while True:
j += 2
yield j
def nondivsbyk(k, nondivs):
j = 0
for i in nondivs:
while j < i:
j += k
if j > i:
yield i
def primes():
nd = nondivsby2()
while True:
p = next(nd)
nd = nondivsbyk(p, nd)
yield p
def main():
for p in primes():
print(p)
Seems your resource POST
method won't get hit as @peeskillet mention. Most probably your ~POST~ request won't work, because it may not be a simple request. The only simple requests are GET, HEAD or POST and request headers are simple(The only simple headers are Accept, Accept-Language, Content-Language, Content-Type= application/x-www-form-urlencoded, multipart/form-data, text/plain).
Since in you already add Access-Control-Allow-Origin
headers to your Response, you can add new OPTIONS
method to your resource class.
@OPTIONS
@Path("{path : .*}")
public Response options() {
return Response.ok("")
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
.header("Access-Control-Max-Age", "2000")
.build();
}
try using "." E.g.
File currentDirectory = new File(".");
This worked for me
You need to make the object first, then use []
to set it.
var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);
UPDATE 2018:
If you're able to use ES6 and Babel, you can use this new feature:
{
[yourKeyVariable]: someValueArray,
}
I don't think anyone has really fully answered the question because they don't describe how the two are used. OK, I think we know that exit kills the script, wherever it is called and you can assign a status to it as well such as exit or exit 0 or exit 7 and so forth. This can be used to determine how the script was forced to stop if called by another script, etc. Enough on exit.
return, when called, will return the value specified to indicate the function's behavior, usually a 1 or a 0. For example:
#!/bin/bash
isdirectory() {
if [ -d "$1" ]
then
return 0
else
return 1
fi
echo "you will not see anything after the return like this text"
}
Check like this:
if isdirectory $1; then echo "is directory"; else echo "not a directory"; fi
Or like this:
isdirectory || echo "not a directory"
In this example, the test can be used to indicate if the directory was found. Notice that anything after the return will not be executed in the function. 0 is true, but false is 1 in the shell, different from other programming languages.
For more information on functions: Returning Values from Bash Functions
Note: The isdirectory function is for instructional purposes only. This should not be how you perform such an option in a real script.*
In specific circumstances you can do a "soft" inheritance:
.composite
{
display:inherit;
background:inherit;
}
.something { display:inline }
.else { background:red }
This only works if you are adding the .composite class to a child element. It is "soft" inheritance because any values not specified in .composite are not inherited obviously. Keep in mind it would still be less characters to simply write "inline" and "red" instead of "inherit".
Here is a list of properties and whether or not they do this automatically: https://www.w3.org/TR/CSS21/propidx.html
It is absolutely possible that all other answers work for people but for me this path worked:
Leave your JDK path under JAVA_HOME
System Variable as it is given here. Do not append bin or another path. It worked for me.
C:\Program Files\Java\jdk1.8.0_11\
Otherwise I am getting this error:
Installing Android Studio, does not point to a valid JVM installation error
You have to implement your own comparison function that will compare the dictionaries by values of name keys. See Sorting Mini-HOW TO from PythonInfo Wiki
The default Android camera application returns a non-null intent only when passing back a thumbnail in the returned Intent. If you pass EXTRA_OUTPUT
with a URI to write to, it will return a null
intent and the picture is in the URI that you passed in.
You can verify this by looking at the camera app's source code on GitHub:
Bundle newExtras = new Bundle();
if (mCropValue.equals("circle")) {
newExtras.putString("circleCrop", "true");
}
if (mSaveUri != null) {
newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, mSaveUri);
} else {
newExtras.putBoolean("return-data", true);
}
I would guess that you're either passing in EXTRA_OUTPUT
somehow, or the camera app on your phone works differently.
Print n prime numbers using python:
num = input('get the value:')
for i in range(2,num+1):
count = 0
for j in range(2,i):
if i%j != 0:
count += 1
if count == i-2:
print i,
Here's my twist on it, with a runnable example. Note this will only work in the situation where Id
is unique, and you have duplicate values in other columns.
DECLARE @SampleData AS TABLE (Id int, Duplicate varchar(20))
INSERT INTO @SampleData
SELECT 1, 'ABC' UNION ALL
SELECT 2, 'ABC' UNION ALL
SELECT 3, 'LMN' UNION ALL
SELECT 4, 'XYZ' UNION ALL
SELECT 5, 'XYZ'
DELETE FROM @SampleData WHERE Id IN (
SELECT Id FROM (
SELECT
Id
,ROW_NUMBER() OVER (PARTITION BY [Duplicate] ORDER BY Id) AS [ItemNumber]
-- Change the partition columns to include the ones that make the row distinct
FROM
@SampleData
) a WHERE ItemNumber > 1 -- Keep only the first unique item
)
SELECT * FROM @SampleData
And the results:
Id Duplicate
----------- ---------
1 ABC
3 LMN
4 XYZ
Not sure why that's what I thought of first... definitely not the simplest way to go but it works.
While you have a return value in checkform, it isn't being used anywhere - try using onclick="return checkform()"
instead.
You may want to considering replacing this method with onsubmit="return checkform()"
in the form tag instead, though both will work for clicking the button.
All XAMPP packages come with Multibyte String (php_mbstring.dll) extension installed.
If you have accidentally removed DLL file from php/ext
folder, just add it back (get the copy from XAMPP zip archive - its downloadable).
If you have deleted the accompanying INI configuration line from php.ini
file, add it back as well:
extension=php_mbstring.dll
Also, ensure to restart your webserver (Apache) using XAMPP control panel.
Additional Info on Enabling PHP Extensions
/XAMPP/php/ext
directory)extension_dir = "ext"
)Your time string is similar to the time format in rfc 2822 (date format in email, http headers). You could parse it using only stdlib:
>>> from email.utils import parsedate_tz
>>> parsedate_tz('Tue Jun 22 07:46:22 EST 2010')
(2010, 6, 22, 7, 46, 22, 0, 1, -1, -18000)
See solutions that yield timezone-aware datetime objects for various Python versions: parsing date with timezone from an email.
In this format, EST
is semantically equivalent to -0500
. Though, in general, a timezone abbreviation is not enough, to identify a timezone uniquely.
None of the answers provided here are completely correct when using TypeScript, as you may not know the kind of element that is selected.
This would therefore be preferred:
if (document.activeElement instanceof HTMLElement)
document.activeElement.blur();
I would furthermore discourage using the solution provided in the accepted answer, as the resulting blurring is not part of the official spec, and could break at any moment.
pow() doesn't work with int
, hence the error "error C2668:'pow': ambiguous call to overloaded function"
http://www.cplusplus.com/reference/clibrary/cmath/pow/
Write your own power function for int
s:
int power(int base, int exp)
{
int result = 1;
while(exp) { result *= base; exp--; }
return result;
}
I was facing this issue in ios 11 but layout was correct for ios 8 - 10.3.3 . For my case I set a Vertical Space Constraint to Superview.Top Margin instead of Superview.Top which works for ios 8 - 11.
You can password protect a SQLite3 DB. Before doing any operations, set the password as follows.
SQLiteConnection conn = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
conn.SetPassword("password");
conn.Open();
then next time you can access it like
conn = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;Password=password;");
conn.Open();
This wont allow any GUI editor to view your data. Some editors can decrypt the DB if you provide the password. The algorithm used is RSA.
Later if you wish to change the password, use
conn.ChangePassword("new_password");
To reset or remove password, use
conn.ChangePassword(String.Empty);
You can use Open Xml Sdk for this. If you have the code in html with color and formatting. You can use altchunks to add it to the word documents. Refer this post Add HTML String to OpenXML (*.docx) Document Hope this helps!
I've gotten around this with
mystr = ' '.join(
["Why, hello there",
"wonderful stackoverflow people!"])
in the past. It's not perfect, but it works nicely for very long strings that need to not have line breaks in them.
Based on @Andre's answer, I might have a slightly better version, in case someone is after a loop-free, completely string-manipulation based solution. It is also useful for those who don't want to dereference any symlinks, which is the downside of using realpath
or readlink -f
.
It works on bash versions 3.2.25 and higher.
shopt -s extglob
normalise_path() {
local path="$1"
# get rid of /../ example: /one/../two to /two
path="${path//\/*([!\/])\/\.\./}"
# get rid of /./ and //* example: /one/.///two to /one/two
path="${path//@(\/\.\/|\/+(\/))//}"
# remove the last '/.'
echo "${path%%/.}"
}
$ normalise_path /home/codemedic/../codemedic////.config
/home/codemedic/.config
The URL decoder should only be used for decoding strings from the urls generated by html forms which are in the "application/x-www-form-urlencoded" mime type. This does not support html characters.
After a search I found a Translate class within the HTML Parser library.
OK, so thanks to all of the contributors above. I am using .NET 4.6 and we also had the same issue. I spent time debugging System.Net.Http
, specifically the HttpClientHandler
, and found the following:
if (ExecutionContext.IsFlowSuppressed())
{
IWebProxy webProxy = (IWebProxy) null;
if (this.useProxy)
webProxy = this.proxy ?? WebRequest.DefaultWebProxy;
if (this.UseDefaultCredentials || this.Credentials != null || webProxy != null && webProxy.Credentials != null)
this.SafeCaptureIdenity(state);
}
So after assessing that the ExecutionContext.IsFlowSuppressed()
might have been the culprit, I wrapped our Impersonation code as follows:
using (((WindowsIdentity)ExecutionContext.Current.Identity).Impersonate())
using (System.Threading.ExecutionContext.SuppressFlow())
{
// HttpClient code goes here!
}
The code inside of SafeCaptureIdenity
(not my spelling mistake), grabs WindowsIdentity.Current()
which is our impersonated identity. This is being picked up because we are now suppressing flow. Because of the using/dispose this is reset after invocation.
It now seems to work for us, phew!
You can add org.apache.http
by using below code in app:Build gradle
dependencies {
compile 'org.apache.httpcomponents:httpclient:4.5'
}
If you don't mind always including .sh on the script file name, then you can keep the same script for Cygwin and Unix (Macbook).
To illustrate:
1. Always include .sh to your script file name, e.g., test1.sh
2. test1.sh looks like the following as an example:
3. On Windows with Cygwin, you type "test1.sh" to run#!/bin/bash
echo '$0 = ' $0
echo '$1 = ' $1
filepath=$1
4. On a Unix, you also type "test1.sh" to run
Note: On Windows, you need to use the file explorer to do following once:
1. Open the file explorer
2. Right-click on a file with .sh extension, like test1.sh
3. Open with... -> Select sh.exe
After this, your Windows 10 remembers to execute all .sh files with sh.exe.
Note: Using this method, you do not need to prepend your script file name with bash to run
When I used CocoaPods to develop iOS projects, there is a .xcworkspace
file, you need to open the project with .xcworkspace
file related with CocoaPods.
But when you Show Package Contents
with .xcworkspace
file, you will find the contents.xcworkspacedata
file.
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:BluetoothColorLamp24G.xcodeproj">
</FileRef>
<FileRef
location = "group:Pods/Pods.xcodeproj">
</FileRef>
</Workspace>
pay attention to this line:
location = "group:BluetoothColorLamp24G.xcodeproj"
The .xcworkspace
file has reference with the .xcodeproj
file.
Development Environment:
macOS 10.14
Xcode 10.1
Change
Range(DataImportColumn & DataImportRow).Offset(0, 2).Value
to
Cells(DataImportRow,DataImportColumn).Value
When you just have the row and the column then you can use the cells()
object. The syntax is Cells(Row,Column)
Also one more tip. You might want to fully qualify your Cells
object. for example
ThisWorkbook.Sheets("WhatEver").Cells(DataImportRow,DataImportColumn).Value
For other languages like German, Spanish, Danish, French etc that contain special characters (like German "Umlaute" as ü
, ä
, ö
) simply add these to the regex search string:
Example for German:
re.sub('[^A-ZÜÖÄa-z0-9]+', '', mystring)
I found this just looking for a way to output simple columns. If you just need no-fuss columns, then you can use this:
print("Titlex\tTitley\tTitlez")
for x, y, z in data:
print(x, "\t", y, "\t", z)
EDIT: I was trying to be as simple as possible, and thereby did some things manually instead of using the teams list. To generalize to the OP's actual question:
#Column headers
print("", end="\t")
for team in teams_list:
print(" ", team, end="")
print()
# rows
for team, row in enumerate(data):
teamlabel = teams_list[team]
while len(teamlabel) < 9:
teamlabel = " " + teamlabel
print(teamlabel, end="\t")
for entry in row:
print(entry, end="\t")
print()
Ouputs:
Man Utd Man City T Hotspur
Man Utd 1 2 1
Man City 0 1 0
T Hotspur 2 4 2
But this no longer seems any more simple than the other answers, with perhaps the benefit that it doesn't require any more imports. But @campkeith's answer already met that and is more robust as it can handle a wider variety of label lengths.
The correct pattern is to call the Redirect overload with endResponse=false and make a call to tell the IIS pipeline that it should advance directly to the EndRequest stage once you return control:
Response.Redirect(url, false);
Context.ApplicationInstance.CompleteRequest();
This blog post from Thomas Marquardt provides additional details, including how to handle the special case of redirecting inside an Application_Error handler.
Maybe the following is what you are looking for:
SELECT name, pathfilename
FROM table1
NATURAL JOIN table2
NATURAL JOIN table3
WHERE name = 'John';
Duplicated id
for pairs name
and city
:
select s.id, t.*
from [stuff] s
join (
select name, city, count(*) as qty
from [stuff]
group by name, city
having count(*) > 1
) t on s.name = t.name and s.city = t.city
I have also used following link as others have suggested you for bluetooth communication.
http://developer.android.com/guide/topics/connectivity/bluetooth.html
The thing is all you need is a class BluetoothChatService.java
this class has following threads:
Now when you call start function of the BluetoothChatService like:
mChatService.start();
It starts accept thread which means it will start looking for connection.
Now when you call
mChatService.connect(<deviceObject>,false/true);
Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.
connect
function will start connecting thread which will look for any device which is running accept thread.
When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:
connected(mmSocket, mmDevice, mSocketType);
this method starts connected thread in both the devices:
Using this socket object connected thread obtains the input and output stream to the other device.
And calls read
function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.
BluetoothChatService also has a write
method which takes byte[]
as input and calls write method on connected thread.
mChatService.write("your message".getByte());
write method in connected thread just write this byte data to outputsream of the other device.
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
// mHandler.obtainMessage(
// BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
// buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.
All the answers that are using the height
are only half part of the story for one reason. If you're going to check like that when device orientation is landscapeLeft
or landscapeRight
the check will fail, because the height
is swapped out with the width
.
That's why my solution looks like this in Swift 4.0:
extension UIScreen {
///
static var isPhoneX: Bool {
let screenSize = UIScreen.main.bounds.size
let width = screenSize.width
let height = screenSize.height
return min(width, height) == 375 && max(width, height) == 812
}
}
You can use a .Net environment Visual studio, Take a look at the differences with the PC version.
A lighter editor would be Visual Code
Alternatives :
Installing the Mono Project runtime . It allows you to re-compile the code and run it on a Mac, but this requires various alterations to the codebase, as the fuller .Net Framework is not available. (Also, WPF applications aren't supported here either.)
Virtual machine (VMWare Fusion perhaps)
Update your codebase to .Net Core, (before choosing this option take a look at this migration process)
.Net Core 3.1 is an open-source, free and available on Window, MacOs and Linux
As of September 14, a release candidate 1 of .Net Core 5.0 has been deployed on Window, MacOs and Linux.
[1] : Release candidate (RC) : releases providing early access to complete features. These releases are supported for production use when they have a go-live license
Another solution as seen here:
find var/log/ -iname "anaconda.*" -exec tar -cvzf file.tar.gz {} +
Your values
object is obviously an Object[]
containing a String[]
containing the values.
String[] stringValues = (String[])values[0];
You can check Visual Studio Downloads for available Visual Studio Community
, Visual Studio Professional
, Visual Studio Enterprise
and Visual Studio Code
download links.
Update!
There is no direct links of Visual Studio 2015
at Visual Studio Downloads anymore. but the below links still works.
OR simply click on direct links below (for .iso/.exe file):
VSCode area:
I would also note there are two ways to get the number of ms in the time point. I'm not sure which one is better, I've benchmarked them and they both have the same performance, so I guess it's a matter of preference. Perhaps Howard could chime in:
auto now = system_clock::now();
//Cast the time point to ms, then get its duration, then get the duration's count.
auto ms = time_point_cast<milliseconds>(now).time_since_epoch().count();
//Get the time point's duration, then cast to ms, then get its count.
auto ms = duration_cast<milliseconds>(tpBid.time_since_epoch()).count();
The first one reads more clearly in my mind going from left to right.
First download this JavaScript code, JSON2.js, that will help us serialize the object into a string.
In my example I'm posting the rows of a jqGrid via Ajax:
var commissions = new Array();
// Do several row data and do some push. In this example is just one push.
var rowData = $(GRID_AGENTS).getRowData(ids[i]);
commissions.push(rowData);
$.ajax({
type: "POST",
traditional: true,
url: '<%= Url.Content("~/") %>' + AREA + CONTROLLER + 'SubmitCommissions',
async: true,
data: JSON.stringify(commissions),
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.Result) {
jQuery(GRID_AGENTS).trigger('reloadGrid');
}
else {
jAlert("A problem ocurred during updating", "Commissions Report");
}
}
});
Now on the controller:
[HttpPost]
[JsonFilter(Param = "commissions", JsonDataType = typeof(List<CommissionsJs>))]
public ActionResult SubmitCommissions(List<CommissionsJs> commissions)
{
var result = dosomething(commissions);
var jsonData = new
{
Result = true,
Message = "Success"
};
if (result < 1)
{
jsonData = new
{
Result = false,
Message = "Problem"
};
}
return Json(jsonData);
}
Create a JsonFilter Class (thanks to JSC reference).
public class JsonFilter : ActionFilterAttribute
{
public string Param { get; set; }
public Type JsonDataType { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Request.ContentType.Contains("application/json"))
{
string inputContent;
using (var sr = new StreamReader(filterContext.HttpContext.Request.InputStream))
{
inputContent = sr.ReadToEnd();
}
var result = JsonConvert.DeserializeObject(inputContent, JsonDataType);
filterContext.ActionParameters[Param] = result;
}
}
}
Create another class so the filter can parse the JSON string to the actual manipulable object: This class comissionsJS are all the rows of my jqGrid.
public class CommissionsJs
{
public string Amount { get; set; }
public string CheckNumber { get; set; }
public string Contract { get; set; }
public string DatePayed { get; set; }
public string DealerName { get; set; }
public string ID { get; set; }
public string IdAgentPayment { get; set; }
public string Notes { get; set; }
public string PaymentMethodName { get; set; }
public string RowNumber { get; set; }
public string AgentId { get; set; }
}
I hope this example helps to illustrate how to post a complex object.
You can use the HTML tag in order to apply font size, font color in one line on JavaScript, as well as you can use .fontcolor()
method to define color, .fontsize()
method to define the font size, .bold()
method to define bold, etc. These are called JavaScript Built-in Functions.
Here is a list of some JavaScript built-in functions:
.big()
.small()
.italics()
.fixed()
.strike()
.sup()
The below built-in functions require parameters:
.fontsize() //e.g.: the size to be applied in number .fontsize(4)
.fontcolor("") //e.g.: the color to be applied in string .fontcolor("red")
.txt.link("") //e.g.: the url to be linkable as string .link("www.test.com")
.toUpperCase() //e.g.: the converted to uppercase to be applied in string .toUpperCase()
Remember the syntax is: string.functionName()
e.g.:
var txt = "Hello World!";
txt.bold();
This also can be done in one line:
var txt = "Hello World!".bold();
The result will be: Hello World!
You can use multiple built-in functions in one line, adding one next to the other. e.g.:
"10/22/2018".fontcolor("red").fontsize(4).bold()
The following is an example how I used it on my JavaScript code to change font (color, size, bold) using both HTML tags and JavaScript functions:
vForm.message = "<HTML><font size = 4 color = 'red'><b> Application Deadline was </b></font></HTML> " + "10/22/2018".fontcolor("red").fontsize(4).bold(); /* setting HTML font color, size, bold and combined them with JavaScript functions to change font color, size, bold in JavaScript code */
... in Powershell you can do something like this:
Get-Date (get-Date ((Get-Date) ) -format MM.yyyy)
... for the last month do this:
Get-Date (get-Date ((Get-Date).AddMonths(-1) ) -format MM.yyyy)
... or for custom Date do this:
Get-Date (get-Date ((Get-Date 12.01.2013) ) -format MM.yyyy)
Im sure there
s something like this possible ...
Gruß
Am I missing something ?
If you can't set visibility on TemplateField then set it on its content
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Visible='<%# MyBoolProperty %>' ID="foo" runat="server" ... />
</ItemTemplate>
</asp:TemplateField>
or if your content is complex then enclose it into a div and set visibility on the div
<asp:TemplateField>
<ItemTemplate>
<div runat="server" visible='<%# MyBoolProperty %>' >
<asp:LinkButton ID="attachmentButton" runat="server" ... />
</div>
</ItemTemplate>
</asp:TemplateField>
We can use splatting for this:
& $command @args
where @args
(automatic variable $args) is splatted into array of parameters.
Under PS, 5.1
try this:
import datetime
from datetime import datetime as dt
today_date = datetime.date.today()
date_time = dt.strptime(date_time_string, '%Y-%m-%d %H:%M')
strp() doesn't exist. I think you mean strptime.
Did you read clang
documentation ? You're probably looking for -emit-llvm
.
If you want to get values in Javascript on frontend, you can use the native way to do it by using :
document.getElementsByName("movie")[0].value;
Where "movie"
is the name of your input
<input type="text" name="movie">
If you want to get it on angular.js controller, you can use;
$scope.movie
<?php
if (isset($_POST['birthdate'])) {
$timestamp = strtotime($_POST['birthdate']);
$date=date('d',$timestamp);
$month=date('m',$timestamp);
$year=date('Y',$timestamp);
}
?>
public Map<String, String> parseJSON(JSONObject json, Map<String, String> dataFields) throws JSONException {
Iterator<String> keys = json.keys();
while (keys.hasNext()) {
String key = keys.next();
String val = null;
try {
JSONObject value = json.getJSONObject(key);
parseJSON(value, dataFields);
} catch (Exception e) {
if (json.isNull(key)) {
val = "";
} else {
try {
val = json.getString(key);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
if (val != null) {
dataFields.put(key, val);
}
}
return dataFields;
}
Your regular expression most likely wants to be
/\nSUMMARY:(.*)$/g
A helpful little trick I like to use is to default assign on match with an array.
var arr = iCalContent.match(/\nSUMMARY:(.*)$/g) || [""]; //could also use null for empty value
return arr[0];
This way you don't get annoying type errors when you go to use arr
I know this is an old post, but a good time to use PrimaryKeyColumn
would be if you wanted a unidirectional relationship or had multiple tables all sharing the same id.
In general this is a bad idea and it would be better to use foreign key relationships with JoinColumn
.
Having said that, if you are working on an older database that used a system like this then that would be a good time to use it.
Call me simple but I just declared a Variant and split the responsetext from my REST GET on the quote comma quote between each item, then got the value I wanted by looking for the last quote with InStrRev. I'm sure that's not as elegant as some of the other suggestions but it works for me.
varLines = Split(.responsetext, """,""")
strType = Mid(varLines(8), InStrRev(varLines(8), """") + 1)
This problem i had in my code. I will paste some example code i have over came below error. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
String query = "insert into STATION2(ID,CITY,STATE,LAT_N,LONG_W) values('" + a1 + "','" + b1 + "','" + c1 + "','" + d1 + "','" + f1 + "')";
//,'" + d1 + "','" + f1 + "','" + g1 + "'
SqlConnection con = new SqlConnection(mycon);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = con;
cmd.ExecuteNonQuery();
**con.Close();**
You want to close the connection each and every time. Before that i didn't us the close connect due to this i got error. After adding close statement i have over came this error
Basically you do the counts as sub-queries within a standard select.
An example would be the following, this returns 1 row, two columns
SELECT
(SELECT COUNT(*) FROM MyTable WHERE MyCol = 'MyValue') AS MyTableCount,
(SELECT COUNT(*) FROM YourTable WHERE MyCol = 'MyValue') AS YourTableCount,
For those who are still coming for solution here, the easiest solution would be to use <wsdlLocation>
, without changing any code. Working steps are given below:
src/main/resource
In pom file, add both wsdlDirectory and wsdlLocation(don't miss / at the beginning of wsdlLocation), like below. While wsdlDirectory is used to generate code and wsdlLocation is used at runtime to create dynamic proxy.
<wsdlDirectory>src/main/resources/mydir</wsdlDirectory>
<wsdlLocation>/mydir/my.wsdl</wsdlLocation>
Then in your java code(with no-arg constructor):
MyPort myPort = new MyPortService().getMyPort();
For completeness, I am providing here full code generation part, with fluent api in generated code.
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
<version>2.5</version>
<dependencies>
<dependency>
<groupId>org.jvnet.jaxb2_commons</groupId>
<artifactId>jaxb2-fluent-api</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-tools</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>wsdl-to-java-generator</id>
<goals>
<goal>wsimport</goal>
</goals>
<configuration>
<xjcArgs>
<xjcArg>-Xfluent-api</xjcArg>
</xjcArgs>
<keep>true</keep>
<wsdlDirectory>src/main/resources/package</wsdlDirectory>
<wsdlLocation>/package/my.wsdl</wsdlLocation>
<sourceDestDir>${project.build.directory}/generated-sources/annotations/jaxb</sourceDestDir>
<packageName>full.package.here</packageName>
</configuration>
</execution>
</executions>
What does the DTD have to say?
If the XML file is for communicating with other existing software (e.g., SOAP), then check that software for what it expects.
If the XML file is for serialisation or communication with non-existing software (e.g., the one you're writing), you can define it. In which case, I'd suggest something that is both easy to parse in your language(s) of choice, and easy to read for humans. e.g., if your language (whether VB.NET or C#.NET or whatever) allows you to parse ISO dates (YYYY-MM-DD) easily, that's the one I'd suggest.
One simple way to get all the queries you need is to use the data from information_schema and concat.
SELECT concat('CREATE TABLE new_db.', TABLE_NAME, ' LIKE old_db.', TABLE_NAME, ';') FROM `TABLES` WHERE TABLE_SCHEMA = 'old_db';
You'll then get a list of results that looks like this:
CREATE TABLE new_db.articles LIKE old_db.articles;
CREATE TABLE new_db.categories LIKE old_db.categories;
CREATE TABLE new_db.users LIKE old_db.users;
...
You can then just run those queries.
However it won't work with MySQL Views. You can avoid them by appending AND TABLE_TYPE = 'BASE TABLE'
from the initial query:
ES6 with Async / Await ,
let meaningOfLife = false;
async function waitForMeaningOfLife(){
while (true){
if (meaningOfLife) { console.log(42); return };
await null; // prevents app from hanging
}
}
waitForMeaningOfLife();
setTimeout(()=>meaningOfLife=true,420)
I don't know if it would work, but maybe you could break the page into columns using the multicol package.
\usepackage{multicol}
\begin{document}
\begin{multicols}{2}[Your list here]
\end{multicols}
First of all, you should use none of them. You are using wrapper
type, which should rarely be used in case you have a primitive type.
So, you should use boolean
rather.
Further, we initialize the boolean
variable to false
to hold an initial default value which is false. In case you have declared it as instance variable, it will automatically be initialized to false
.
But, its completely upto you, whether you assign a default value or not. I rather prefer to initialize them at the time of declaration.
But if you are immediately assigning to your variable, then you can directly assign a value to it, without having to define a default
value.
So, in your case I would use it like this: -
boolean isMatch = email1.equals (email2);
From Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning
the following
Excessive GC Time and OutOfMemoryError
The concurrent collector will throw an OutOfMemoryError if too much time is being spent in garbage collection: if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, an OutOfMemoryError will be thrown. This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small. If necessary, this feature can be disabled by adding the option -XX:-UseGCOverheadLimit to the command line.
The policy is the same as that in the parallel collector, except that time spent performing concurrent collections is not counted toward the 98% time limit. In other words, only collections performed while the application is stopped count toward excessive GC time. Such collections are typically due to a concurrent mode failure or an explicit collection request (e.g., a call to System.gc()).
in conjunction with a passage further down
One of the most commonly encountered uses of explicit garbage collection occurs with RMIs distributed garbage collection (DGC). Applications using RMI refer to objects in other virtual machines. Garbage cannot be collected in these distributed applications without occasionally collection the local heap, so RMI forces full collections periodically. The frequency of these collections can be controlled with properties. For example,
java -Dsun.rmi.dgc.client.gcInterval=3600000
-Dsun.rmi.dgc.server.gcInterval=3600000
specifies explicit collection once per hour instead of the default rate of once per minute. However, this may also cause some objects to take much longer to be reclaimed. These properties can be set as high as Long.MAX_VALUE to make the time between explicit collections effectively infinite, if there is no desire for an upper bound on the timeliness of DGC activity.
Seems to imply that the evaluation period for determining the 98% is one minute long, but it might be configurable on Sun's JVM with the correct define.
Of course, other interpretations are possible.
If you are using Jenkins templates you could have additional VM settings defined in it and this might conflicting with your system VM settings
example your tempalate may have references such as these
<mavenOpts>-Xms512m -Xmx1024m -Xss1024k -XX:MaxPermSize=1024m -Dmaven.test.failure.ignore=false</mavenOpts>
Ensure to align these template entries with the VM setting of your system
First, add it to .gitignore
, so it is not accidentally committed by you (or someone else) again:
.idea
Second, remove the directory only from the repository, but do not delete it locally. To achieve that, do what is listed here:
Remove a file from a Git repository without deleting it from the local filesystem
Third, commit the .gitignore
file and the removal of .idea
from the repository. After that push it to the remote(s).
The full process would look like this:
$ echo '.idea' >> .gitignore
$ git rm -r --cached .idea
$ git add .gitignore
$ git commit -m '(some message stating you added .idea to ignored entries)'
$ git push
(optionally you can replace last line with git push some_remote
, where some_remote
is the name of the remote you want to push to)
Yes. This error is a structured exception that wasn't mapped into a .NET error. It's probably your DataGrid mapping throwing a native exception that was uncaught.
You can tell what exception is occurring by looking at the ExternalException.ErrorCode property. I'd check your stack trace, and if it's tied to the DevExpress grid, report the problem to them.
No compiler worth its weight in salt will run differently between
for(int i=0; i<10; i++)
and
for(int i=0;i<10;++i)
++i and i++ have the same cost. The only thing that differs is that the return value of ++i is i+1 whereas the return value of i++ is i.
So for those prefering ++i, there's probably no valid justification, just personal preference.
EDIT: This is wrong for classes, as said in about every other post. i++ will generate a copy if i is a class.
Personally I would remove the returns and keep the breaks. I would use the switch statement to assign a value to a variable. Then return that variable after the switch statement.
Though this is an arguable point I've always felt that good design and encapsulation means one way in and one way out. It is much easier to guarantee the logic and you don't accidentally miss cleanup code based on the cyclomatic complexity of your function.
One exception: Returning early is okay if a bad parameter is detected at the beginning of a function--before any resources are acquired.
Use a slice, not an arrray. Just create it using
reg := []string {"a","b","c"}
An alternative would have been to convert your array to a slice when joining :
fmt.Println(strings.Join(reg[:],","))
Read the Go blog about the differences between slices and arrays.
This is more the Angular way to do it: http://plnkr.co/edit/xYNX47EsYvl4aRuGZmvo?p=preview
ng-click
. Your final requirements may be different, but using a directive to bind click
and change src
was overkill, since most of it can be handled with templatebackground-image
, then you'll need a directive like ngSrc that defers setting the background-image
style until after real data has loaded.To handle runtime permission google has provided a library project. You can check this from here https://github.com/googlesamples/easypermissions
EasyPermissions is installed by adding the following dependency to your build.gradle file:
dependencies {
compile 'pub.devrel:easypermissions:0.3.0'
}
To begin using EasyPermissions, have your Activity (or Fragment) override the onRequestPermissionsResult method:
public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// Forward results to EasyPermissions
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
@Override
public void onPermissionsGranted(int requestCode, List<String> list) {
// Some permissions have been granted
// ...
}
@Override
public void onPermissionsDenied(int requestCode, List<String> list) {
// Some permissions have been denied
// ...
}
}
Here you will get a working example how this library works https://github.com/milon87/EasyPermission
Self invoked function in javascript:
A self-invoking expression is invoked (started) automatically, without being called. A self-invoking expression is invoked right after its created. This is basically used for avoiding naming conflict as well as for achieving encapsulation. The variables or declared objects are not accessible outside this function. For avoiding the problems of minimization(filename.min) always use self executed function.
Dockerfile
is good if you only have one docker file (per-directory). You can use whatever standard you want if you need multiple docker files in the same directory -
if you have a good reason. In a recent project there were AWS docker files and local dev environment files because the environments differed enough:
Dockerfile
Dockerfile.aws
You start by writing a class that derives from Attribute:
public class MyCustomAttribute: Attribute
{
public string SomeProperty { get; set; }
}
Then you could decorate anything (class, method, property, ...) with this attribute:
[MyCustomAttribute(SomeProperty = "foo bar")]
public class Foo
{
}
and finally you would use reflection to fetch it:
var customAttributes = (MyCustomAttribute[])typeof(Foo).GetCustomAttributes(typeof(MyCustomAttribute), true);
if (customAttributes.Length > 0)
{
var myAttribute = customAttributes[0];
string value = myAttribute.SomeProperty;
// TODO: Do something with the value
}
You could limit the target types to which this custom attribute could be applied using the AttributeUsage attribute:
/// <summary>
/// This attribute can only be applied to classes
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class MyCustomAttribute : Attribute
Important things to know about attributes:
Couple of typos:
while((c = getchar())!= EOF)
in place of:
while((c = getchar() != EOF))
Also getchar() treats a return key as a valid input, so you need to buffer it too.EOF is a marker to indicate end of input. Generally it is an int with all bits set.
#include <stdio.h>
int main()
{
int c;
while((c = getchar())!= EOF)
{
if( getchar() == EOF )
break;
printf(" %d\n", c);
}
printf("%d %u %x- at EOF\n", c , c, c);
}
prints:
49 50 -1 4294967295 ffffffff- at EOF
for input:
1 2 <ctrl-d>
YourButton.Attributes.Add("onclick", "return false");
or
<asp:button runat="server" ... OnClientClick="return false" />
just open the bin folder and copy and paste the .dll files to the folder you are working in..it should fix the problem
The below example is self explainatory. where refs and events can be used to call function from and to parent and child.
// PARENT
<template>
<parent>
<child
@onChange="childCallBack"
ref="childRef"
:data="moduleData"
/>
<button @click="callChild">Call Method in child</button>
</parent>
</template>
<script>
export default {
methods: {
callChild() {
this.$refs.childRef.childMethod('Hi from parent');
},
childCallBack(message) {
console.log('message from child', message);
}
}
};
</script>
// CHILD
<template>
<child>
<button @click="callParent">Call Parent</button>
</child>
</template>
<script>
export default {
methods: {
callParent() {
this.$emit('onChange', 'hi from child');
},
childMethod(message) {
console.log('message from parent', message);
}
}
}
</script>
How about this?
WAITFOR DELAY '00:00:02';
If you have "00:02" it's interpreting that as Hours:Minutes.
Try this code...
ScriptManager.RegisterClientScriptBlock(UpdatePanel1, this.GetType(), "script", "alert('Hi');", true);
Where UpdatePanel1
is the id
for Updatepanel
on your page
I found this page in the documentation which has an objective-c enum for all of the error codes under the NSURLErrorDomain.
Here is a bit of code from one of my applications... Let me know if it suits your needs. You can use this if you know the file you want to use.
URL defaultImage = ClassA.class.getResource("/packageA/subPackage/image-name.png");
File imageFile = new File(defaultImage.toURI());
Hope that helps.
Be careful when accessing DateTime.Now twice, as it's possible for the calls to straddle midnight and you'll get wacky results on rare occasions and be left scratching your head.
To be safe, you should assign DateTime.Now to a local variable first if you're going to use it more than once:
var now = DateTime.Now;
var time = now.ToString("hh:mm:ss tt");
var date = now.ToString("MM/dd/yy");
Note the use of lower case "hh" do display hours from 00-11 even in the afternoon, and "tt" to show AM/PM, as the question requested. If you want 24 hour clock 00-23, use "HH".
For just one run (from the unix shell prompt):
$ PORT=1234 node app.js
More permanently:
$ export PORT=1234
$ node app.js
In Windows:
set PORT=1234
In Windows PowerShell:
$env:PORT = 1234
You can get the view Back if you put an ID to your Layout.
<RelativeLayout
android:id="@+id/my_relative_layout_id"
And call it from findViewById ...
$connect = new mysqli('localhost', 'user', 'password', 'db');
$result = $connect->query("select * from ...");
$count=$result->num_rows;
if(empty($count)){
echo"Query returned nothing";
}
else{
echo"query returned results";
}
Change your directive definition from app.module
to app.directive
. Apart from that everything looks fine.
Btw, very rarely do you have to inject a service into a directive. If you are injecting a service ( which usually is a data source or model ) into your directive ( which is kind of part of a view ), you are creating a direct coupling between your view and model. You need to separate them out by wiring them together using a controller.
It does work fine. I am not sure what you are doing which is wrong. Here is a plunk of it working.
Although the accepted answer is absolutely clear, I just wanted to check efficiency in terms of time.
The best way is to print joined string of numbers converted to strings.
print(" ".join(list(map(str,l))))
Note that I used map instead of loop. I wrote a little code of all 4 different ways to compare time:
import time as t
a, b = 10, 210000
l = list(range(a, b))
tic = t.time()
for i in l:
print(i, end=" ")
print()
tac = t.time()
t1 = (tac - tic) * 1000
print(*l)
toe = t.time()
t2 = (toe - tac) * 1000
print(" ".join([str(i) for i in l]))
joe = t.time()
t3 = (joe - toe) * 1000
print(" ".join(list(map(str, l))))
toy = t.time()
t4 = (toy - joe) * 1000
print("Time",t1,t2,t3,t4)
Result:
Time 74344.76 71790.83 196.99 153.99
The output was quite surprising to me. Huge difference of time in cases of 'loop method' and 'joined-string method'.
Conclusion: Do not use loops for printing list if size is too large( in order of 10**5 or more).
If the setTimeout function does not work for you either, then do the following:
//Create an iframe
iframe = $('body').append($('<iframe id="documentToPrint" name="documentToPrint" src="about:blank"/>'));
iframeElement = $('#documentToPrint')[0].contentWindow.document;
//Open the iframe
iframeElement.open();
//Write your content to the iframe
iframeElement.write($("yourContentId").html());
//This is the important bit.
//Wait for the iframe window to load, then print it.
$('#documentToPrint')[0].contentWindow.onload = function () {
$('#print-document')[0].contentWindow.print();
$('#print-document').remove();
};
iframeElement.close();
--- create a ws server vs2012 upd 3
new project
choose .net framework 3.5
asp.net web service application
right click on the project root
choose add service reference
choose wsdl
--- how can I create a ws client from a wsdl file?
I´ve a ws server Axis2 under tomcat 7 and I want to test the compatibility
easy but not efficient:
list(df.education).count('9th')
The solution for me was to set the AppPool from using the AppPoolIdentity to the NetworkService identity.
I couldn't get live or delegate to work on a div in a lightbox (tinybox).
I used setTimeout successfullly, in the following simple way:
$('#displayContact').click(function() {
TINY.box.show({html:'<form><textarea id="contactText"></textarea><div id="contactSubmit">Submit</div></form>', close:true});
setTimeout(setContactClick, 1000);
})
function setContactClick() {
$('#contactSubmit').click(function() {
alert($('#contactText').val());
})
}
The best way to help memory to be freed is to nullify large objects:
Sub Whatever()
Dim someLargeObject as SomeObject
'expensive computation
Set someLargeObject = Nothing
End Sub
Also note that global variables remain allocated from one call to another, so if you don't need persistence you should either not use global variables or nullify them when you don't need them any longer.
However this won't help if:
Another possibility is to switch to a 64 bit version of Excel which should be able to use more RAM before crashing (32 bits versions are typically limited at around 1.3GB).
I've tested this using the following powershell script and using (,) between the addresses. It worked for me!
$EmailFrom = "<[email protected]>";
$EmailPassword = "<password>";
$EmailTo = "<[email protected]>,<[email protected]>";
$SMTPServer = "<smtp.server.com>";
$SMTPPort = <port>;
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer,$SMTPPort);
$SMTPClient.EnableSsl = $true;
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom, $EmailPassword);
$Subject = "Notification from XYZ";
$Body = "this is a notification from XYZ Notifications..";
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body);
Retrieving the day of the week's number is dramatically simplified in Swift 3 because DateComponents
is no longer optional. Here it is as an extension:
extension Date {
func dayNumberOfWeek() -> Int? {
return Calendar.current.dateComponents([.weekday], from: self).weekday
}
}
// returns an integer from 1 - 7, with 1 being Sunday and 7 being Saturday
print(Date().dayNumberOfWeek()!) // 4
If you were looking for the written, localized version of the day of week:
extension Date {
func dayOfWeek() -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE"
return dateFormatter.string(from: self).capitalized
// or use capitalized(with: locale) if you want
}
}
print(Date().dayOfWeek()!) // Wednesday
There are two different Lambda integrations you can configure in API Gateway, such as Lambda integration and Lambda proxy integration. For Lambda integration, you can customise what you are going to pass to Lambda in the payload that you don't need to parse the body, but when you are using Lambda Proxy integration in API Gateway, API Gateway will proxy everything to Lambda in payload like this,
{
"message": "Hello me!",
"input": {
"path": "/test/hello",
"headers": {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, lzma, sdch, br",
"Accept-Language": "en-US,en;q=0.8",
"CloudFront-Forwarded-Proto": "https",
"CloudFront-Is-Desktop-Viewer": "true",
"CloudFront-Is-Mobile-Viewer": "false",
"CloudFront-Is-SmartTV-Viewer": "false",
"CloudFront-Is-Tablet-Viewer": "false",
"CloudFront-Viewer-Country": "US",
"Host": "wt6mne2s9k.execute-api.us-west-2.amazonaws.com",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 OPR/39.0.2256.48",
"Via": "1.1 fb7cca60f0ecd82ce07790c9c5eef16c.cloudfront.net (CloudFront)",
"X-Amz-Cf-Id": "nBsWBOrSHMgnaROZJK1wGCZ9PcRcSpq_oSXZNQwQ10OTZL4cimZo3g==",
"X-Forwarded-For": "192.168.100.1, 192.168.1.1",
"X-Forwarded-Port": "443",
"X-Forwarded-Proto": "https"
},
"pathParameters": {"proxy": "hello"},
"requestContext": {
"accountId": "123456789012",
"resourceId": "us4z18",
"stage": "test",
"requestId": "41b45ea3-70b5-11e6-b7bd-69b5aaebc7d9",
"identity": {
"cognitoIdentityPoolId": "",
"accountId": "",
"cognitoIdentityId": "",
"caller": "",
"apiKey": "",
"sourceIp": "192.168.100.1",
"cognitoAuthenticationType": "",
"cognitoAuthenticationProvider": "",
"userArn": "",
"userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 OPR/39.0.2256.48",
"user": ""
},
"resourcePath": "/{proxy+}",
"httpMethod": "GET",
"apiId": "wt6mne2s9k"
},
"resource": "/{proxy+}",
"httpMethod": "GET",
"queryStringParameters": {"name": "me"},
"stageVariables": {"stageVarName": "stageVarValue"},
"body": "{\"foo\":\"bar\"}",
"isBase64Encoded": false
}
}
For the example you are referencing, it is not getting the body from the original request. It is constructing the response body back to API Gateway. It should be in this format,
{
"statusCode": httpStatusCode,
"headers": { "headerName": "headerValue", ... },
"body": "...",
"isBase64Encoded": false
}
Yes sure, provided you have its context. (See how to get canvas context here.)
var imgData = context.getImageData(0,0,canvas.width,canvas.height);
// { data: [r,g,b,a,r,g,b,a,r,g,..], ... }
function getPixel(imgData, index) {
var i = index*4, d = imgData.data;
return [d[i],d[i+1],d[i+2],d[i+3]] // Returns array [R,G,B,A]
}
// AND/OR
function getPixelXY(imgData, x, y) {
return getPixel(imgData, y*imgData.width+x);
}
PS: If you plan to mutate the data and draw them back on the canvas, you can use subarray
var
idt = imgData, // See previous code snippet
a = getPixel(idt, 188411), // Array(4) [0, 251, 0, 255]
b = idt.data.subarray(188411*4, 188411*4 + 4) // Uint8ClampedArray(4) [0, 251, 0, 255]
a[0] = 255 // Does nothing
getPixel(idt, 188411), // Array(4) [0, 251, 0, 255]
b[0] = 255 // Mutates the original imgData.data
getPixel(idt, 188411), // Array(4) [255, 251, 0, 255]
// Or use it in the function
function getPixel(imgData, index) {
var i = index*4, d = imgData.data;
return imgData.data.subarray(index, index+4) // Returns subarray [R,G,B,A]
}
You can experiment with this on http://qry.me/xyscope/, the code for this is in the source, just copy/paste it in the console.
You can retrieve them from memory.
So first you get the rows in a DataSet, and then get the last 5 out of the DataSet.
popup method will give a secure question to visitor..
here is my simple solution: and working everyhere.
<script type="text/javascript">
function targetMeBlank() {
document.forms[0].target = "_blank";
}
</script>
<asp:linkbutton runat="server" ID="lnkbtn1" Text="target me to blank dude" OnClick="lnkbtn1_Click" OnClientClick="targetMeBlank();"/>
Note that if you use SELECT FOR UPDATE
to perform a uniqueness check before an insert, you will get a deadlock for every race condition unless you enable the innodb_locks_unsafe_for_binlog
option. A deadlock-free method to check uniqueness is to blindly insert a row into a table with a unique index using INSERT IGNORE
, then to check the affected row count.
add below line to my.cnf
file
innodb_locks_unsafe_for_binlog = 1
#1 - ON
0 - OFF
Using JavaScript
public ActionResult Index()
{
return Content("<script>window.location = 'http://www.example.com';</script>");
}
Note: As @Jeremy Ray Brown said , This is not the best option but you might find useful in some situations.
Hope this helps.