Here is a heavy tutorial that has good stuff in it to pick out:
http://mobile.tutsplus.com/tutorials/mobile-web-apps/jquery_android/
You can use np.logaddexp
(which implements the idea in @gg349's answer):
In [33]: d = np.array([[1089, 1093]])
In [34]: e = np.array([[1000, 4443]])
In [35]: log_res = np.logaddexp(-3*d[0,0], -3*d[0,1]) - np.logaddexp(-3*e[0,0], -3*e[0,1])
In [36]: log_res
Out[36]: -266.99999385580668
In [37]: res = exp(log_res)
In [38]: res
Out[38]: 1.1050349147204485e-116
Or you can use scipy.special.logsumexp
:
In [52]: from scipy.special import logsumexp
In [53]: res = np.exp(logsumexp(-3*d) - logsumexp(-3*e))
In [54]: res
Out[54]: 1.1050349147204485e-116
Select Project->Properties from the menu bar.
Click C/C++ Build on the left in the dialog that comes up.
More elegant approach:
echo "Memory usage for PID <>:"; for mem in {Private,Rss,Shared,Swap,Pss};do grep $mem /proc/<pid>/smaps | awk -v mem_type="$mem" '{i=i+$2} END {print mem_type,"memory usage:"i}' ;done
catch
ing in this fashion, in my experience, is dangerous. Any error thrown in the entire stack will be caught, not just an error from this promise (which is probably not what you want).
The second argument to a promise is already a rejection/failure callback. It's better and safer to use that instead.
Here's a typescript typesafe one-liner I wrote to handle this:
function wait<R, E>(promise: Promise<R>): [R | null, E | null] {
return (promise.then((data: R) => [data, null], (err: E) => [null, err]) as any) as [R, E];
}
// Usage
const [currUser, currUserError] = await wait<GetCurrentUser_user, GetCurrentUser_errors>(
apiClient.getCurrentUser()
);
NASDAQ offers 10 years of historical EOD data for each symbol
http://www.nasdaq.com/aspx/historical_quotes.aspx?symbol=AAPL&selected=AAPL
You could automate the process of downloading this data.
If you're facing this issue with macOS Catalina, I recommend these steps:
Install Homebrew (if you haven't already done so): head over to brew.sh or simply run this command: /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Run brew install [email protected]
Update your $PATH variable to include the newly installed version of php:
echo 'export PATH="/usr/local/opt/[email protected]/bin:$PATH"' >> ~/.zshrc
echo 'export PATH="/usr/local/opt/[email protected]/sbin:$PATH"' >> ~/.zshrc
Reload your shell preferences script $ source ~/.zshrc
or source ~/.bashrc
Finally, install laravel: composer global require laravel/installer
Try this:
HTML:
<input type="submit" value="submit" name="submit" onclick="myfunction()">
jQuery:
<script type="text/javascript">
function myfunction()
{
var url = $(location).attr('href');
$('#spn_url').html('<strong>' + url + '</strong>');
}
</script>
How to create database in MySQL Workbench 6.3
I have not used BeuatifulSoup but maybe the following can help in some tiny way.
import re
import urllib2
stuff = urllib2.urlopen(your_url_goes_here).read() # stuff will contain the *entire* page
# Replace the string Python with your desired regex
results = re.findall('(Python)',stuff)
for i in results:
print i
I'm not suggesting this is a replacement but maybe you can glean some value in the concept until a direct answer comes along.
Simpler and a Standard solution to increment the number and to retain the dot at the end. Even if you get the css right, it will not work if your HTML is not correct. see below.
ol {
counter-reset: item;
}
ol li {
display: block;
}
ol li:before {
content: counters(item, ". ") ". ";
counter-increment: item;
}
ol {
counter-reset: item;
li {
display: block;
&:before {
content: counters(item, ". ") ". ";
counter-increment: item
}
}
}
If you add the child make sure the it is under the parent li
.
<!-- WRONG -->
<ol>
<li>Parent 1</li> <!-- Parent is Individual. Not hugging -->
<ol>
<li>Child</li>
</ol>
<li>Parent 2</li>
</ol>
<!-- RIGHT -->
<ol>
<li>Parent 1
<ol>
<li>Child</li>
</ol>
</li> <!-- Parent is Hugging the child -->
<li>Parent 2</li>
</ol>
Only call time pass-by-reference is removed. So change:
call_user_func($func, &$this, &$client ...
To this:
call_user_func($func, $this, $client ...
&$this
should never be needed after PHP4 anyway period.
If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {
)
I had a similar problem. I am posting my solution here because I believe it might help one of the commenters.
For me, the obstacle was that the page required a login and then gave me a new URL through javascript. Here is what I had to do:
curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <URL>
Note that j_username
and j_password
is the name of the fields for my website's login form. You will have to open the source of the webpage to see what the 'name' of the username field and the 'name' of the password field is in your case.
After that I go an html file with java script in which the new URL was embedded. After parsing this out just resubmit with the new URL:
curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <NEWURL>
Quick and dirty?
#!/bin/sh
if [ -f sometempfile ]
echo "Already running... will now terminate."
exit
else
touch sometempfile
fi
..do what you want here..
rm sometempfile
I recently had to do this with google's search box, this is an extreme hack reserved for extreme situations (the resulting selector was slightly different, but I made it work in this example)
/*_x000D_
this is just used to calculate the resulting svg data url and need not be included in the final page_x000D_
*/_x000D_
_x000D_
var text = placeholder.outerHTML;_x000D_
var url = "data:image/svg+xml;,"+text.replace(/id="placeholder"/g," ").replace(/\n|([ ] )/g,"");//.replace(/" /g,"\"");_x000D_
img.src = url;_x000D_
result.value = url;_x000D_
overlay.style.backgroundImage = "url('"+url+"')";
_x000D_
svg,img{_x000D_
border: 3px dashed black;_x000D_
}_x000D_
textarea{_x000D_
width:50%;_x000D_
height:300px;_x000D_
vertical-align: top;_x000D_
}_x000D_
.wrapper{_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
}_x000D_
#overlay{_x000D_
position:absolute;_x000D_
left:0;_x000D_
top:0;_x000D_
right:0;_x000D_
bottom:0;_x000D_
pointer-events: none;_x000D_
background-repeat: no-repeat;_x000D_
background-position: center left;_x000D_
}_x000D_
#my_input:focus + #overlay{_x000D_
display: none;_x000D_
}
_x000D_
As SVG <svg id="placeholder"xmlns="http://www.w3.org/2000/svg"width="235"height="13"><text x="0"y="10"font-family="Verdana"font-size="12" fill ="green">Some New Rad Placeholder</text></svg>_x000D_
<br>_x000D_
As IMG <img id="img">_x000D_
<br>_x000D_
As Data URI <textarea id="result"></textarea><br>_x000D_
_x000D_
As "Placeholder" <div class="wrapper">_x000D_
<input id="my_input" />_x000D_
<div id="overlay">_x000D_
</div>
_x000D_
Actually, VSCode shows you the preview of a file when you open it. If you want to open files in a new tab, just disable the preview with this setting (paste this in the settings.json file).
"workbench.editor.enablePreview": false,
— you can take it one step further and use this setting
"workbench.startupEditor": "newUntitledFile",
— It will open your VSCode editor with a blank new untitled file to quickly get started.
require(ggplot2)
require(nlme)
set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)
mp <- within(mp,
{
wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
wow <- rnorm(N)*wav+rnorm(N)*wav^3
})
m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))
Get fitted values (the same as m01$fitted
)
fit <- predict(m01)
Normally we could use something like predict(...,se.fit=TRUE)
to get the confidence intervals on the prediction, but gls
doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :
V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))
Put together a "prediction frame":
predframe <- with(mp,data.frame(year,wav,
wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))
Now plot with geom_ribbon
(p1 <- ggplot(mp, aes(year, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It's easier to see that we got the right answer if we plot against wav
rather than year
:
(p2 <- ggplot(mp, aes(wav, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly()
fits -- see ?makepredictcall
.
I'm just starting some string manipulations and found this question. I was probably trying to do something like the OP, "usual me". The previous answers did not clear up my confusion, but after thinking a little about it I finally "got it".
As long as a
, b
, c
, d
, and e
have the same value, they reference to the same place. Memory is saved. As soon as the variable start to have different values, they get start to have different references. My learning experience came from this code:
import copy
a = 'hello'
b = str(a)
c = a[:]
d = a + ''
e = copy.copy(a)
print map( id, [ a,b,c,d,e ] )
print a, b, c, d, e
e = a + 'something'
a = 'goodbye'
print map( id, [ a,b,c,d,e ] )
print a, b, c, d, e
The printed output is:
[4538504992, 4538504992, 4538504992, 4538504992, 4538504992]
hello hello hello hello hello
[6113502048, 4538504992, 4538504992, 4538504992, 5570935808]
goodbye hello hello hello hello something
I would suggest to remove the rows from the underlying DataTable, or if you don't need the datatable anymore, set the datasource to null.
$about = DB::where('page', 'about-me')->first();
in stead of get()
.
It works on my project. Thanks.
You can press q to exit.
git hist
is using a pager tool so you can scroll up and down the results before returning to the console.
Short answer: Use the change
event. Here's a couple of practical examples. Since I misread the question, I'll include jQuery examples along with plain JavaScript. You're not gaining much, if anything, by using jQuery though.
Using querySelector
.
var checkbox = document.querySelector("input[name=checkbox]");
checkbox.addEventListener('change', function() {
if (this.checked) {
console.log("Checkbox is checked..");
} else {
console.log("Checkbox is not checked..");
}
});
_x000D_
<input type="checkbox" name="checkbox" />
_x000D_
$('input[name=checkbox]').change(function() {
if ($(this).is(':checked')) {
console.log("Checkbox is checked..")
} else {
console.log("Checkbox is not checked..")
}
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox" />
_x000D_
Here's an example of a list of checkboxes. To select multiple elements we use querySelectorAll
instead of querySelector
. Then use Array.filter
and Array.map
to extract checked values.
// Select all checkboxes with the name 'settings' using querySelectorAll.
var checkboxes = document.querySelectorAll("input[type=checkbox][name=settings]");
let enabledSettings = []
/*
For IE11 support, replace arrow functions with normal functions and
use a polyfill for Array.forEach:
https://vanillajstoolkit.com/polyfills/arrayforeach/
*/
// Use Array.forEach to add an event listener to each checkbox.
checkboxes.forEach(function(checkbox) {
checkbox.addEventListener('change', function() {
enabledSettings =
Array.from(checkboxes) // Convert checkboxes to an array to use filter and map.
.filter(i => i.checked) // Use Array.filter to remove unchecked checkboxes.
.map(i => i.value) // Use Array.map to extract only the checkbox values from the array of objects.
console.log(enabledSettings)
})
});
_x000D_
<label>
<input type="checkbox" name="settings" value="forcefield">
Enable forcefield
</label>
<label>
<input type="checkbox" name="settings" value="invisibilitycloak">
Enable invisibility cloak
</label>
<label>
<input type="checkbox" name="settings" value="warpspeed">
Enable warp speed
</label>
_x000D_
let checkboxes = $("input[type=checkbox][name=settings]")
let enabledSettings = [];
// Attach a change event handler to the checkboxes.
checkboxes.change(function() {
enabledSettings = checkboxes
.filter(":checked") // Filter out unchecked boxes.
.map(function() { // Extract values using jQuery map.
return this.value;
})
.get() // Get array.
console.log(enabledSettings);
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
<input type="checkbox" name="settings" value="forcefield">
Enable forcefield
</label>
<label>
<input type="checkbox" name="settings" value="invisibilitycloak">
Enable invisibility cloak
</label>
<label>
<input type="checkbox" name="settings" value="warpspeed">
Enable warp speed
</label>
_x000D_
You're doing only one mistake.
use replaceAll()
function over there.
e.g.
String str = "Hi";
String str1 = "hello";
str.replaceAll( str, str1 );
Combination of all of these suggestions, and the reasons behind them. Feel free to add more test cases too. If getting the client IP is of utmost importance, than you might wan to get all of theses are run some comparisons on which result might be more accurate.
Simple check of all suggestions in this thread plus some of my own code...
using System.IO;
using System.Net;
public string GetUserIP()
{
string strIP = String.Empty;
HttpRequest httpReq = HttpContext.Current.Request;
//test for non-standard proxy server designations of client's IP
if (httpReq.ServerVariables["HTTP_CLIENT_IP"] != null)
{
strIP = httpReq.ServerVariables["HTTP_CLIENT_IP"].ToString();
}
else if (httpReq.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
strIP = httpReq.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
//test for host address reported by the server
else if
(
//if exists
(httpReq.UserHostAddress.Length != 0)
&&
//and if not localhost IPV6 or localhost name
((httpReq.UserHostAddress != "::1") || (httpReq.UserHostAddress != "localhost"))
)
{
strIP = httpReq.UserHostAddress;
}
//finally, if all else fails, get the IP from a web scrape of another server
else
{
WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
using (WebResponse response = request.GetResponse())
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
strIP = sr.ReadToEnd();
}
//scrape ip from the html
int i1 = strIP.IndexOf("Address: ") + 9;
int i2 = strIP.LastIndexOf("</body>");
strIP = strIP.Substring(i1, i2 - i1);
}
return strIP;
}
Here is an example that shows the differences, which will help with the explanation.
var s1 = new String("Avoid newing things where possible");
var s2 = "A string, in TypeScript of type 'string'";
var s3: string;
String
is the JavaScript String type, which you could use to create new strings. Nobody does this as in JavaScript the literals are considered better, so s2
in the example above creates a new string without the use of the new
keyword and without explicitly using the String
object.
string
is the TypeScript string type, which you can use to type variables, parameters and return values.
Additional notes...
Currently (Feb 2013) Both s1
and s2
are valid JavaScript. s3
is valid TypeScript.
Use of String
. You probably never need to use it, string literals are universally accepted as being the correct way to initialise a string. In JavaScript, it is also considered better to use object literals and array literals too:
var arr = []; // not var arr = new Array();
var obj = {}; // not var obj = new Object();
If you really had a penchant for the string, you could use it in TypeScript in one of two ways...
var str: String = new String("Hello world"); // Uses the JavaScript String object
var str: string = String("Hello World"); // Uses the TypeScript string type
Set the Maximise property to False.
One way is to add the item(s) to be deleted to a new list. Then go through and delete those items.
I don’t know for sure but I’m reading a book right now and what I am getting is that a program need to handle its signal ( as when I press CTRL-C
). Now a program can use SIG_IGN
to ignore all signals or SIG_DFL
to restore the default action.
Now if you do $ command &
then this process running as background process simply ignores all signals that will occur. For foreground processes these signals are not ignored.
Largest table I've encountered on SQL Server 8 on Windows2003 was 799 million with 5 columns. But whether or not it's good will is to be measured against the SLA and usage case - e.g. load 50-100,000,000 records and see if it still works.
This code snippet is working properly
Here is what I do. All of these instructions are based on my minimal experiences with working PACs, so YMMV.
Download your pac file via your pac URL. It's plain text and should be easy to open in a text editor.
Near the bottom, there's probably a section that says something like: return "PROXY w.x.y.z:a" where "w.x.y.z" is an ip address or username and "a" is a port number.
Write these down.
In a recent version of eclipse :
At this point, you should be able to browse using the internal web browser (at least on http URLs).
Good luck.
Edit:
Just so you know, it's WAY easier to use Nexus, one set of <mirror>
tags and a single proxy setup (inside Nexus) to manage the proxy issues of Maven inside a firewall.
The following is a summary of what you need to do under OS X Mavericks (10.9). This is all summarized in
http://hints.macworld.com/article.php?story=20060825071728278
Go to Terminal->Preferences->Settings->Advanced.
Under International, make sure the character encoding is set to Unicode (UTF-8).
Also, and this is key: under Emulation, make sure that Escape non-ASCII input with Control-V is unchecked (i.e. is not set).
These two settings fix things for Terminal.
Make sure your locale is set to something that ends in .UTF-8
. Type locale
and look at the LC_CTYPE
line. If it doesn't say something like en_US.UTF-8
(the stuff before the dot might change if you are using a non-US-English locale), then in your Bash .profile
or .bashrc
in your home directory, add a line like this:
export LC_CTYPE=en_US.UTF-8
This will fix things for command-line programs in general.
Add the following lines to .inputrc
in your home directory (create it if necessary):
set meta-flag on
set input-meta on
set output-meta on
set convert-meta off
This makes Bash be eight-bit clean, so it will pass UTF-8 characters in and out without messing with them.
Keep in mind you will have to restart Bash (e.g. close and reopen the Terminal window) to get it to pay attention to all the settings you make in 2 and 3 above.
The best is QSpinBox
.
And for a double value use QDoubleSpinBox
.
QSpinBox myInt;
myInt.setMinimum(-5);
myInt.setMaximum(5);
myInt.setSingleStep(1);// Will increment the current value with 1 (if you use up arrow key) (if you use down arrow key => -1)
myInt.setValue(2);// Default/begining value
myInt.value();// Get the current value
//connect(&myInt, SIGNAL(valueChanged(int)), this, SLOT(myValueChanged(int)));
The number is held in an int[]
- the maximum size of an array is Integer.MAX_VALUE
. So the maximum BigInteger probably is (2 ^ 32) ^ Integer.MAX_VALUE
.
Admittedly, this is implementation dependent, not part of the specification.
In Java 8, some information was added to the BigInteger javadoc, giving a minimum supported range and the actual limit of the current implementation:
BigInteger
must support values in the range-2
Integer.MAX_VALUE
(exclusive) to+2
Integer.MAX_VALUE
(exclusive) and may support values outside of that range.Implementation note:
BigInteger
constructors and operations throwArithmeticException
when the result is out of the supported range of-2
Integer.MAX_VALUE
(exclusive) to+2
Integer.MAX_VALUE
(exclusive).
The fix is to modify your EDMX file, using the XML editor, and change the value of ProviderManifestToken from 2012 to 2008. I found that on line 7 in my EDMX file. After saving that change, the paging SQL will be generated using the “old”, SQL Server 2008 compatible syntax.
My apologies for posting an answer on this very old thread. Posting it for the people like me, I solved this issue today.
The answer by @felix almost brought me there. I had two issues:
The following setup resolves this
jar {
manifest {
attributes(
'Main-Class': 'my.project.main',
)
}
}
task fatJar(type: Jar) {
manifest.from jar.manifest
classifier = 'all'
from {
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
} {
exclude "META-INF/*.SF"
exclude "META-INF/*.DSA"
exclude "META-INF/*.RSA"
}
with jar
}
To add this to the standard assemble or build task, add:
artifacts {
archives fatJar
}
Edit: thanks to @mjaggard: in recent versions of Gradle, change configurations.runtime
to configurations.runtimeClasspath
I created .pfx file from .key and .pem files.
Like this openssl pkcs12 -inkey rootCA.key -in rootCA.pem -export -out rootCA.pfx
That's not the direct answer but still maybe it helps out someone else.
http://code.google.com/p/javascript-number-formatter/ :
UPDATE This is my home grown pp
utilities for most common tasks:
var NumUtil = {};
/**
Petty print 'num' wth exactly 'signif' digits.
pp(123.45, 2) == "120"
pp(0.012343, 3) == "0.0123"
pp(1.2, 3) == "1.20"
*/
NumUtil.pp = function(num, signif) {
if (typeof(num) !== "number")
throw 'NumUtil.pp: num is not a number!';
if (isNaN(num))
throw 'NumUtil.pp: num is NaN!';
if (num < 1e-15 || num > 1e15)
return num;
var r = Math.log(num)/Math.LN10;
var dot = Math.floor(r) - (signif-1);
r = r - Math.floor(r) + (signif-1);
r = Math.round(Math.exp(r * Math.LN10)).toString();
if (dot >= 0) {
for (; dot > 0; dot -= 1)
r += "0";
return r;
} else if (-dot >= r.length) {
var p = "0.";
for (; -dot > r.length; dot += 1) {
p += "0";
}
return p+r;
} else {
return r.substring(0, r.length + dot) + "." + r.substring(r.length + dot);
}
}
/** Append leading zeros up to 2 digits. */
NumUtil.align2 = function(v) {
if (v < 10)
return "0"+v;
return ""+v;
}
/** Append leading zeros up to 3 digits. */
NumUtil.align3 = function(v) {
if (v < 10)
return "00"+v;
else if (v < 100)
return "0"+v;
return ""+v;
}
NumUtil.integer = {};
/** Round to integer and group by 3 digits. */
NumUtil.integer.pp = function(num) {
if (typeof(num) !== "number") {
console.log("%s", new Error().stack);
throw 'NumUtil.integer.pp: num is not a number!';
}
if (isNaN(num))
throw 'NumUtil.integer.pp: num is NaN!';
if (num > 1e15)
return num;
if (num < 0)
throw 'Negative num!';
num = Math.round(num);
var group = num % 1000;
var integ = Math.floor(num / 1000);
if (integ === 0) {
return group;
}
num = NumUtil.align3(group);
while (true) {
group = integ % 1000;
integ = Math.floor(integ / 1000);
if (integ === 0)
return group + " " + num;
num = NumUtil.align3(group) + " " + num;
}
return num;
}
NumUtil.currency = {};
/** Round to coins and group by 3 digits. */
NumUtil.currency.pp = function(amount) {
if (typeof(amount) !== "number")
throw 'NumUtil.currency.pp: amount is not a number!';
if (isNaN(amount))
throw 'NumUtil.currency.pp: amount is NaN!';
if (amount > 1e15)
return amount;
if (amount < 0)
throw 'Negative amount!';
if (amount < 1e-2)
return 0;
var v = Math.round(amount*100);
var integ = Math.floor(v / 100);
var frac = NumUtil.align2(v % 100);
var group = integ % 1000;
integ = Math.floor(integ / 1000);
if (integ === 0) {
return group + "." + frac;
}
amount = NumUtil.align3(group);
while (true) {
group = integ % 1000;
integ = Math.floor(integ / 1000);
if (integ === 0)
return group + " " + amount + "." + frac;
amount = NumUtil.align3(group) + " " + amount;
}
return amount;
}
private OutputStream outputStream;
private InputStream inStream;
private void init() throws IOException {
BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
if (blueAdapter != null) {
if (blueAdapter.isEnabled()) {
Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();
if(bondedDevices.size() > 0) {
Object[] devices = (Object []) bondedDevices.toArray();
BluetoothDevice device = (BluetoothDevice) devices[position];
ParcelUuid[] uuids = device.getUuids();
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
socket.connect();
outputStream = socket.getOutputStream();
inStream = socket.getInputStream();
}
Log.e("error", "No appropriate paired devices.");
} else {
Log.e("error", "Bluetooth is disabled.");
}
}
}
public void write(String s) throws IOException {
outputStream.write(s.getBytes());
}
public void run() {
final int BUFFER_SIZE = 1024;
byte[] buffer = new byte[BUFFER_SIZE];
int bytes = 0;
int b = BUFFER_SIZE;
while (true) {
try {
bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
nohup some_command &> nohup2.out &
and voila.
Older syntax for Bash version < 4:
nohup some_command > nohup2.out 2>&1 &
In UNIX systems, you can append to the LD_LIBRARY_PATH environment variable. On Windows, the JVM automatically sets the system property, java.library.path, to PATH; so if the dll is on your PATH, then you're set.
I've done this before successfully - I have some code at home. When I get home tonight, I'll update this answer with the working code of a service launching a console app.
I thought I'd try this from scratch. Here's some code I wrote that launches a console app. I installed it as a service and ran it and it worked properly: cmd.exe launches (as seen in Task Manager) and lives for 10 seconds until I send it the exit command. I hope this helps your situation as it does work properly as expected here.
using (System.Diagnostics.Process process = new System.Diagnostics.Process())
{
process.StartInfo = new System.Diagnostics.ProcessStartInfo(@"c:\windows\system32\cmd.exe");
process.StartInfo.CreateNoWindow = true;
process.StartInfo.ErrorDialog = false;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
process.Start();
//// do some other things while you wait...
System.Threading.Thread.Sleep(10000); // simulate doing other things...
process.StandardInput.WriteLine("exit"); // tell console to exit
if (!process.HasExited)
{
process.WaitForExit(120000); // give 2 minutes for process to finish
if (!process.HasExited)
{
process.Kill(); // took too long, kill it off
}
}
}
With the constructor:
// create a vector with 20 integer elements
std::vector<int> arr(20);
for(int x = 0; x < 20; ++x)
arr[x] = x;
Package & install are various phases in maven build lifecycle. package phase will execute all phases prior to that & it will stop with packaging the project as a jar. Similarly install phase will execute all prior phases & finally install the project locally for other dependent projects.
For understanding maven build lifecycle please go through the following link https://ayolajayamaha.blogspot.in/2014/05/difference-between-mvn-clean-install.html
I was recieving the same error when I was tring to call an object element by using another objects return value like;
$this->array1 = a json table which returns country codes of the ip
$this->array2 = a json table which returns languages of the country codes
$this->array2->$this->array1->country;// Error line
The above code was throwing the error and I tried many ways to fix it like; calling this part $this->array1->country
in another function as return value, (string)
, taking it into quotations etc. I couldn't even find the solution on the web then i realised that the solution was very simple. All you have to do it wrap it with curly brackets and that allows you to target an object with another object's element value. like;
$this->array1 = a json table which returns country codes of the ip
$this->array2 = a json table which returns languages of the country codes
$this->array2->{$this->array1->country};
If anyone facing the same and couldn't find the answer, I hope this can help because i spend a night for this simple solution =)
With
git config -l
, I now see I have acredential.helper=osxkeychain
option
That means the credential helper (initially introduced in 1.7.10) is now in effect, and will cache automatically the password for accessing a remote repository over HTTP.
(as in "GIT: Any way to set default login credentials?")
You can disable that option entirely, or only for a single repo.
You told your repository to rebase. It looks like you were on a commit (identified by SHA 9c168a5) and then did git rebase master
or git pull --rebase master
.
You are rebasing the branch master onto that commit. You can end the rebase via git rebase --abort
. This would put back at the state that you were at before you started rebasing.
Since pandas 1.0.0 df.sort_values
has a new parameter ignore_index
which does exactly what you need:
In [1]: df2 = df.sort_values(by=['x','y'],ignore_index=True)
In [2]: df2
Out[2]:
x y
0 0 0
1 0 1
2 0 2
3 1 0
4 1 1
5 1 2
6 2 0
7 2 1
8 2 2
Yes, you can configure the Spring servlet context xml file to define your beans (i.e., classes), so that it can do the automatic injection for you. However, do note, that you have to do other configurations to have Spring up and running and the best way to do that, is to follow a tutorial ground up.
Once you have your Spring configured probably, you can do the following in your Spring servlet context xml file for Example 1 above to work (please replace the package name of com.movies to what the true package name is and if this is a 3rd party class, then be sure that the appropriate jar file is on the classpath) :
<beans:bean id="movieFinder" class="com.movies.MovieFinder" />
or if the MovieFinder class has a constructor with a primitive value, then you could something like this,
<beans:bean id="movieFinder" class="com.movies.MovieFinder" >
<beans:constructor-arg value="100" />
</beans:bean>
or if the MovieFinder class has a constructor expecting another class, then you could do something like this,
<beans:bean id="movieFinder" class="com.movies.MovieFinder" >
<beans:constructor-arg ref="otherBeanRef" />
</beans:bean>
...where 'otherBeanRef' is another bean that has a reference to the expected class.
More points regarding File Descriptor
:
File Descriptors
(FD) are non-negative integers (0, 1, 2, ...)
that are associated with files that are opened.
0, 1, 2
are standard FD's that corresponds to STDIN_FILENO
, STDOUT_FILENO
and STDERR_FILENO
(defined in unistd.h
) opened by default on behalf of shell when the program starts.
FD's are allocated in the sequential order, meaning the lowest possible unallocated integer value.
FD's for a particular process can be seen in /proc/$pid/fd
(on Unix based systems).
During some work with an auto-focus lens, I came across this very useful set of algorithms for detecting image focus. It's implemented in MATLAB, but most of the functions are quite easy to port to OpenCV with filter2D.
It's basically a survey implementation of many focus measurement algorithms. If you want to read the original papers, references to the authors of the algorithms are provided in the code. The 2012 paper by Pertuz, et al. Analysis of focus measure operators for shape from focus (SFF) gives a great review of all of these measure as well as their performance (both in terms of speed and accuracy as applied to SFF).
EDIT: Added MATLAB code just in case the link dies.
function FM = fmeasure(Image, Measure, ROI)
%This function measures the relative degree of focus of
%an image. It may be invoked as:
%
% FM = fmeasure(Image, Method, ROI)
%
%Where
% Image, is a grayscale image and FM is the computed
% focus value.
% Method, is the focus measure algorithm as a string.
% see 'operators.txt' for a list of focus
% measure methods.
% ROI, Image ROI as a rectangle [xo yo width heigth].
% if an empty argument is passed, the whole
% image is processed.
%
% Said Pertuz
% Abr/2010
if ~isempty(ROI)
Image = imcrop(Image, ROI);
end
WSize = 15; % Size of local window (only some operators)
switch upper(Measure)
case 'ACMO' % Absolute Central Moment (Shirvaikar2004)
if ~isinteger(Image), Image = im2uint8(Image);
end
FM = AcMomentum(Image);
case 'BREN' % Brenner's (Santos97)
[M N] = size(Image);
DH = Image;
DV = Image;
DH(1:M-2,:) = diff(Image,2,1);
DV(:,1:N-2) = diff(Image,2,2);
FM = max(DH, DV);
FM = FM.^2;
FM = mean2(FM);
case 'CONT' % Image contrast (Nanda2001)
ImContrast = inline('sum(abs(x(:)-x(5)))');
FM = nlfilter(Image, [3 3], ImContrast);
FM = mean2(FM);
case 'CURV' % Image Curvature (Helmli2001)
if ~isinteger(Image), Image = im2uint8(Image);
end
M1 = [-1 0 1;-1 0 1;-1 0 1];
M2 = [1 0 1;1 0 1;1 0 1];
P0 = imfilter(Image, M1, 'replicate', 'conv')/6;
P1 = imfilter(Image, M1', 'replicate', 'conv')/6;
P2 = 3*imfilter(Image, M2, 'replicate', 'conv')/10 ...
-imfilter(Image, M2', 'replicate', 'conv')/5;
P3 = -imfilter(Image, M2, 'replicate', 'conv')/5 ...
+3*imfilter(Image, M2, 'replicate', 'conv')/10;
FM = abs(P0) + abs(P1) + abs(P2) + abs(P3);
FM = mean2(FM);
case 'DCTE' % DCT energy ratio (Shen2006)
FM = nlfilter(Image, [8 8], @DctRatio);
FM = mean2(FM);
case 'DCTR' % DCT reduced energy ratio (Lee2009)
FM = nlfilter(Image, [8 8], @ReRatio);
FM = mean2(FM);
case 'GDER' % Gaussian derivative (Geusebroek2000)
N = floor(WSize/2);
sig = N/2.5;
[x,y] = meshgrid(-N:N, -N:N);
G = exp(-(x.^2+y.^2)/(2*sig^2))/(2*pi*sig);
Gx = -x.*G/(sig^2);Gx = Gx/sum(Gx(:));
Gy = -y.*G/(sig^2);Gy = Gy/sum(Gy(:));
Rx = imfilter(double(Image), Gx, 'conv', 'replicate');
Ry = imfilter(double(Image), Gy, 'conv', 'replicate');
FM = Rx.^2+Ry.^2;
FM = mean2(FM);
case 'GLVA' % Graylevel variance (Krotkov86)
FM = std2(Image);
case 'GLLV' %Graylevel local variance (Pech2000)
LVar = stdfilt(Image, ones(WSize,WSize)).^2;
FM = std2(LVar)^2;
case 'GLVN' % Normalized GLV (Santos97)
FM = std2(Image)^2/mean2(Image);
case 'GRAE' % Energy of gradient (Subbarao92a)
Ix = Image;
Iy = Image;
Iy(1:end-1,:) = diff(Image, 1, 1);
Ix(:,1:end-1) = diff(Image, 1, 2);
FM = Ix.^2 + Iy.^2;
FM = mean2(FM);
case 'GRAT' % Thresholded gradient (Snatos97)
Th = 0; %Threshold
Ix = Image;
Iy = Image;
Iy(1:end-1,:) = diff(Image, 1, 1);
Ix(:,1:end-1) = diff(Image, 1, 2);
FM = max(abs(Ix), abs(Iy));
FM(FM<Th)=0;
FM = sum(FM(:))/sum(sum(FM~=0));
case 'GRAS' % Squared gradient (Eskicioglu95)
Ix = diff(Image, 1, 2);
FM = Ix.^2;
FM = mean2(FM);
case 'HELM' %Helmli's mean method (Helmli2001)
MEANF = fspecial('average',[WSize WSize]);
U = imfilter(Image, MEANF, 'replicate');
R1 = U./Image;
R1(Image==0)=1;
index = (U>Image);
FM = 1./R1;
FM(index) = R1(index);
FM = mean2(FM);
case 'HISE' % Histogram entropy (Krotkov86)
FM = entropy(Image);
case 'HISR' % Histogram range (Firestone91)
FM = max(Image(:))-min(Image(:));
case 'LAPE' % Energy of laplacian (Subbarao92a)
LAP = fspecial('laplacian');
FM = imfilter(Image, LAP, 'replicate', 'conv');
FM = mean2(FM.^2);
case 'LAPM' % Modified Laplacian (Nayar89)
M = [-1 2 -1];
Lx = imfilter(Image, M, 'replicate', 'conv');
Ly = imfilter(Image, M', 'replicate', 'conv');
FM = abs(Lx) + abs(Ly);
FM = mean2(FM);
case 'LAPV' % Variance of laplacian (Pech2000)
LAP = fspecial('laplacian');
ILAP = imfilter(Image, LAP, 'replicate', 'conv');
FM = std2(ILAP)^2;
case 'LAPD' % Diagonal laplacian (Thelen2009)
M1 = [-1 2 -1];
M2 = [0 0 -1;0 2 0;-1 0 0]/sqrt(2);
M3 = [-1 0 0;0 2 0;0 0 -1]/sqrt(2);
F1 = imfilter(Image, M1, 'replicate', 'conv');
F2 = imfilter(Image, M2, 'replicate', 'conv');
F3 = imfilter(Image, M3, 'replicate', 'conv');
F4 = imfilter(Image, M1', 'replicate', 'conv');
FM = abs(F1) + abs(F2) + abs(F3) + abs(F4);
FM = mean2(FM);
case 'SFIL' %Steerable filters (Minhas2009)
% Angles = [0 45 90 135 180 225 270 315];
N = floor(WSize/2);
sig = N/2.5;
[x,y] = meshgrid(-N:N, -N:N);
G = exp(-(x.^2+y.^2)/(2*sig^2))/(2*pi*sig);
Gx = -x.*G/(sig^2);Gx = Gx/sum(Gx(:));
Gy = -y.*G/(sig^2);Gy = Gy/sum(Gy(:));
R(:,:,1) = imfilter(double(Image), Gx, 'conv', 'replicate');
R(:,:,2) = imfilter(double(Image), Gy, 'conv', 'replicate');
R(:,:,3) = cosd(45)*R(:,:,1)+sind(45)*R(:,:,2);
R(:,:,4) = cosd(135)*R(:,:,1)+sind(135)*R(:,:,2);
R(:,:,5) = cosd(180)*R(:,:,1)+sind(180)*R(:,:,2);
R(:,:,6) = cosd(225)*R(:,:,1)+sind(225)*R(:,:,2);
R(:,:,7) = cosd(270)*R(:,:,1)+sind(270)*R(:,:,2);
R(:,:,7) = cosd(315)*R(:,:,1)+sind(315)*R(:,:,2);
FM = max(R,[],3);
FM = mean2(FM);
case 'SFRQ' % Spatial frequency (Eskicioglu95)
Ix = Image;
Iy = Image;
Ix(:,1:end-1) = diff(Image, 1, 2);
Iy(1:end-1,:) = diff(Image, 1, 1);
FM = mean2(sqrt(double(Iy.^2+Ix.^2)));
case 'TENG'% Tenengrad (Krotkov86)
Sx = fspecial('sobel');
Gx = imfilter(double(Image), Sx, 'replicate', 'conv');
Gy = imfilter(double(Image), Sx', 'replicate', 'conv');
FM = Gx.^2 + Gy.^2;
FM = mean2(FM);
case 'TENV' % Tenengrad variance (Pech2000)
Sx = fspecial('sobel');
Gx = imfilter(double(Image), Sx, 'replicate', 'conv');
Gy = imfilter(double(Image), Sx', 'replicate', 'conv');
G = Gx.^2 + Gy.^2;
FM = std2(G)^2;
case 'VOLA' % Vollath's correlation (Santos97)
Image = double(Image);
I1 = Image; I1(1:end-1,:) = Image(2:end,:);
I2 = Image; I2(1:end-2,:) = Image(3:end,:);
Image = Image.*(I1-I2);
FM = mean2(Image);
case 'WAVS' %Sum of Wavelet coeffs (Yang2003)
[C,S] = wavedec2(Image, 1, 'db6');
H = wrcoef2('h', C, S, 'db6', 1);
V = wrcoef2('v', C, S, 'db6', 1);
D = wrcoef2('d', C, S, 'db6', 1);
FM = abs(H) + abs(V) + abs(D);
FM = mean2(FM);
case 'WAVV' %Variance of Wav...(Yang2003)
[C,S] = wavedec2(Image, 1, 'db6');
H = abs(wrcoef2('h', C, S, 'db6', 1));
V = abs(wrcoef2('v', C, S, 'db6', 1));
D = abs(wrcoef2('d', C, S, 'db6', 1));
FM = std2(H)^2+std2(V)+std2(D);
case 'WAVR'
[C,S] = wavedec2(Image, 3, 'db6');
H = abs(wrcoef2('h', C, S, 'db6', 1));
V = abs(wrcoef2('v', C, S, 'db6', 1));
D = abs(wrcoef2('d', C, S, 'db6', 1));
A1 = abs(wrcoef2('a', C, S, 'db6', 1));
A2 = abs(wrcoef2('a', C, S, 'db6', 2));
A3 = abs(wrcoef2('a', C, S, 'db6', 3));
A = A1 + A2 + A3;
WH = H.^2 + V.^2 + D.^2;
WH = mean2(WH);
WL = mean2(A);
FM = WH/WL;
otherwise
error('Unknown measure %s',upper(Measure))
end
end
%************************************************************************
function fm = AcMomentum(Image)
[M N] = size(Image);
Hist = imhist(Image)/(M*N);
Hist = abs((0:255)-255*mean2(Image))'.*Hist;
fm = sum(Hist);
end
%******************************************************************
function fm = DctRatio(M)
MT = dct2(M).^2;
fm = (sum(MT(:))-MT(1,1))/MT(1,1);
end
%************************************************************************
function fm = ReRatio(M)
M = dct2(M);
fm = (M(1,2)^2+M(1,3)^2+M(2,1)^2+M(2,2)^2+M(3,1)^2)/(M(1,1)^2);
end
%******************************************************************
A few examples of OpenCV versions:
// OpenCV port of 'LAPM' algorithm (Nayar89)
double modifiedLaplacian(const cv::Mat& src)
{
cv::Mat M = (Mat_<double>(3, 1) << -1, 2, -1);
cv::Mat G = cv::getGaussianKernel(3, -1, CV_64F);
cv::Mat Lx;
cv::sepFilter2D(src, Lx, CV_64F, M, G);
cv::Mat Ly;
cv::sepFilter2D(src, Ly, CV_64F, G, M);
cv::Mat FM = cv::abs(Lx) + cv::abs(Ly);
double focusMeasure = cv::mean(FM).val[0];
return focusMeasure;
}
// OpenCV port of 'LAPV' algorithm (Pech2000)
double varianceOfLaplacian(const cv::Mat& src)
{
cv::Mat lap;
cv::Laplacian(src, lap, CV_64F);
cv::Scalar mu, sigma;
cv::meanStdDev(lap, mu, sigma);
double focusMeasure = sigma.val[0]*sigma.val[0];
return focusMeasure;
}
// OpenCV port of 'TENG' algorithm (Krotkov86)
double tenengrad(const cv::Mat& src, int ksize)
{
cv::Mat Gx, Gy;
cv::Sobel(src, Gx, CV_64F, 1, 0, ksize);
cv::Sobel(src, Gy, CV_64F, 0, 1, ksize);
cv::Mat FM = Gx.mul(Gx) + Gy.mul(Gy);
double focusMeasure = cv::mean(FM).val[0];
return focusMeasure;
}
// OpenCV port of 'GLVN' algorithm (Santos97)
double normalizedGraylevelVariance(const cv::Mat& src)
{
cv::Scalar mu, sigma;
cv::meanStdDev(src, mu, sigma);
double focusMeasure = (sigma.val[0]*sigma.val[0]) / mu.val[0];
return focusMeasure;
}
No guarantees on whether or not these measures are the best choice for your problem, but if you track down the papers associated with these measures, they may give you more insight. Hope you find the code useful! I know I did.
None of the previously submitted answers really worked the way I wanted to solve this issue. To me the ideal solution would provide the “Select One” (or whatever initial text) when the spinner is first displayed. When the user taps the spinner, the initial text shouldn’t be a part of the drop down that is displayed.
To further complicate my particular situation, my spinner data is coming form a cursor that is loaded via the LoaderManager callbacks.
After considerable experimentation I came up with the following solution:
public class MyFragment extends Fragment implements
LoaderManager.LoaderCallbacks<Cursor>{
private static final String SPINNER_INIT_VALUE = "Select A Widget";
private Spinner mSpinner;
private int mSpinnerPosition;
private boolean mSpinnerDropDownShowing = false;
private View mSpinnerDropDown;
private MyCursorAdapter mCursorAdapter;
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
...
mCursorAdapter = new MyCursorAdapter(getActivity());
mSpinner = (Spinner) rootView.findViewById(R.id.theSpinner);
mSpinner.setOnTouchListener(mSpinnerTouchListener);
mSpinner.setAdapter(mCursorAdapter);
...
}
//Capture the touch events to toggle the spinner's dropdown visibility
private OnTouchListener mSpinnerTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if(mSpinnerDropDown != null && mSpinnerDropDownShowing == false){
mSpinnerDropDownShowing = true;
mSpinnerDropDown.setVisibility(View.VISIBLE);
}
return false;
}
};
//Capture the click event on the spinner drop down items
protected OnClickListener spinnerItemClick = new OnClickListener(){
@Override
public void onClick(View view) {
String widget = ((TextView) view.findViewById(android.R.id.text1)).getText().toString();
if(!widget.equals(SPINNER_INIT_VALUE)){
if(mCursorAdapter != null){
Cursor cursor = mCursorAdapter.getCursor();
if(cursor.moveToFirst()){
while(!cursor.isAfterLast()){
if(widget.equals(cursor.getString(WidgetQuery.WIDGET_NAME))){
...
//Set the spinner to the correct item
mSpinnerPosition = cursor.getPosition() + 1;
mSpinner.setSelection(mSpinnerPosition);
break;
}
cursor.moveToNext();
}
}
}
}
//Hide the drop down. Not the most elegent solution but it is the only way I could hide/dismiss the drop down
mSpinnerDropDown = view.getRootView();
mSpinnerDropDownShowing = false;
mSpinnerDropDown.setVisibility(View.GONE);
}
};
private class MyCursorAdapter extends CursorAdapter {
private final int DISPLACEMENT = 1;
private final int DEFAULT_ITEM_ID = Integer.MAX_VALUE;
private Activity mActivity;
public MyCursorAdapter(Activity activity) {
super(activity, null, false);
mActivity = activity;
}
//When loading the regular views, inject the defualt item
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(position == 0){
if(convertView == null){
convertView = mActivity.getLayoutInflater().inflate(R.layout.list_item_widget, parent, false);
}
return getDefaultItem(convertView);
}
return super.getView(position - DISPLACEMENT, convertView, parent);
}
//When loading the drop down views, set the onClickListener for each view
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent){
View view = super.getDropDownView(position, convertView, parent);
view.setOnClickListener(spinnerItemClick);
return view;
}
//The special default item that is being injected
private View getDefaultItem(View convertView){
TextView text = (TextView) convertView.findViewById(android.R.id.text1);
text.setText(SPINNER_INIT_VALUE);
return convertView;
}
@Override
public long getItemId(int position) {
if (position == 0) {
return DEFAULT_ITEM_ID;
}
return super.getItemId(position - DISPLACEMENT);
}
@Override
public boolean isEnabled(int position) {
return position == 0 ? true : super.isEnabled(position - DISPLACEMENT);
}
@Override
public int getViewTypeCount() {
return super.getViewTypeCount() + DISPLACEMENT;
}
@Override
public int getItemViewType(int position) {
if (position == 0) {
return super.getViewTypeCount();
}
return super.getItemViewType(position - DISPLACEMENT);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return mActivity.getLayoutInflater().inflate(R.layout.list_item_widget, parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor){
if(cursor.isAfterLast()){
return;
}
TextView text = (TextView) view.findViewById(android.R.id.text1);
String WidgetName = cursor.getString(WidgetQuery.WIDGET_NAME);
text.setText(WidgetName);
}
}
}
Either return straight out of the loop:
foreach(string s in sList){
if(s.equals("ok")){
return true;
}
}
// if you haven't returned by now, no items are "ok"
return false;
Or use break
:
bool isOk = false;
foreach(string s in sList){
if(s.equals("ok")){
isOk = true;
break; // jump out of the loop
}
}
if(isOk)
{
// do something
}
However, in your case it might be better to do something like this:
if(sList.Contains("ok"))
{
// at least one element is "ok"
}
else
{
// no elements are "ok"
}
I guess best way to do this is ...
int main()
{
char str[100];
scanf("[^EOF]",str);
printf("%s",str);
return 0;
}
function myResizeFunction() {
...
}
$(function() {
$(window).resize(myResizeFunction).trigger('resize');
});
This will cause your resize handler to trigger on window resize and on document ready. Of course, you can attach your resize handler outside of the document ready handler if you want .trigger('resize')
to run on page load instead.
UPDATE: Here's another option if you don't want to make use of any other third-party libraries.
This technique adds a specific class to your target element so you have the advantage of controlling the styling through CSS only (and avoiding inline styling).
It also ensures that the class is only added or removed when the actual threshold point is triggered and not on each and every resize. It will fire at one threshold point only: when the height changes from <= 818 to > 819 or vice versa and not multiple times within each region. It's not concerned with any change in width.
function myResizeFunction() {
var $window = $(this),
height = Math.ceil($window.height()),
previousHeight = $window.data('previousHeight');
if (height !== previousHeight) {
if (height < 819)
previousHeight >= 819 && $('.footer').removeClass('hgte819');
else if (!previousHeight || previousHeight < 819)
$('.footer').addClass('hgte819');
$window.data('previousHeight', height);
}
}
$(function() {
$(window).on('resize.optionalNamespace', myResizeFunction).triggerHandler('resize.optionalNamespace');
});
As an example, you might have the following as some of your CSS rules:
.footer {
bottom: auto;
left: auto;
position: static;
}
.footer.hgte819 {
bottom: 3px;
left: 0;
position: absolute;
}
The first line of a constructor is always an invocation to another constructor. You can choose between calling a constructor from the same class with "this(...)" or a constructor from the parent clas with "super(...)". If you don't include either, the compiler includes this line for you: super();
In addition to already posted examples, here is another approach using express-async-wrap and asynchronous functions (ES2017).
Router
router.put('/:id/settings/profile', wrap(async function (request, response, next) {
const username = request.body.username
const email = request.body.email
const userWithEmail = await userService.findUserByEmail(email)
if (userWithEmail) {
return response.status(409).send({message: 'Email is already taken.'})
}
const userWithUsername = await userService.findUserByUsername(username)
if (userWithUsername) {
return response.status(409).send({message: 'Username is already taken.'})
}
const user = await userService.updateProfileSettings(userId, username, email)
return response.status(200).json({user: user})
}))
UserService
async function updateProfileSettings (userId, username, email) {
try {
return User.findOneAndUpdate({'_id': userId}, {
$set: {
'username': username,
'auth.email': email
}
}, {new: true})
} catch (error) {
throw new Error(`Unable to update user with id "${userId}".`)
}
}
async function findUserByEmail (email) {
try {
return User.findOne({'auth.email': email.toLowerCase()})
} catch (error) {
throw new Error(`Unable to connect to the database.`)
}
}
async function findUserByUsername (username) {
try {
return User.findOne({'username': username})
} catch (error) {
throw new Error(`Unable to connect to the database.`)
}
}
// other methods
export default {
updateProfileSettings,
findUserByEmail,
findUserByUsername,
}
Resources
driver.findElement(By.id("invoice_supplier_id")).setAttribute("value", "your value");
You can use javascript's indexOf function.
var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";
if(str1.indexOf(str2) != -1){
alert(str2 + " found");
}
Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML.
Adding a value of selected
to the item we want to appear as a header forces it to show in the first place as a placeholder.
Something like:
<option selected disabled>Choose here</option>
The complete markup should be along these lines:
<select>
<option selected disabled>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
You can take a look at this fiddle, and here's the result:
If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden
attribute like so:
<select>
<option selected disabled hidden>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
Check the fiddle here and the screenshot below.
Here is the solution:
<select>
<option style="display:none;" selected>Select language</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
Since some of the answers give here relate to setting up SMTP in general (and not just for @shinod particular issue where it had been working and stopped), I thought it would be helpful if I updated the answer because this is a lot simpler to do now than it used to be :-)
In PHP 4 the PEAR Mail package is typically already installed, and this really simple tutorial shows you the few lines of code that you need to add to your php file http://email.about.com/od/emailprogrammingtips/qt/PHP_Email_SMTP_Authentication.htm
Most hosting companies list the SMTP settings that you'll need. I use JustHost, and they list theirs at https://my.justhost.com/cgi/help/26 (under Outgoing Mail Server)
You could also sidestep nested cursor issues, general cursor issues, and global variable issues by avoiding the cursors entirely.
declare @rowid int
declare @rowid2 int
declare @id int
declare @type varchar(10)
declare @rows int
declare @rows2 int
declare @outer table (rowid int identity(1,1), id int, type varchar(100))
declare @inner table (rowid int identity(1,1), clientid int, whatever int)
insert into @outer (id, type)
Select id, type from sometable
select @rows = count(1) from @outer
while (@rows > 0)
Begin
select top 1 @rowid = rowid, @id = id, @type = type
from @outer
insert into @innner (clientid, whatever )
select clientid whatever from contacts where contactid = @id
select @rows2 = count(1) from @inner
while (@rows2 > 0)
Begin
select top 1 /* stuff you want into some variables */
/* Other statements you want to execute */
delete from @inner where rowid = @rowid2
select @rows2 = count(1) from @inner
End
delete from @outer where rowid = @rowid
select @rows = count(1) from @outer
End
You can use img[alt] {styles}
to style only the alternative text.
Moment js solution to this is
var d = new Date(new Date().setHours(0,0,0,0));
m.add(m.utcOffset(), 'm')
m.toDate().toISOString()
// output "2019-07-18T00:00:00.000Z"
A solution for me:
$old_ErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = 'SilentlyContinue'
if((Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue) -eq $null) {
WriteTraceForTrans "The session configuration MyShellUri is already unregistered."
}
else {
#Unregister-PSSessionConfiguration -Name "MyShellUri" -Force -ErrorAction Ignore
}
$ErrorActionPreference = $old_ErrorActionPreference
Or use try-catch
try {
(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue)
}
catch {
}
$.validator.addMethod("mymail", function(value, element) {
return this.optional( element ) || /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test( value );
}, "Enter valid email!");
This may help! a small modification to the answer by user4974898!
if you want to emebed the canvas you can use this snippet
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas id=canvas width=200 height=200></canvas>
<iframe id='img' width=200 height=200></iframe>
<script>
window.onload = function() {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.fillStyle = "green";
context.fillRect(50, 50, 100, 100);
document.getElementById('img').src = canvas.toDataURL("image/jpeg");
console.log(canvas.toDataURL("image/jpeg"));
}
</script>
</body>
</html>
I'm not sure I understand your question. But there are two approaches to making the image invisible...
Pure HTML
<img src="a.gif" style="display: none;" />
Or...
HTML + Javascript
<script type="text/javascript">
document.getElementById("myImage").style.display = "none";
</script>
<img id="myImage" src="a.gif" />
Lots of suggestions using Regex. How about this extension method without it:
public static string Replace(this string str, string old, string @new, StringComparison comparison)
{
@new = @new ?? "";
if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(old) || old.Equals(@new, comparison))
return str;
int foundAt = 0;
while ((foundAt = str.IndexOf(old, foundAt, comparison)) != -1)
{
str = str.Remove(foundAt, old.Length).Insert(foundAt, @new);
foundAt += @new.Length;
}
return str;
}
When you click on the image you'll get the alert:
<img src="logo1.jpg" onClick='alert("Hello World!")'/>
if this is what you want.
This sometimes happens when a string is converted from Windows-1252 to UTF-8 twice.
We had this in a Zend/PHP/MySQL application where characters like that were appearing in the database, probably due to the MySQL connection not specifying the correct character set. We had to:
Ensure Zend and PHP were communicating with the database in UTF-8 (was not by default)
Repair the broken characters with several SQL queries like this...
UPDATE MyTable SET
MyField1 = CONVERT(CAST(CONVERT(MyField1 USING latin1) AS BINARY) USING utf8),
MyField2 = CONVERT(CAST(CONVERT(MyField2 USING latin1) AS BINARY) USING utf8);
Do this for as many tables/columns as necessary.
You can also fix some of these strings in PHP if necessary. Note that because characters have been encoded twice, we actually need to do a reverse conversion from UTF-8 back to Windows-1252, which confused me at first.
mb_convert_encoding('’', 'Windows-1252', 'UTF-8'); // returns ’
find
them and grep
for the string:
This will find all files of your 3 types in /starting/path and grep for the regular expression '(document\.cookie|setcookie)'
. Split over 2 lines with the backslash just for readability...
find /starting/path -type f -name "*.php" -o -name "*.html" -o -name "*.js" | \
xargs egrep -i '(document\.cookie|setcookie)'
If you have JQuery loaded already, you can just do this:
$('body').css('background-image', 'url(../images/backgrounds/header-top.jpg)');
EDIT:
First load JQuery in the head tag:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
Then call the Javascript to change the background image when something happens on the page, like when it finishes loading:
<script type="text/javascript">
$(document).ready(function() {
$('body').css('background-image', 'url(../images/backgrounds/header-top.jpg)');
});
</script>
Here is a sample code:
<?php
$sql="select * from Posts limit 20";
$response = array();
$posts = array();
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)) {
$title=$row['title'];
$url=$row['url'];
$posts[] = array('title'=> $title, 'url'=> $url);
}
$response['posts'] = $posts;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
?>
These two terms differentiate between two different ways of walking a tree.
It is probably easiest just to exhibit the difference. Consider the tree:
A
/ \
B C
/ / \
D E F
A depth first traversal would visit the nodes in this order
A, B, D, C, E, F
Notice that you go all the way down one leg before moving on.
A breadth first traversal would visit the node in this order
A, B, C, D, E, F
Here we work all the way across each level before going down.
(Note that there is some ambiguity in the traversal orders, and I've cheated to maintain the "reading" order at each level of the tree. In either case I could get to B before or after C, and likewise I could get to E before or after F. This may or may not matter, depends on you application...)
Both kinds of traversal can be achieved with the pseudocode:
Store the root node in Container
While (there are nodes in Container)
N = Get the "next" node from Container
Store all the children of N in Container
Do some work on N
The difference between the two traversal orders lies in the choice of Container
.
The recursive implementation looks like
ProcessNode(Node)
Work on the payload Node
Foreach child of Node
ProcessNode(child)
/* Alternate time to work on the payload Node (see below) */
The recursion ends when you reach a node that has no children, so it is guaranteed to end for finite, acyclic graphs.
At this point, I've still cheated a little. With a little cleverness you can also work-on the nodes in this order:
D, B, E, F, C, A
which is a variation of depth-first, where I don't do the work at each node until I'm walking back up the tree. I have however visited the higher nodes on the way down to find their children.
This traversal is fairly natural in the recursive implementation (use the "Alternate time" line above instead of the first "Work" line), and not too hard if you use a explicit stack, but I'll leave it as an exercise.
The MessageBox in the Extended WPF Toolkit is very nice. It's at Microsoft.Windows.Controls.MessageBox after referencing the toolkit DLL. Of course this was released Aug 9 2011 so it would not have been an option for you originally. It can be found at Github for everyone out there looking around.
Have you tried using :
git dif | grep -B <number of before lines to show> <regex>
In my case, i try to search where do i put a debug statement in the many files, i need to see which file already got this debug statement like this :
git diff | grep -B 5 dd\(
const str = (new Date()).toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");
It uses the built-in function Date.toISOString()
, chops off the ms, replaces the hyphens with slashes, and replaces the T with a space to go from say '2019-01-05T09:01:07.123'
to '2019/01/05 09:01:07'
.
const now = new Date();
const offsetMs = now.getTimezoneOffset() * 60 * 1000;
const dateLocal = new Date(now.getTime() - offsetMs);
const str = dateLocal.toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");
much simpler:
$("selector for element").get(0).scrollIntoView();
if more than one item returns in the selector, the get(0) will get only the first item.
Your constructor is expecting one parameter (data). You're not passing it in the call. I guess you wanted to initialise a field in the object. That would look like this:
class DHT:
def __init__(self):
self.data = {}
self.data['one'] = '1'
self.data['two'] = '2'
self.data['three'] = '3'
def showData(self):
print(self.data)
if __name__ == '__main__':
DHT().showData()
Or even just:
class DHT:
def __init__(self):
self.data = {'one': '1', 'two': '2', 'three': '3'}
def showData(self):
print(self.data)
In order to use word-wrap: break-word
, you need to set a width (in px). For example:
div {
width: 250px;
word-wrap: break-word;
}
word-wrap is a CSS3 property, but it should work in all browsers, including IE 5.5-9.
Java 8 is in the market after almost 2 decades, following is the way to iterate org.json.JSONArray
with java8 Stream API.
import org.json.JSONArray;
import org.json.JSONObject;
@Test
public void access_org_JsonArray() {
//Given: array
JSONArray jsonArray = new JSONArray(Arrays.asList(new JSONObject(
new HashMap() {{
put("a", 100);
put("b", 200);
}}
),
new JSONObject(
new HashMap() {{
put("a", 300);
put("b", 400);
}}
)));
//Then: convert to List<JSONObject>
List<JSONObject> jsonItems = IntStream.range(0, jsonArray.length())
.mapToObj(index -> (JSONObject) jsonArray.get(index))
.collect(Collectors.toList());
// you can access the array elements now
jsonItems.forEach(arrayElement -> System.out.println(arrayElement.get("a")));
// prints 100, 300
}
If the iteration is only one time, (no need to .collect
)
IntStream.range(0, jsonArray.length())
.mapToObj(index -> (JSONObject) jsonArray.get(index))
.forEach(item -> {
System.out.println(item);
});
Actually NULL filter is not being ignored. Thing is this is how joining two tables work.
I will try to walk down with the steps performed by database server to make it understand.
For example when you execute the query which you said is ignoring the NULL condition.
SELECT
*
FROM
shipments s
LEFT OUTER JOIN returns r
ON s.id = r.id
AND r.id is null
WHERE
s.day >= CURDATE() - INTERVAL 10 DAY
1st thing happened is all the rows from table SHIPMENTS get selected
on next step database server will start selecting one by one record from 2nd(RETURNS) table.
on third step the record from RETURNS table will be qualified against the join conditions you have provided in the query which in this case is (s.id = r.id and r.id is NULL)
note that this qualification applied on third step only decides if server should accept or reject the current record of RETURNS table to append with the selected row of SHIPMENT table. It can in no way effect the selection of record from SHIPMENT table.
And once server is done with joining two tables which contains all the rows of SHIPMENT table and selected rows of RETURNS table it applies the where clause on the intermediate result. so when you put (r.id is NULL) condition in where clause than all the records from the intermediate result with r.id = null gets filtered out.
I've found this to work the best across all browsers and devices (PC, tables & mobile).
<script type="text/javascript">
function iframeLoaded() {
var iFrameID = document.getElementById('idIframe');
if(iFrameID) {
// here you can make the height, I delete it first, then I make it again
iFrameID.height = "";
iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight + "px";
}
}
</script>
<iframe id="idIframe" onload="iframeLoaded()" frameborder="0" src="yourpage.php" height="100%" width="100%" scrolling="no"></iframe>
You could use an <a>
tag with different styles:
a:link { }
a:visited { }
a:hover { }
a:active { }
I'd recommend using that in conjunction with CSS sprites: https://css-tricks.com/css-sprites/
If I imagined that you set android:configChanges
in manifest.xml and create several directory for several language such as: values-fr OR values-nl
, I could suggest this code(In Activity class):
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// change language by onclick a button
Configuration newConfig = new Configuration();
newConfig.locale = Locale.FRENCH;
onConfigurationChanged(newConfig);
}
});
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics());
setContentView(R.layout.main);
setTitle(R.string.app_name);
// Checks the active language
if (newConfig.locale == Locale.ENGLISH) {
Toast.makeText(this, "English", Toast.LENGTH_SHORT).show();
} else if (newConfig.locale == Locale.FRENCH){
Toast.makeText(this, "French", Toast.LENGTH_SHORT).show();
}
}
I tested this code, It is correct.
Try this:
import matplotlib as plt
after importing the file we can use matplotlib library but remember to use it as plt
df.plt(kind='line',figsize=(10,5))
after that the plot will be done and size increased. In figsize the 10 is for breadth and 5 is for height. Also other attributes can be added to the plot too.
Please set your form action attribute as below it will solve your problem.
<form name="addProductForm" id="addProductForm" action="javascript:;" enctype="multipart/form-data" method="post" accept-charset="utf-8">
jQuery code:
$(document).ready(function () {
$("#addProductForm").submit(function (event) {
//disable the default form submission
event.preventDefault();
//grab all form data
var formData = $(this).serialize();
$.ajax({
url: 'addProduct.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function () {
alert('Form Submitted!');
},
error: function(){
alert("error in ajax form submission");
}
});
return false;
});
});
I have wrapped it in my date time helper class here
https://github.com/normandqq/Date-Time-Helper
using
$dateLastDay = Model_DTHpr::getLastDayOfTheMonth();
And it is done
A good example of using the Generic Repository pattern and implementing a generic solution for this might look something like this.
public IList<TEntity> Get<TParamater>(IList<Expression<Func<TEntity, TParamater>>> includeProperties)
{
foreach (var include in includeProperties)
{
query = query.Include(include);
}
return query.ToList();
}
Go to Tools >> Preferences >> IPython console >> Graphics >> Backend:Inline, change "Inline" to "Automatic", click "OK"
Reset the kernel at the console, and the plot will appear in a separate window
You can use functools.partial
for this (as you suspected):
from functools import partial
def target(lock, iterable_item):
for item in iterable_item:
# Do cool stuff
if (... some condition here ...):
lock.acquire()
# Write to stdout or logfile, etc.
lock.release()
def main():
iterable = [1, 2, 3, 4, 5]
pool = multiprocessing.Pool()
l = multiprocessing.Lock()
func = partial(target, l)
pool.map(func, iterable)
pool.close()
pool.join()
Example:
def f(a, b, c):
print("{} {} {}".format(a, b, c))
def main():
iterable = [1, 2, 3, 4, 5]
pool = multiprocessing.Pool()
a = "hi"
b = "there"
func = partial(f, a, b)
pool.map(func, iterable)
pool.close()
pool.join()
if __name__ == "__main__":
main()
Output:
hi there 1
hi there 2
hi there 3
hi there 4
hi there 5
For unit test:
spyOn(component.form, 'valid').and.returnValue(true);
Add above code in API gateway under GET-Integration Request> mapping section.
You need to Open the SQL Developer first and then click on File option and browse to the location where your .sql is placed. Once you are at the location where file is placed double click on it, this will get the file open in SQL Developer. Now select all of the content of file (CTRL + A) and press F9 key. Just make sure there is a commit statement at the end of the .sql script so that the changes are persisted in the database
This may be the easiest method
If we need only one column to be numeric
yyz$b <- as.numeric(as.character(yyz$b))
But, if all the columns needs to changed to numeric
, use lapply
to loop over the columns and convert to numeric
by first converting it to character
class as the columns were factor
.
yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))
Both the columns in the OP's post are factor
because of the string "n/a"
. This could be easily avoided while reading the file using na.strings = "n/a"
in the read.table/read.csv
or if we are using data.frame
, we can have character
columns with stringsAsFactors=FALSE
(the default is stringsAsFactors=TRUE
)
Regarding the usage of apply
, it converts the dataset to matrix
and matrix
can hold only a single class. To check the class
, we need
lapply(yyz, class)
Or
sapply(yyz, class)
Or check
str(yyz)
For anyone else reading this looking to disable this via GPO for all users, this is the setting:
Computer Configuration/Administrative Templates/Windows Components/Internet Explorer/Compatibility View/Turn on Internet Explorer Standards Mode for Local Intranet
although the web.config edit fixed it for me.
You can use the std::istream::getline() (or preferably the version that works on std::string) function to get an entire line. Both have versions that allow you to specify the delimiter (end of line character). The default for the string version is '\n'.
A pointer can receive a NULL parameter, a reference parameter can not. If there's ever a chance that you could want to pass "no object", then use a pointer instead of a reference.
Also, passing by pointer allows you to explicitly see at the call site whether the object is passed by value or by reference:
// Is mySprite passed by value or by reference? You can't tell
// without looking at the definition of func()
func(mySprite);
// func2 passes "by pointer" - no need to look up function definition
func2(&mySprite);
other than using this.form.submit()
you also submiting by id or name.
example i have form like this : <form action="" name="PostName" id="IdName">
By Name : <select onchange="PostName.submit()">
By Id : <select onchange="IdName.submit()">
So as I understand it, you need to pull out successive pairs of hex digits, then decode that 2-digit hex number and take the corresponding char:
String s = "...";
StringBuilder sb = new StringBuilder(s.length() / 2);
for (int i = 0; i < s.length(); i+=2) {
String hex = "" + s.charAt(i) + s.charAt(i+1);
int ival = Integer.parseInt(hex, 16);
sb.append((char) ival);
}
String string = sb.toString();
We have two ways to change default port number in Angular.
First way is by CLI command:
ng serve --port 2400 --open
Second way is by configuration at the location:
ProjectName\node_modules\@angular-devkit\build-angular\src\dev-server\schema.json.
Make changes in schema.json file.
{
"title": "Dev Server Target",
"description": "Dev Server target options for Build Facade.",
"type": "object",
"properties": {
"browserTarget": {
"type": "string",
"description": "Target to serve."
},
"port": {
"type": "number",
"description": "Port to listen on.",
"default": 2400
},
Here, Apple Documentation has explained the difference between weak and strong property using various examples :
Here, In this blog author has collected all the properties in same place. It will help to compare properties characteristics :
http://rdcworld-iphone.blogspot.in/2012/12/variable-property-attributes-or.html
Another variant:
List<MyType> items = new List<MyType>();
items.AddRange(myDico.values);
The simplest and best way to get yesterday's date is:
subdate(current_date, 1)
Your query would be:
SELECT
url as LINK,
count(*) as timesExisted,
sum(DateVisited between UNIX_TIMESTAMP(subdate(current_date, 1)) and
UNIX_TIMESTAMP(current_date)) as timesVisitedYesterday
FROM mytable
GROUP BY 1
For the curious, the reason that sum(condition)
gives you the count of rows that satisfy the condition, which would otherwise require a cumbersome and wordy case
statement, is that in mysql boolean values are 1
for true and 0
for false, so summing a condition effectively counts how many times it's true. Using this pattern can neaten up your SQL code.
The currently accepted answer is incorrect - document.documentElement.scrollTop
always returns 0 on Chrome. This is because WebKit uses body
for keeping track of scrolling, whereas Firefox and IE use html
.
To get the current position, you want:
document.documentElement.scrollTop || document.body.scrollTop
You can set the current position to 1000px down the page like so:
document.documentElement.scrollTop = document.body.scrollTop = 1000;
Or, using jQuery (animate it while you're at it!):
$("html, body").animate({ scrollTop: "1000px" });
It will not work like this, put both images as background images:
.bg-img {
background:url(images/yourImg.jpg) no-repeat 0 0;
}
.bg-img:hover {
background:url(images/yourImg-1.jpg) no-repeat 0 0;
}
The error:
'int' object has no attribute '__getitem__'
means that you're attempting to apply the index operator []
on an int, not a list. So is col
not a list, even when it should be? Let's start from that.
Look here:
col = [[0 for col in range(5)] for row in range(6)]
Use a different variable name inside, looks like the list comprehension overwrites the col
variable during iteration. (Not during the iteration when you set col
, but during the following ones.)
It works for me in all the browsers:
document.onkeydown = function(){
switch (event.keyCode){
case 116 : //F5 button
event.returnValue = false;
event.keyCode = 0;
return false;
case 82 : //R button
if (event.ctrlKey){
event.returnValue = false;
event.keyCode = 0;
return false;
}
}
}
To get the first and the last day of the year, one can use the CONCAT
function. The resulting value may be cast to any type.
CONCAT(YEAR(Getdate()),'-01-01') FirstOfYear,
CONCAT(YEAR(GETDATE()),'-12-31') LastOfYear
The first solution does not work for any UTF-8 alphabet. (It will cut text such as ????). I have managed to create a function which does not use RegExp and use good UTF-8 support in the JavaScript engine. The idea is simple if a symbol is equal in uppercase and lowercase it is a special character. The only exception is made for whitespace.
function removeSpecials(str) {
var lower = str.toLowerCase();
var upper = str.toUpperCase();
var res = "";
for(var i=0; i<lower.length; ++i) {
if(lower[i] != upper[i] || lower[i].trim() === '')
res += str[i];
}
return res;
}
Update: Please note, that this solution works only for languages where there are small and capital letters. In languages like Chinese, this won't work.
Update 2: I came to the original solution when I was working on a fuzzy search. If you also trying to remove special characters to implement search functionality, there is a better approach. Use any transliteration library which will produce you string only from Latin characters and then the simple Regexp will do all magic of removing special characters. (This will work for Chinese also and you also will receive side benefits by making Tromsø
== Tromso
).
Way simplest: copy and paste this into Terminal (but be sure to read more first):
bash <(curl -Ls http://git.io/eUx7rg)
This will install and configure everything automagically. The script is provided by MacMiniVault and is available on Github. More information about the mySQL install script on http://www.macminivault.com/mysql-yosemite/.
Add step="0.01"
to the <input type="number" />
parameters:
<input type="number" min="0.01" step="0.01" max="2500" value="25.67" />
Demo: http://jsfiddle.net/uzbjve2u/
But the Dollar sign must stay outside the textbox... every non-numeric or separator charachter will be cropped automatically.
Otherwise you could use a classic textbox, like described here.
Use this as an example:
docker create --name new_ubuntu -it -p 8080:8080 -p 15672:15672 -p 5432:5432 ubuntu:latest bash
look what you've created(and copy its CONTAINER ID xxxxx):
docker ps -a
now write the miracle maker word(start):
docker start xxxxx
good luck
export default class App extends Component {_x000D_
state = { username: '', password: '' }_x000D_
_x000D_
onChangeText = (key, val) => {_x000D_
this.setState({ [key]: val})_x000D_
}_x000D_
_x000D_
render() { _x000D_
return (_x000D_
<View style={styles.container}>_x000D_
<Text>Login Form</Text>_x000D_
<TextInput_x000D_
placeholder='Username'_x000D_
onChangeText={val => this.onChangeText('username', val)}_x000D_
style={styles.input}_x000D_
/>_x000D_
<TextInput_x000D_
placeholder='Password'_x000D_
onChangeText={val => this.onChangeText('password', val)}_x000D_
style={styles.input}_x000D_
secureTextEntry={true}_x000D_
/> _x000D_
</View>_x000D_
);_x000D_
}_x000D_
}
_x000D_
Hope this will solve your problem
This also happens if your TLS client is unable to be authenticate by the server configured to require client authentication.
Technically both answers above are correct, but since you are setting your ImageView to fill_parent
instead of wrap_content
, the image within is not centered, but the ImageView itself is.
Give your ImageView the attributes:
android:scaleType="centerInside"
android:gravity="center"
The scaleType is really only necessary in this case if the image exceeds the size of the ImageView. You may also want different scaleTypes. In conclusion, android:gravity
is what you're looking for in this case, but if your ImageView is set to wrap_content
, you should set the ImageView's gravity (android:layout_gravity
) to be centered within the parent.
Below is an example of multiple figures that I used recently in Latex. You need to call these packages
\usepackage{graphicx}
\usepackage{subfig})
\begin{figure}[H]%
\centering
\subfloat[Row1]{{\includegraphics[scale=.36]{1.png} }}%
\subfloat[Row2]{{\includegraphics[scale=.36]{2.png} }}%
\subfloat[Row3]{{\includegraphics[scale=.36]{3.png} }}%
\hfill
\subfloat[Row4]{{\includegraphics[scale=0.37]{4.png} }}%
\subfloat[Row5]{{\includegraphics[scale=0.37]{5.png} }}%
\caption{Multiple figures in latex.}%
\label{fig:MFL}%
\end{figure}
You can simply use the most Pythonic approach (IMHO):
import os
your_path = r"d:\stuff\morestuff\furtherdown\THEFILE.txt"
path_list = your_path.split(os.sep)
print path_list
Which will give you:
['d:', 'stuff', 'morestuff', 'furtherdown', 'THEFILE.txt']
The clue here is to use os.sep
instead of '\\'
or '/'
, as this makes it system independent.
To remove colon from the drive letter (although I don't see any reason why you would want to do that), you can write:
path_list[0] = path_list[0][0]
Do you mean tmux window? Ctrl + b + ,
if you have C-b as send prefix (it's by default)
Also C-b :rename-window <new name>
and tmux rename-window <new name>
work too.
As I know you can't rename pane
Here's a link that helped me with this.
It uses PagedList.MVC NuGet package. I'll try to summarize the steps
Install the PagedList.MVC NuGet package
Build project
Add using PagedList;
to the controller
Modify your action to set page
public ActionResult ListMyItems(int? page)
{
List list = ItemDB.GetListOfItems();
int pageSize = 3;
int pageNumber = (page ?? 1);
return View(list.ToPagedList(pageNumber, pageSize));
}
Add paging links to the bottom of your view
@*Your existing view*@
Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount
@Html.PagedListPager(Model, page => Url.Action("Index",
new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
I found myself wanting to do this and I reviewed the above answers and did a hybrid approach of them. It got a little tricky, but here is what I did:
My button already worked with a server side post. I wanted to let that to continue to work so I left the "OnClick" the same, but added a OnClientClick:
OnClientClick="if (!OnClick_Submit()) return false;"
Here is my full button element in case it matters:
<asp:Button UseSubmitBehavior="false" runat="server" Class="ms-ButtonHeightWidth jiveSiteSettingsSubmit" OnClientClick="if (!OnClick_Submit()) return false;" OnClick="BtnSave_Click" Text="<%$Resources:wss,multipages_okbutton_text%>" id="BtnOK" accesskey="<%$Resources:wss,okbutton_accesskey%>" Enabled="true"/>
If I inspect the onclick attribute of the HTML button at runtime it actually looks like this:
if (!OnClick_Submit()) return false;WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$PlaceHolderMain$ctl03$RptControls$BtnOK", "", true, "", "", false, true))
Then in my Javascript I added the OnClick_Submit method. In my case I needed to do a check to see if I needed to show a dialog to the user. If I show the dialog I return false causing the event to stop processing. If I don't show the dialog I return true causing the event to continue processing and my postback logic to run as it used to.
function OnClick_Submit() {
var initiallyActive = initialState.socialized && initialState.activityEnabled;
var socialized = IsSocialized();
var enabled = ActivityStreamsEnabled();
var displayDialog;
// Omitted the setting of displayDialog for clarity
if (displayDialog) {
$("#myDialog").dialog('open');
return false;
}
else {
return true;
}
}
Then in my Javascript code that runs when the dialog is accepted, I do the following depending on how the user interacted with the dialog:
$("#myDialog").dialog('close');
__doPostBack('message', '');
The "message" above is actually different based on what message I want to send.
Back in my server-side code, I changed OnLoad from:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e)
if (IsPostBack)
{
return;
}
// OnLoad logic removed for clarity
}
To:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e)
if (IsPostBack)
{
switch (Request.Form["__EVENTTARGET"])
{
case "message1":
// We did a __doPostBack with the "message1" command provided
Page.Validate();
BtnSave_Click(this, new CommandEventArgs("message1", null));
break;
case "message2":
// We did a __doPostBack with the "message2" command provided
Page.Validate();
BtnSave_Click(this, new CommandEventArgs("message2", null));
break;
}
return;
}
// OnLoad logic removed for clarity
}
Then in BtnSave_Click method I do the following:
CommandEventArgs commandEventArgs = e as CommandEventArgs;
string message = (commandEventArgs == null) ? null : commandEventArgs.CommandName;
And finally I can provide logic based on whether or not I have a message and based on the value of that message.
Just use setTitle(null)
above
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
The title will disappear then you can use the logo of your choice.....
i think i'd try with MAX something like this:
SELECT staff_id, max( date ) from owner.table group by staff_id
then link in your other columns:
select staff_id, site_id, pay_level, latest
from owner.table,
( SELECT staff_id, max( date ) latest from owner.table group by staff_id ) m
where m.staff_id = staff_id
and m.latest = date
This file will serve you as a good sendfile
example : http://tldp.org/LDP/LGNET/91/misc/tranter/server.c.txt
HOPE YOU LIKE THIS SIMPLE CODE OF CONVERSION FROM DECIMAL TO BINARY
#include<iostream>
using namespace std;
int main()
{
int input,rem,res,count=0,i=0;
cout<<"Input number: ";
cin>>input;`enter code here`
int num=input;
while(input > 0)
{
input=input/2;
count++;
}
int arr[count];
while(num > 0)
{
arr[i]=num%2;
num=num/2;
i++;
}
for(int i=count-1 ; i>=0 ; i--)
{
cout<<" " << arr[i]<<" ";
}
return 0;
}
class Foo (object):
# ^class name #^ inherits from object
bar = "Bar" #Class attribute.
def __init__(self):
# #^ The first variable is the class instance in methods.
# # This is called "self" by convention, but could be any name you want.
#^ double underscore (dunder) methods are usually special. This one
# gets called immediately after a new instance is created.
self.variable = "Foo" #instance attribute.
print self.variable, self.bar #<---self.bar references class attribute
self.bar = " Bar is now Baz" #<---self.bar is now an instance attribute
print self.variable, self.bar
def method(self, arg1, arg2):
#This method has arguments. You would call it like this: instance.method(1, 2)
print "in method (args):", arg1, arg2
print "in method (attributes):", self.variable, self.bar
a = Foo() # this calls __init__ (indirectly), output:
# Foo bar
# Foo Bar is now Baz
print a.variable # Foo
a.variable = "bar"
a.method(1, 2) # output:
# in method (args): 1 2
# in method (attributes): bar Bar is now Baz
Foo.method(a, 1, 2) #<--- Same as a.method(1, 2). This makes it a little more explicit what the argument "self" actually is.
class Bar(object):
def __init__(self, arg):
self.arg = arg
self.Foo = Foo()
b = Bar(a)
b.arg.variable = "something"
print a.variable # something
print b.Foo.variable # Foo
You can use Scanner class like this:
import java.util.Scanner;
public class Main{
public static void main(String args[]){
Scanner scan= new Scanner(System.in);
//For string
String text= scan.nextLine();
System.out.println(text);
//for int
int num= scan.nextInt();
System.out.println(num);
}
}
You can use include=FALSE
to exclude everything in a chunk.
```{r include=FALSE}
source("C:/Rscripts/source.R")
```
If you only want to suppress messages, use message=FALSE
instead:
```{r message=FALSE}
source("C:/Rscripts/source.R")
```
just to add the full command:
adb shell ls -R | grep filename
this is actually a pretty fast lookup on Android
We can use the new fs.promises API
const fs = require('fs').promises;
(async() => {
const stat = await fs.lstat('test.txt');
console.log(stat.isFile());
})().catch(console.error)
Here's how you would detect if a path is a file or a directory asynchronously, which is the recommended approach in node. using fs.lstat
const fs = require("fs");
let path = "/path/to/something";
fs.lstat(path, (err, stats) => {
if(err)
return console.log(err); //Handle error
console.log(`Is file: ${stats.isFile()}`);
console.log(`Is directory: ${stats.isDirectory()}`);
console.log(`Is symbolic link: ${stats.isSymbolicLink()}`);
console.log(`Is FIFO: ${stats.isFIFO()}`);
console.log(`Is socket: ${stats.isSocket()}`);
console.log(`Is character device: ${stats.isCharacterDevice()}`);
console.log(`Is block device: ${stats.isBlockDevice()}`);
});
Note when using the synchronous API:
When using the synchronous form any exceptions are immediately thrown. You can use try/catch to handle exceptions or allow them to bubble up.
try{
fs.lstatSync("/some/path").isDirectory()
}catch(e){
// Handle error
if(e.code == 'ENOENT'){
//no such file or directory
//do something
}else {
//do something else
}
}
You have to drop the constraint before drop your table.
You can use those queries to find all FKs in your table and find the FKs in the tables in which your table is used.
Declare @SchemaName VarChar(200) = 'Your Schema name'
Declare @TableName VarChar(200) = 'Your Table Name'
-- Find FK in This table.
SELECT
' IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id =
OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + FK.name + ']'
+ ''') AND parent_object_id = OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' +
OBJECT_NAME(FK.parent_object_id) + ']' + ''')) ' +
'ALTER TABLE ' + OBJECT_SCHEMA_NAME(FK.parent_object_id) +
'.[' + OBJECT_NAME(FK.parent_object_id) +
'] DROP CONSTRAINT ' + FK.name
, S.name , O.name, OBJECT_NAME(FK.parent_object_id)
FROM sys.foreign_keys AS FK
INNER JOIN Sys.objects As O
ON (O.object_id = FK.parent_object_id )
INNER JOIN SYS.schemas AS S
ON (O.schema_id = S.schema_id)
WHERE
O.name = @TableName
And S.name = @SchemaName
-- Find the FKs in the tables in which this table is used
SELECT
' IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id =
OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + FK.name + ']'
+ ''') AND parent_object_id = OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' +
OBJECT_NAME(FK.parent_object_id) + ']' + ''')) ' +
' ALTER TABLE ' + OBJECT_SCHEMA_NAME(FK.parent_object_id) +
'.[' + OBJECT_NAME(FK.parent_object_id) +
'] DROP CONSTRAINT ' + FK.name
, S.name , O.name, OBJECT_NAME(FK.parent_object_id)
FROM sys.foreign_keys AS FK
INNER JOIN Sys.objects As O
ON (O.object_id = FK.referenced_object_id )
INNER JOIN SYS.schemas AS S
ON (O.schema_id = S.schema_id)
WHERE
O.name = @TableName
And S.name = @SchemaName
From the javadoc
@param the sole object to be stored in the returned list.
@return an immutable list containing only the specified object.
example
import java.util.*;
public class HelloWorld {
public static void main(String args[]) {
// create an array of string objs
String initList[] = { "One", "Two", "Four", "One",};
// create one list
List list = new ArrayList(Arrays.asList(initList));
System.out.println("List value before: "+list);
// create singleton list
list = Collections.singletonList("OnlyOneElement");
list.add("five"); //throws UnsupportedOperationException
System.out.println("List value after: "+list);
}
}
Use it when code expects a read-only list, but you only want to pass one element in it. singletonList
is (thread-)safe and fast.
Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.
The first element in a collection is generally located at index 0
. The last element is at index n-1
, where n
is the Size
of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1
, you're going to get an error.
When you declare an array like this:
var array = new int[6]
The first and last elements in the array are
var firstElement = array[0];
var lastElement = array[5];
So when you write:
var element = array[5];
you are retrieving the sixth element in the array, not the fifth one.
Typically, you would loop over an array like this:
for (int index = 0; index < array.Length; index++)
{
Console.WriteLine(array[index]);
}
This works, because the loop starts at zero, and ends at Length-1
because index
is no longer less than Length
.
This, however, will throw an exception:
for (int index = 0; index <= array.Length; index++)
{
Console.WriteLine(array[index]);
}
Notice the <=
there? index
will now be out of range in the last loop iteration, because the loop thinks that Length
is a valid index, but it is not.
Lists work the same way, except that you generally use Count
instead of Length
. They still start at zero, and end at Count - 1
.
for (int index = 0; i < list.Count; index++)
{
Console.WriteLine(list[index]);
}
However, you can also iterate through a list using foreach
, avoiding the whole problem of indexing entirely:
foreach (var element in list)
{
Console.WriteLine(element.ToString());
}
You cannot index an element that hasn't been added to a collection yet.
var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]); // Throws exception.
In Android Studio 3.0 +, sometimes UI tests are somehow interpreted as unit tests and it doesn't ask for target deployment selection. You can go to Edit Configuration and mark it as an Integration test and it would start working
Look at the WAITFOR command.
E.g.
-- wait for 1 minute
WAITFOR DELAY '00:01'
-- wait for 1 second
WAITFOR DELAY '00:00:01'
This command allows you a high degree of precision but is only accurate within 10ms - 16ms on a typical machine as it relies on GetTickCount. So, for example, the call WAITFOR DELAY '00:00:00:001'
is likely to result in no wait at all.
As other have already said, everything in S3 is an object. To you, it may be files and folders. But to S3, they're just objects.
If you don't need objects which end with a '/' you can safely delete them e.g. via REST api or AWS Java SDK (I assume you have write access). You will not lose "nested files" (there no files, so you will not lose objects whose names are prefixed with the key you delete)
AmazonS3 amazonS3 = AmazonS3ClientBuilder.standard().withCredentials(new ProfileCredentialsProvider()).withRegion("region").build();
amazonS3.deleteObject(new DeleteObjectRequest("my-bucket", "users/<user-id>/contacts/<contact-id>/"));
Please note that I'm using ProfileCredentialsProvider
so that my requests are not anonymous. Otherwise, you will not be able to delete an object. I have my AWS keep key stored in ~/.aws/credentials file.
A pandas MultiIndex consists of a list of tuples. So the most natural approach would be to reshape your input dict so that its keys are tuples corresponding to the multi-index values you require. Then you can just construct your dataframe using pd.DataFrame.from_dict
, using the option orient='index'
:
user_dict = {12: {'Category 1': {'att_1': 1, 'att_2': 'whatever'},
'Category 2': {'att_1': 23, 'att_2': 'another'}},
15: {'Category 1': {'att_1': 10, 'att_2': 'foo'},
'Category 2': {'att_1': 30, 'att_2': 'bar'}}}
pd.DataFrame.from_dict({(i,j): user_dict[i][j]
for i in user_dict.keys()
for j in user_dict[i].keys()},
orient='index')
att_1 att_2
12 Category 1 1 whatever
Category 2 23 another
15 Category 1 10 foo
Category 2 30 bar
An alternative approach would be to build your dataframe up by concatenating the component dataframes:
user_ids = []
frames = []
for user_id, d in user_dict.iteritems():
user_ids.append(user_id)
frames.append(pd.DataFrame.from_dict(d, orient='index'))
pd.concat(frames, keys=user_ids)
att_1 att_2
12 Category 1 1 whatever
Category 2 23 another
15 Category 1 10 foo
Category 2 30 bar
Sample Kotlin code as below:-
Page 1
val i = Intent(this, Page2::class.java)
val getrec = list[position].promotion_id
val bundle = Bundle()
bundle.putString("stuff", getrec)
i.putExtras(bundle)
startActivity(i)
Page 2
var bundle = getIntent().getExtras()
var stuff = bundle.getString("stuff")
Ctrl
+ F
install.packages("https://cran.r-project.org/src/contrib/Archive/[NAME OF PACKAGE]/[VERSION NUMBER].tar.gz", repos = NULL, type="source")
"In some cases, you need to install several packages in advance to use the package you want to use.
For example, I needed to install 7 packages(Sejong
, hash
, rJava
, tau
, RSQLite
, devtools
, stringr
) to install KoNLP
package.
install.packages('Sejong')
install.packages('hash')
install.packages('rJava')
install.packages('tau')
install.packages('RSQLite')
install.packages('devtools')
install.packages('stringr')
library(Sejong)
library(hash)
library(rJava)
library(tau)
library(RSQLite)
library(devtools)
library(stringr)
install.packages("https://cran.r-project.org/src/contrib/Archive/KoNLP/KoNLP_0.80.2.tar.gz", repos = NULL, type="source")
library(KoNLP)
Short answer:
In common use, space " "
, Tab "\t"
and newline "\n"
are the difference:
string.IsNullOrWhiteSpace("\t"); //true
string.IsNullOrEmpty("\t"); //false
string.IsNullOrWhiteSpace(" "); //true
string.IsNullOrEmpty(" "); //false
string.IsNullOrWhiteSpace("\n"); //true
string.IsNullOrEmpty("\n"); //false
https://dotnetfiddle.net/4hkpKM
also see this answer about: whitespace characters
Long answer:
There are also a few other white space characters, you probably never used before
https://docs.microsoft.com/en-us/dotnet/api/system.char.iswhitespace
Open with append:
pFile2 = fopen("myfile2.txt", "a");
then just write to pFile2
, no need to fseek()
.
You can use the magic methods __getattribute__
and __setattr__
.
class MyClass:
def __init__(self, attrvalue):
self.myattr = attrvalue
def __getattribute__(self, attr):
if attr == "myattr":
#Getter for myattr
def __setattr__(self, attr):
if attr == "myattr":
#Setter for myattr
Be aware that __getattr__
and __getattribute__
are not the same. __getattr__
is only invoked when the attribute is not found.
Strange that no-one mentioned the Cross Site scripting prevention benefit of .text()
over .html()
(Although others have just mentioned that .text()
escapes the data).
It's always recommended to use .text()
when you want to update data in DOM which is just data / text for the user to see.
.html()
should be mostly used to get the HTML content within a div.
The GNU Coding Standard is a good reference for things like this. This section deals with the output of --help
. In this case it is not very specific. You probably can't go wrong with printing a table showing the short and long options and a succinct description. Try to get the spacing between all arguments right for readability. You probably want to provide a man
page (and possibly an info
manual) for your tool to provide a more elaborate explanation.
Since many people arrive here debugging their slow website I would like to inform you about my case which none of the google explanations helped to resolve. My huge stalled times (sometimes 1min) were caused by Apache running on Windows having too few worker threads to handle the connections, therefore they were being queued.
This may apply to you if you apache log has following note:
Server ran out of threads to serve requests. Consider raising the ThreadsPerChild setting
This issue is resolved in Apache httpd.conf. Uncomment : Include conf/extra/httpd-mpm.conf
And edit httpd-mpm.conf
<IfModule mpm_winnt_module>
ThreadLimit 2000
ThreadsPerChild 2000
MaxConnectionsPerChild 0
</IfModule>
Note that you may not need 2000 threads, or may need more. 2000 was OK for my case.
This will strip all commas from the text and left justify it.
for row in inputfile:
place = row['your_row_number_here'].strip(', ')
? ????? ??????
use padding tags the above float tags didnt worked out, I used
padding left:5px;
padding left :30px
In Java type conversions are performed automatically when the type of the expression on the right hand side of an assignment operation can be safely promoted to the type of the variable on the left hand side of the assignment. Thus we can safely assign:
byte -> short -> int -> long -> float -> double.
The same will not work the other way round. For example we cannot automatically convert a long to an int because the first requires more storage than the second and consequently information may be lost. To force such a conversion we must carry out an explicit conversion.
Type - Conversion
In your third point, "T" cannot be resolved because its not declared, usually when you declare a generic class you can use "T" as the name of the bound type parameter, many online examples including oracle's tutorials use "T" as the name of the type parameter, say for example, you declare a class like:
public class FooHandler<T>
{
public void operateOnFoo(T foo) { /*some foo handling code here*/}
}
you are saying that FooHandler's
operateOnFoo
method expects a variable of type "T" which is declared on the class declaration itself, with this in mind, you can later add another method like
public void operateOnFoos(List<T> foos)
in all the cases either T, E or U there all identifiers of the type parameter, you can even have more than one type parameter which uses the syntax
public class MyClass<Atype,AnotherType> {}
in your forth ponint although efectively Sting is a sub type of Object, in generics classes there is no such relation, List<String>
is not a sub type of List<Object>
they are two diferent types from the compiler point of view, this is best explained in this blog entry
Escape the quotes with backslashes:
printf("She said \"time flies like an arrow, but fruit flies like a banana\".");
There are special escape characters that you can use in string literals, and these are denoted with a leading backslash.
I started creating a Node.js/browserify application following the Cross Platform JavaScript blog post. And I ran into this issue, because my brand new Gruntfile didn't pass jshint.
Luckily I found an answer in the Leanpub book on Grunt:
If we try it now, we will scan our Gruntfile… and get some errors:
$ grunt jshint Running "jshint:all" (jshint) task Linting Gruntfile.js...ERROR [L1:C1] W097: Use the function form of "use strict". 'use strict'; Linting Gruntfile.js...ERROR [L3:C1] W117: 'module' is not defined. module.exports = function (grunt) { Warning: Task "jshint:all" failed. Use --force to continue.
Both errors are because the Gruntfile is a Node program, and by default JSHint does not recognise or allow the use of
module
and the string version ofuse strict
. We can set a JSHint rule that will accept our Node programs. Let’s edit our jshint task configuration and add an options key:jshint: { options: { node: true }, }
Adding node: true
to the jshint options
, to put jshint into "Node mode", removed both errors for me.
This is an extension to Langdon's answer with a directive approach to the problem. If you're going to have multiple galleries on the page this may be one way to go about it without much fuss.
Usage:
<gallery images="items"></gallery>
<gallery images="cats"></gallery>
This uses twitter bootstrap 3.x with one css class to get labels to sit on top of the inputs. Here's a fiddle link, make sure to expand results panel wide enough to see effect.
HTML:
<div class="row myform">
<div class="col-md-12">
<form name="myform" role="form" novalidate>
<div class="form-group">
<label class="control-label" for="fullName">Address Line</label>
<input required type="text" name="addr" id="addr" class="form-control" placeholder="Address"/>
</div>
<div class="form-inline">
<div class="form-group">
<label>State</label>
<input required type="text" name="state" id="state" class="form-control" placeholder="State"/>
</div>
<div class="form-group">
<label>ZIP</label>
<input required type="text" name="zip" id="zip" class="form-control" placeholder="Zip"/>
</div>
</div>
<div class="form-group">
<label class="control-label" for="country">Country</label>
<input required type="text" name="country" id="country" class="form-control" placeholder="country"/>
</div>
</form>
</div>
</div>
CSS:
.myform input.form-control {
display: block; /* allows labels to sit on input when inline */
margin-bottom: 15px; /* gives padding to bottom of inline inputs */
}
ViewBag is of type dynamic. More, you cannot do ViewBag["Foo"]
. You will get exception - Cannot apply indexing with [] to an expression of type 'System.Dynamic.DynamicObject'.
Internal implementation of ViewBag
actually stores Foo into ViewData["Foo"]
(type of ViewDataDictionary), so those 2 are interchangeable. ViewData["Foo"]
and ViewBag.Foo
.
And scope. ViewBag and ViewData are ment to pass data between Controller's Actions and View it renders.
chmod 400 mykey.pem
ssh -i mykey.pem [email protected]
Will connect you over ssh using a .pem file to any server.
For full-screen frame redirects and similar things I have two methods. Both work fine on mobile and desktop.
Note this are complete cross-browser working, valid HTML files. Just change title
and src
for your needs.
1. this is my favorite:
<!DOCTYPE html>
<meta charset=utf-8>
<title> Title-1 </title>
<meta name=viewport content="width=device-width">
<style>
html, body, iframe { height:100%; width:100%; margin:0; border:0; display:block }
</style>
<iframe src=src1></iframe>
<!-- More verbose CSS for better understanding:
html { height:100% }
body { height:100%; margin:0 }
iframe { height:100%; width:100%; border:0; display:block }
-->
or 2. something like that, slightly shorter:
<!DOCTYPE html>
<meta charset=utf-8>
<title> Title-2 </title>
<meta name=viewport content="width=device-width">
<iframe src=src2 style="position:absolute; top:0; left:0; width:100%; height:100%; border:0">
</iframe>
Note:
The above examples avoid using height:100vh
because old browsers don't know it (maybe moot these days) and height:100vh
is not always equal to height:100%
on mobile browsers (probably not applicable here). Otherwise, vh
simplifies things a little bit, so
3. this is an example using vh (not my favorite, less compatible with little advantage)
<!DOCTYPE html>
<meta charset=utf-8>
<title> Title-3 </title>
<meta name=viewport content="width=device-width">
<style>
body { margin:0 }
iframe { display:block; width:100%; height:100vh; border:0 }
</style>
<iframe src=src3></iframe>
I learned python first by myself over a summer just by doing the tutorial on the python site (sadly, I don't seem to be able to find that anymore, so I can't post a link).
Later, python was taught to me in one of my first year courses at university. In the summer that followed, I practiced with PythonChallenge and with problems from Google Code Jam. Solving these problems help from an algorithmic perspective as well as from the perspective of learning what Python can do as well as how to manipulate it to get the fullest out of python.
For similar reasons, I have heard that code golf works as well, but i have never tried it for myself.
You need to check the origin
and add if not exists.
if ! git config remote.origin.url >/dev/null; then
git remote add origin [email protected]:john/doe.git
fi
Create file check.sh
, paste the script update your git repository URL and run ./check.sh
.
Spend a whole week, after all the following setting worked ! and finally saved. Removing the UrlScan from ISAPI fileters in IIS fixes the problem in our case
Using Java 8:
private static Comparator<String> nullSafeStringComparator = Comparator
.nullsFirst(String::compareToIgnoreCase);
private static Comparator<Metadata> metadataComparator = Comparator
.comparing(Metadata::getName, nullSafeStringComparator)
.thenComparing(Metadata::getValue, nullSafeStringComparator);
public int compareTo(Metadata that) {
return metadataComparator.compare(this, that);
}
["1","2","3","4"].forEach( function(item) {
const optionObj = document.createElement("option");
optionObj.textContent = item;
document.getElementById("myselect").appendChild(optionObj);
});
Date()
With this you call a function called Date()
. It doesn't accept any arguments and returns a string representing the current date and time.
new Date()
With this you're creating a new instance of Date.
You can use only the following constructors:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
So, use 2010-08-17 12:09:36
as parameter to constructor is not allowed.
See w3schools.
EDIT: new Date(dateString)
uses one of these formats:
Here's a trick I found to compare two branches and show how many commits each branch is ahead of the other (a more general answer on your question 1):
For local branches:
git rev-list --left-right --count master...test-branch
For remote branches:
git rev-list --left-right --count origin/master...origin/test-branch
This gives output like the following:
1 7
This output means: "Compared to master
, test-branch
is 7 commits ahead and 1 commit behind."
You can also compare local branches with remote branches, e.g. origin/master...master
to find out how many commits the local master
branch is ahead/behind its remote counterpart.
oImg.setAttribute('width', '1px');
px
is for CSS only. Use either:
oImg.width = '1';
to set a width through HTML, or:
oImg.style.width = '1px';
to set it through CSS.
Note that old versions of IE don't create a proper image with document.createElement()
, and old versions of KHTML don't create a proper DOM Node with new Image()
, so if you want to be fully backwards compatible use something like:
// IEWIN boolean previously sniffed through eg. conditional comments
function img_create(src, alt, title) {
var img = IEWIN ? new Image() : document.createElement('img');
img.src = src;
if ( alt != null ) img.alt = alt;
if ( title != null ) img.title = title;
return img;
}
Also be slightly wary of document.body.appendChild
if the script may execute as the page is in the middle of loading. You can end up with the image in an unexpected place, or a weird JavaScript error on IE. If you need to be able to add it at load-time (but after the <body>
element has started), you could try inserting it at the start of the body using body.insertBefore(body.firstChild)
.
To do this invisibly but still have the image actually load in all browsers, you could insert an absolutely-positioned-off-the-page <div>
as the body's first child and put any tracking/preload images you don't want to be visible in there.
You can also use DateTime class:
$time1 = new DateTime('09:00:59');
$time2 = new DateTime('09:01:00');
$interval = $time1->diff($time2);
echo $interval->format('%s second(s)');
Result:
1 second(s)
Simply create a new external tool configuration (from Eclipse Run -> External Tools)
for example - To open Cygwin terminal on the current resource directory:
Location:
C:\cygwin\bin\mintty.exe
Working Directory:
${container_loc}
Arguments:
-i /Cygwin-Terminal.ico
-"cygpath -p '${container_loc}' | xargs cd"
You have a line break <br>
in-between the second and third images in your markup. Get rid of that, and it'll show inline.
You need to set option CURLOPT_PROXYTYPE
to CURLPROXY_SOCKS5_HOSTNAME
, which sadly wasn't defined in old PHP versions, circa pre-5.6; if you have earlier in but you can explicitly use its value, which is equal to 7
:
curl_setopt($ch, CURLOPT_PROXYTYPE, 7);
I don't think that you need to use each()
, you can use standard for loop
var children = $element.children().not(".pb-sortable-placeholder");
for (var i = 0; i < children.length; i++) {
var currentChild = children.eq(i);
// whatever logic you want
var oldPosition = currentChild.data("position");
}
this way you can have the standard for loop features like break
and continue
works by default
also, the debugging will be easier
The keyword 'const' was proposed earlier and now it has been officially included in ES6. By using the const keyword, you can pass a value/string that will act as an immutable string.
I installed GitHubDesktop
on Windows 10 and git.exe
is located there:
C:\Users\john\AppData\Local\GitHubDesktop\app-0.7.2\resources\app\git\cmd\git.exe
If you are looking for UML sequence diagrams, you might be interested in pkf-umlsd, which is based on TiKZ. Nice demos can be found here.
I was also struggling with this problem, and find that the best way is to use a CURSOR.
I have tried Denis solution with OUTPUT, but as he mentiond, it's impossible to output external columns in an insert statement, and the MERGE can't work when insert multiple rows by select.
So, i've used a CURSOR, for each row in the outer table, i've done a INSERT, then use the @@IDENTITY for another INSERT.
DECLARE @OuterID int
DECLARE MY_CURSOR CURSOR
LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR
SELECT ID FROM [external_Table]
OPEN MY_CURSOR
FETCH NEXT FROM MY_CURSOR INTO @OuterID
WHILE @@FETCH_STATUS = 0
BEGIN
INSERT INTO [Table] (data)
SELECT data
FROM [external_Table] where ID = @OuterID
INSERT INTO [second_table] (FK,OuterID)
VALUES(@OuterID,@@identity)
FETCH NEXT FROM MY_CURSOR INTO @OuterID
END
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR
First, I thought:
"...In Microsoft SQL Server the
SELECT...INTO
automatically creates the new table whereas Oracle seems to require you to manually create it before executing theSELECT...INTO
statement..."
But after manually generating a table, it still did not work, still showing the "missing keyword" error.
So I gave up this time and solved it by first manually creating the table, then using the "classic" SELECT
statement:
INSERT INTO assignment_20081120 SELECT * FROM assignment;
Which worked as expected. If anyone come up with an explanaition on how to use the SELECT...INTO
in a correct way, I would be happy!
You could do something like the following which is really easy and very clean:
public function __construct()
{
$arguments = func_get_args();
switch(sizeof(func_get_args()))
{
case 0: //No arguments
break;
case 1: //One argument
$this->do_something($arguments[0]);
break;
case 2: //Two arguments
$this->do_something_else($arguments[0], $arguments[1]);
break;
}
}
Use your subquery to return the correct grouping, because you're halfway there.
Try this:
select
a.*
from
messages a
inner join
(select name, max(id) as maxid from messages group by name) as b on
a.id = b.maxid
If it's not id
you want the max of:
select
a.*
from
messages a
inner join
(select name, max(other_col) as other_col
from messages group by name) as b on
a.name = b.name
and a.other_col = b.other_col
This way, you avoid correlated subqueries and/or ordering in your subqueries, which tend to be very slow/inefficient.
In pre Sql 2008 By taking out the date part:
GROUP BY CONVERT(CHAR(8),DateTimeColumn,10)
This can be simplified by completely skipping the where object and the $users declaration. All you need is:
Code
get-content c:\scripts\users.txt | get-aduser -properties * | select displayname, office | export-csv c:\path\to\your.csv
Why are you trying to run "./adb"? That skips the path variable entirely and only looks for "adb" in the current directory. Try running "adb" instead.
Edit: your path looks wrong. You say you get
/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/Libs/android-sdk-mac_x86/tools:/Libs/android-sdk-mac_x86/platform-tools
You're missing the /Users/simon part.
Also note that if you have both .profile and .bash_profile files, only the latter gets executed.
IISReset stops and restarts the entire web server (including non-ASP.NET apps)
Recycling an app pool will only affect applications running in that app pool.
Editing the web.config in a web application only affects that web application (recycles just that app).
Editing the machine.config on the machine will recycle all app pools running.
IIS will monitor the /bin directory of your application. Whenever a change is detected in those dlls, it will recycle the app and re-load those new dlls. It also monitors the web.config & machine.config in the same way and performs the same action for the applicable apps.
David's post was attempting to show what the clock resolution is on Windows. I was confused by his output, so I wrote some code that shows that time.time()
on my Windows 8 x64 laptop has a resolution of 1 msec:
# measure the smallest time delta by spinning until the time changes
def measure():
t0 = time.time()
t1 = t0
while t1 == t0:
t1 = time.time()
return (t0, t1, t1-t0)
samples = [measure() for i in range(10)]
for s in samples:
print s
Which outputs:
(1390455900.085, 1390455900.086, 0.0009999275207519531)
(1390455900.086, 1390455900.087, 0.0009999275207519531)
(1390455900.087, 1390455900.088, 0.0010001659393310547)
(1390455900.088, 1390455900.089, 0.0009999275207519531)
(1390455900.089, 1390455900.09, 0.0009999275207519531)
(1390455900.09, 1390455900.091, 0.0010001659393310547)
(1390455900.091, 1390455900.092, 0.0009999275207519531)
(1390455900.092, 1390455900.093, 0.0009999275207519531)
(1390455900.093, 1390455900.094, 0.0010001659393310547)
(1390455900.094, 1390455900.095, 0.0009999275207519531)
And a way to do a 1000 sample average of the delta:
reduce( lambda a,b:a+b, [measure()[2] for i in range(1000)], 0.0) / 1000.0
Which output on two consecutive runs:
0.001
0.0010009999275207519
So time.time()
on my Windows 8 x64 has a resolution of 1 msec.
A similar run on time.clock()
returns a resolution of 0.4 microseconds:
def measure_clock():
t0 = time.clock()
t1 = time.clock()
while t1 == t0:
t1 = time.clock()
return (t0, t1, t1-t0)
reduce( lambda a,b:a+b, [measure_clock()[2] for i in range(1000000)] )/1000000.0
Returns:
4.3571334791658954e-07
Which is ~0.4e-06
An interesting thing about time.clock()
is that it returns the time since the method was first called, so if you wanted microsecond resolution wall time you could do something like this:
class HighPrecisionWallTime():
def __init__(self,):
self._wall_time_0 = time.time()
self._clock_0 = time.clock()
def sample(self,):
dc = time.clock()-self._clock_0
return self._wall_time_0 + dc
(which would probably drift after a while, but you could correct this occasionally, for example dc > 3600
would correct it every hour)
The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:
Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();
This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.
Try to write your code between the HTML pre tag.
Cast the operands to floats:
float ans = (float)a / (float)b;
ASCII: 7 bits. 128 code points.
ISO-8859-1: 8 bits. 256 code points.
UTF-8: 8-32 bits (1-4 bytes). 1,112,064 code points.
Both ISO-8859-1 and UTF-8 are backwards compatible with ASCII, but UTF-8 is not backwards compatible with ISO-8859-1:
#!/usr/bin/env python3
c = chr(0xa9)
print(c)
print(c.encode('utf-8'))
print(c.encode('iso-8859-1'))
Output:
©
b'\xc2\xa9'
b'\xa9'
Referencing means taking the address of an existing variable (using &) to set a pointer variable. In order to be valid, a pointer has to be set to the address of a variable of the same type as the pointer, without the asterisk:
int c1;
int* p1;
c1 = 5;
p1 = &c1;
//p1 references c1
Dereferencing a pointer means using the * operator (asterisk character) to retrieve the value from the memory address that is pointed by the pointer: NOTE: The value stored at the address of the pointer must be a value OF THE SAME TYPE as the type of variable the pointer "points" to, but there is no guarantee this is the case unless the pointer was set correctly. The type of variable the pointer points to is the type less the outermost asterisk.
int n1;
n1 = *p1;
Invalid dereferencing may or may not cause crashes:
Invalid referencing is more likely to cause compiler errors than crashes, but it's not a good idea to rely on the compiler for this.
References:
http://www.codingunit.com/cplusplus-tutorial-pointers-reference-and-dereference-operators
& is the reference operator and can be read as “address of”.
* is the dereference operator and can be read as “value pointed by”.
http://www.cplusplus.com/doc/tutorial/pointers/
& is the reference operator
* is the dereference operator
http://en.wikipedia.org/wiki/Dereference_operator
The dereference operator * is also called the indirection operator.
Inspired by sergionni's answer, I ended up doing the following steps:
Help --> Installation Details --> Installation History tab
In the Previous configurations
table, you can select a configuration
and see in the Configuration contents
exactly which plugins were installed and are included in it.
It's easy to find the configuration that contains the plugin you want to remove, using the Compare
button. This button is enabled when two configurations are selected.
After tracking the configuration that's responsible for that plugin, select the previous configuration and press the Revert
button.
Note that if you revert to a configuration that isn't the one just right before the Current Installation
, it causes any other plugins that were installed since, to be uninstalled as well.
In summary :
<input type="submit">
<button type="submit"> Submit </button>
Both by default will visually draw a button that performs the same action (submit the form).
However, it is recommended to use <button type="submit">
because it has better semantics, better ARIA support and it is easier to style.
For Each is much faster than for I=1 to X, for some reason. Just try to go through the same dictionary,
once with for each Dkey in dDict,
and once with for Dkey = lbound(dDict.keys) to ubound(dDict.keys)
=>You will notice a huge difference, even though you are going through the same construct.
You can use meta characters like *
(http://api.jquery.com/category/selectors/).
So I think you just can use $('#player_*')
.
In your case you could also try the "Attribute starts with" selector:
http://api.jquery.com/attribute-starts-with-selector/: $('div[id^="player_"]')
git reset --hard 4a155e5
Will move the HEAD back to where you want to be. There may be other references ahead of that time that you would need to remove if you don't want anything to point to the history you just deleted.
select 'delete from ' +TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_TYPE='BASE TABLE'
where result come.
Copy and paste on query window and run the command
If you're not worried about a couple minutes time to do so, a solution would be to rm -rf node_modules
and npm install
again to rebuild the local modules.