For python2 users on MacOS (python@2 formula won't be found), as brew stopped support of python2 you need to use such command! But don't forget to unlink old python if it was pre-installed.
brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/86a44a0a552c673a05f11018459c9f5faae3becc/Formula/[email protected]
If you've done some mistake, simply brew uninstall python@2
old way, and try again.
git config user.name
git config user.email
I believe these are the commands you are looking for.
Here is where I found them: http://alvinalexander.com/git/git-show-change-username-email-address
For me below solution worked you may get help too, I wrote below line in app's gradle file
packagingOptions {
exclude 'META-INF/proguard/androidx-annotations.pro'
}
For those who other solutions are not working, check if you're using a DNS service like CloudFlare. In that case activate the "Development Mode" or use the "Purge Cache" tool.
Better to return HttpResponseMessage with StreamContent inside of it.
Here is example:
public HttpResponseMessage GetFile(string id)
{
if (String.IsNullOrEmpty(id))
return Request.CreateResponse(HttpStatusCode.BadRequest);
string fileName;
string localFilePath;
int fileSize;
localFilePath = getFileFromID(id, out fileName, out fileSize);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = fileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return response;
}
UPD from comment by patridge: Should anyone else get here looking to send out a response from a byte array instead of an actual file, you're going to want to use new ByteArrayContent(someData) instead of StreamContent (see here).
As I often need a fast way to reset current branch on windows through command prompt, here's a fast way:
for /f "tokens=1* delims= " %a in ('git branch^|findstr /b "*"') do @git reset --hard origin/%b
Thumbs up first before use codes please!!! Create an image that fully cover the whole tab bar item for each item. This is needed to use the image you created as a tab bar item button. Be sure to make the height/width ratio be the same of each tab bar item too. Then:
UITabBarController *tabBarController = (UITabBarController *)self;
UITabBar *tabBar = tabBarController.tabBar;
UITabBarItem *tabBarItem1 = [tabBar.items objectAtIndex:0];
UITabBarItem *tabBarItem2 = [tabBar.items objectAtIndex:1];
UITabBarItem *tabBarItem3 = [tabBar.items objectAtIndex:2];
UITabBarItem *tabBarItem4 = [tabBar.items objectAtIndex:3];
int x,y;
x = tabBar.frame.size.width/4 + 4; //when doing division, it may be rounded so that you need to add 1 to each item;
y = tabBar.frame.size.height + 10; //the height return always shorter, this is compensated by added by 10; you can change the value if u like.
//because the whole tab bar item will be replaced by an image, u dont need title
tabBarItem1.title = @"";
tabBarItem2.title = @"";
tabBarItem3.title = @"";
tabBarItem4.title = @"";
[tabBarItem1 setFinishedSelectedImage:[self imageWithImage:[UIImage imageNamed:@"item1-select.png"] scaledToSize:CGSizeMake(x, y)] withFinishedUnselectedImage:[self imageWithImage:[UIImage imageNamed:@"item1-deselect.png"] scaledToSize:CGSizeMake(x, y)]];//do the same thing for the other 3 bar item
JVM specification doesn't say anything specific about garbage collection. Due to this, vendors are free to implement GC in their way.
So this vagueness causes uncertainty in garbage collection behavior. You should check your JVM details to know about the garbage collection approaches/algorithms. Also there are options to customize behavior as well.
Use the following:
bower install --save git://github.com/USER/REPOS_NAME.git
More here: http://bower.io/#getting-started
That's because you want @selector(lowercaseString)
, not @selector(lowercaseString:)
. There's a subtle difference: the second one implies a parameter (note the colon at the end), but - [NSString lowercaseString]
does not take a parameter.
You can rename (changing URL of a remote repository) using :
git remote set-url origin new_URL
new_URL can be like https://github.com/abcdefgh/abcd.git
Too permanently delete the remote repository use :
git remote remove origin
- name: host
debug: msg="{{ item }}"
with_items:
- "{{ groups['tests'] }}"
This piece of code will give the message:
'10.112.84.122'
'10.112.84.124'
as groups['tests']
basically return a list of unique ip addresses ['10.112.84.122','10.112.84.124']
whereas groups['tomcat'][0]
returns 10.112.84.124
.
Use This:
rm -Force ./.git/index.lock
I agree with the above comments about overriding toString()
on your own classes (and about automating that process as much as possible).
For classes you didn't define, you could write a ToStringHelper
class with an overloaded method for each library class you want to have handled to your own tastes:
public class ToStringHelper {
//... instance configuration here (e.g. punctuation, etc.)
public toString(List m) {
// presentation of List content to your liking
}
public toString(Map m) {
// presentation of Map content to your liking
}
public toString(Set m) {
// presentation of Set content to your liking
}
//... etc.
}
EDIT: Responding to the comment by xukxpvfzflbbld, here's a possible implementation for the cases mentioned previously.
package com.so.demos;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class ToStringHelper {
private String separator;
private String arrow;
public ToStringHelper(String separator, String arrow) {
this.separator = separator;
this.arrow = arrow;
}
public String toString(List<?> l) {
StringBuilder sb = new StringBuilder("(");
String sep = "";
for (Object object : l) {
sb.append(sep).append(object.toString());
sep = separator;
}
return sb.append(")").toString();
}
public String toString(Map<?,?> m) {
StringBuilder sb = new StringBuilder("[");
String sep = "";
for (Object object : m.keySet()) {
sb.append(sep)
.append(object.toString())
.append(arrow)
.append(m.get(object).toString());
sep = separator;
}
return sb.append("]").toString();
}
public String toString(Set<?> s) {
StringBuilder sb = new StringBuilder("{");
String sep = "";
for (Object object : s) {
sb.append(sep).append(object.toString());
sep = separator;
}
return sb.append("}").toString();
}
}
This isn't a full-blown implementation, but just a starter.
I had a similar issue, in my case I am using a custom settings.xml
which was not picked from IntelliJ.
Solution:
File > Settings > Build, Execution, Deployment > Maven: User settings file
(chose here my custom settings.xml).
If you wish to create a pdf from php, pdflib will help you (as some others suggested).
Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.
So, the options I know are:
DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.
HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.
Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:
wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.
htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.
This answer is an update with a little more consideration for OOM and various other leaks.
Assumes you have a directory intended as the destination and a name String already defined.
File destination = new File(directory.getPath() + File.separatorChar + filename);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
source.compress(Bitmap.CompressFormat.PNG, 100, bytes);
FileOutputStream fo = null;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
} catch (IOException e) {
} finally {
try {
fo.close();
} catch (IOException e) {}
}
If data already exists in the column you should do:
ALTER TABLE tbl_name ALTER COLUMN col_name TYPE integer USING col_name::integer;
As pointed out by @nobu and @jonathan-porter in comments to @derek-kromm's answer.
Here is a function that compares your test data against the training data, with the Tf-Idf transformer fitted with the training data. Advantage is that you can quickly pivot or group by to find the n closest elements, and that the calculations are down matrix-wise.
def create_tokenizer_score(new_series, train_series, tokenizer):
"""
return the tf idf score of each possible pairs of documents
Args:
new_series (pd.Series): new data (To compare against train data)
train_series (pd.Series): train data (To fit the tf-idf transformer)
Returns:
pd.DataFrame
"""
train_tfidf = tokenizer.fit_transform(train_series)
new_tfidf = tokenizer.transform(new_series)
X = pd.DataFrame(cosine_similarity(new_tfidf, train_tfidf), columns=train_series.index)
X['ix_new'] = new_series.index
score = pd.melt(
X,
id_vars='ix_new',
var_name='ix_train',
value_name='score'
)
return score
train_set = pd.Series(["The sky is blue.", "The sun is bright."])
test_set = pd.Series(["The sun in the sky is bright."])
tokenizer = TfidfVectorizer() # initiate here your own tokenizer (TfidfVectorizer, CountVectorizer, with stopwords...)
score = create_tokenizer_score(train_series=train_set, new_series=test_set, tokenizer=tokenizer)
score
ix_new ix_train score
0 0 0 0.617034
1 0 1 0.862012
An array is a variable, so in that case mapfile will work
mapfile y <<'z'
abc'asdf"
$(dont-execute-this)
foo"bar"''
z
Then you can print like this
printf %s "${y[@]}"
Another example of the same concept - but say - you have 2 different columns - and you want to apply different agg functions to each of them i.e
f.groupBy("col1").agg(sum("col2").alias("col2"), avg("col3").alias("col3"), ...)
Here is the way to achieve it - though I do not yet know how to add the alias in this case
See the example below - Using Maps
val Claim1 = StructType(Seq(StructField("pid", StringType, true),StructField("diag1", StringType, true),StructField("diag2", StringType, true), StructField("allowed", IntegerType, true), StructField("allowed1", IntegerType, true)))
val claimsData1 = Seq(("PID1", "diag1", "diag2", 100, 200), ("PID1", "diag2", "diag3", 300, 600), ("PID1", "diag1", "diag5", 340, 680), ("PID2", "diag3", "diag4", 245, 490), ("PID2", "diag2", "diag1", 124, 248))
val claimRDD1 = sc.parallelize(claimsData1)
val claimRDDRow1 = claimRDD1.map(p => Row(p._1, p._2, p._3, p._4, p._5))
val claimRDD2DF1 = sqlContext.createDataFrame(claimRDDRow1, Claim1)
val l = List("allowed", "allowed1")
val exprs = l.map((_ -> "sum")).toMap
claimRDD2DF1.groupBy("pid").agg(exprs) show false
val exprs = Map("allowed" -> "sum", "allowed1" -> "avg")
claimRDD2DF1.groupBy("pid").agg(exprs) show false
.name
{
max-width: 100%;
overflow-x: hidden;
}
You apply the above style or you can create function in javaScript to solve that problem
That's true, element in Set are not ordered, by definition of the Set Collection. So they can't be access by an index.
But why don't we have a get(object) method, not by providing the index as parameter, but an object that is equal to the one we are looking for? By this way, we can access the data of the element inside the Set, just by knowing its attributes used by the equal method.
I find that num * 1
is simple, clear, and works for integers and floats...
You need to split the line first.
import csv
with open('log.txt', 'r') as in_file:
stripped = (line.strip() for line in in_file)
lines = (line.split(",") for line in stripped if line)
with open('log.csv', 'w') as out_file:
writer = csv.writer(out_file)
writer.writerow(('title', 'intro'))
writer.writerows(lines)
If you're using jQuery, it's as simple as this:
$('#mySelect').change(function()
{
$('#myForm').submit();
});
It is no use putting the .fn, it will reffers to the prototype.
What you need to do is $.fancybox.close();
The thing is that you are maybe experiencing another error from js.
There are any errors on screen?
Is your fancybox and jquery the latest releases?
jquery is currently in 1.4.1 and fb in 1.3 something
Experiment putting a link inside the fancybox and put that function in it.
You probably had read that, but in any case, http://fancybox.net/api
One thing that you probably might need to do is isolate each part in order to realize what it is.
Still an old one, but answer from Lee did not give me the group.Key as result. Therefore, I am using the following statement to group a list and return a grouped list:
public IOrderedEnumerable<IGrouping<string, User>> groupedCustomerList;
groupedCustomerList =
from User in userList
group User by User.GroupID into newGroup
orderby newGroup.Key
select newGroup;
Each group now has a key, but also contains an IGrouping which is a collection that allows you to iterate over the members of the group.
Using lodash would be good solution
Ex:
var object = { 'a': { 'b': { 'c': 3 } } };
_.get(object, 'a.b.c');
// => 3
I think you want to change the setting called "DropDownStyle" to be "DropDownList".
Well a big requirement to implement PreRender as opposed to Load is the need to work with the controls on the page. On Page_Load, the controls are not rendered, and therefore cannot be referenced.
If you want to have a solid color for your navigation bar in iOS 6 similar to iOS 7 use this:
[[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setBackgroundColor:[UIColor greenColor]];
in iOS 7 use the barTintColor
like this:
navigationController.navigationBar.barTintColor = [UIColor greenColor];
or
[[UINavigationBar appearance] setBarTintColor:[UIColor greenColor]];
A more appropriate method is to use std::cin.ignore
:
#include <iostream>
void Pause()
{
std::cout << "Press Enter to continue...";
std::cout.flush();
std::cin.ignore(10000, '\n');
return;
}
Try this one:
function show_sub(cat) {
var parent = cat,
sub = parent.getElementsByClassName('sub');
if (sub[0].style.display == 'inline'){
sub[0].style.display = 'none';
}
else {
sub[0].style.display = 'inline';
}
}
document.getElementById('cat').onclick = function(){
show_sub(this);
};?
and use this for IE6 & 7
if (typeof document.getElementsByClassName!='function') {
document.getElementsByClassName = function() {
var elms = document.getElementsByTagName('*');
var ei = new Array();
for (i=0;i<elms.length;i++) {
if (elms[i].getAttribute('class')) {
ecl = elms[i].getAttribute('class').split(' ');
for (j=0;j<ecl.length;j++) {
if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
ei.push(elms[i]);
}
}
} else if (elms[i].className) {
ecl = elms[i].className.split(' ');
for (j=0;j<ecl.length;j++) {
if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
ei.push(elms[i]);
}
}
}
}
return ei;
}
}
follow some steps below:
open cygwin setup again
choose catagory on view tab
fill "make" in search tab
expand devel
find "make: a GNU version of the 'make' ultility", click to install
Done!
If someone wants to handle backPressed for a webView inside a fragment, then he can use below code.
Copy below code into your Activity
class (that contains a fragment YourFragmmentName
)
@Override
public void onBackPressed() {
List<Fragment> fragmentList = getSupportFragmentManager().getFragments();
boolean handled = false;
for(Object f: fragmentList) {
if(f instanceof YourFragmentName) {
handled = ((YourFragmentName)f).onBackPressed();
if(handled) {
break;
}
}
}
if(!handled) {
super.onBackPressed();
}
}
Copy this code in the fragment YourFragmentName
public boolean onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
return true;
} else {
return false;
}
}
Notes
Activity
should be replaced with the actual Acitivity class you are using.YourFragmentName
should be replaced with the name of your Fragment.webView
in YourFragmentName
so that it can be accessed from within the function.DISTINCT is the keyword you're looking for.
In MSSQL, copying unique rows from a table to another can be done like this:
SELECT DISTINCT column_name
INTO newTable
FROM srcTable
The column_name
is the column you're searching the unique values from.
Tested and works.
Python calls __enter__
when execution enters the context of the with statement and it’s time to acquire the resource. When execution leaves the context again, Python calls __exit__
to free up the resource
Let's consider Context Managers and the “with” Statement in Python. Context Manager is a simple “protocol” (or interface) that your object needs to follow so it can be used with the with statement. Basically all you need to do is add enter and exit methods to an object if you want it to function as a context manager. Python will call these two methods at the appropriate times in the resource management cycle.
Let’s take a look at what this would look like in practical terms. Here’s how a simple implementation of the open() context manager might look like:
class ManagedFile:
def __init__(self, name):
self.name = name
def __enter__(self):
self.file = open(self.name, 'w')
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
Our ManagedFile class follows the context manager protocol and now supports the with statement.
>>> with ManagedFile('hello.txt') as f:
... f.write('hello, world!')
... f.write('bye now')`enter code here`
Python calls enter when execution enters the context of the with statement and it’s time to acquire the resource. When execution leaves the context again, Python calls exit to free up the resource.
Writing a class-based context manager isn’t the only way to support the with statement in Python. The contextlib utility module in the standard library provides a few more abstractions built on top of the basic context manager protocol. This can make your life a little easier if your use cases matches what’s offered by contextlib.
I had the same problem but it occured in all my projects, I tried Invalidate Cache / Restart
but even it doesn´t solved the problem.
At the end I realized that in my Gradle Settings
, Offline Work
was enabled.
Go to Build, Execution, Deployment
> Gradle
in Gradle Settings
unchecked Offline Work
.
It solved the the problem downloading some configuration files for my Android Studio.
You need some sort of Inter Process Communication. Use a pipe or a shared buffer.
2.0 Compatible Answer: In Tensorflow 2.x (2.1)
, you can get the dimensions (shape) of the tensor as integer values, as shown in the Code below:
Method 1 (using tf.shape
):
import tensorflow as tf
c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
Shape = c.shape.as_list()
print(Shape) # [2,3]
Method 2 (using tf.get_shape()
):
import tensorflow as tf
c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
Shape = c.get_shape().as_list()
print(Shape) # [2,3]
Use this one, it is trusted solution and works well for all browsers:
protected void clearInput(WebElement webElement) {
// isIE() - just checks is it IE or not - use your own implementation
if (isIE() && "file".equals(webElement.getAttribute("type"))) {
// workaround
// if IE and input's type is file - do not try to clear it.
// If you send:
// - empty string - it will find file by empty path
// - backspace char - it will process like a non-visible char
// In both cases it will throw a bug.
//
// Just replace it with new value when it is need to.
} else {
// if you have no StringUtils in project, check value still empty yet
while (!StringUtils.isEmpty(webElement.getAttribute("value"))) {
// "\u0008" - is backspace char
webElement.sendKeys("\u0008");
}
}
}
If input has type="file" - do not clear it for IE. It will try to find file by empty path and will throw a bug.
More details you could find on my blog
I got this error after change a loop in my program, let`s see:
for ...
for ...
x_batch.append(one_hot(int_word, vocab_size))
y_batch.append(one_hot(int_nb, vocab_size, value))
...
...
if ...
x_batch = np.asarray(x_batch)
y_batch = np.asarray(y_batch)
...
In fact, I was reusing the variable and forgot to reset them inside the external loop, like the comment of John Lyon:
for ...
x_batch = []
y_batch = []
for ...
x_batch.append(one_hot(int_word, vocab_size))
y_batch.append(one_hot(int_nb, vocab_size, value))
...
...
if ...
x_batch = np.asarray(x_batch)
y_batch = np.asarray(y_batch)
...
Then, check if you are using np.asarray() or something like that.
throw
re-throws the caught exception, retaining the stack trace, while throw new Exception
loses some of the details of the caught exception.
You would normally use throw
by itself to log an exception without fully handling it at that point.
BlackWasp has a good article sufficiently titled Throwing Exceptions in C#.
You need to use .change()
event as well as using #
to target element by id
:
$('#EventStartTimeMin').change(function() {
if($(this).val()===""){
console.log('empty');
}
});
An <input>
's width is generated from its size
attribute. The default size
is what's driving the auto width.
You could try width:100%
as illustrated in my example below.
Doesn't fill width:
<form action='' method='post' style='width:200px;background:khaki'>
<input style='width:auto' />
</form>
Fills width:
<form action='' method='post' style='width:200px;background:khaki'>
<input style='width:100%' />
</form>
Smaller size, smaller width:
<form action='' method='post' style='width:200px;background:khaki'>
<input size='5' />
</form>
UPDATE
Here's the best I could do after a few minutes. It's 1px off in FF, Chrome, and Safari, and perfect in IE. (The problem is #^&* IE applies borders differently than everyone else so it's not consistent.)
<div style='padding:30px;width:200px;background:red'>
<form action='' method='post' style='width:200px;background:blue;padding:3px'>
<input size='' style='width:100%;margin:-3px;border:2px inset #eee' />
<br /><br />
<input size='' style='width:100%' />
</form>
</div>
Just how you've done it. assertTrue(boolean)
also has an overload assertTrue(String, boolean)
where the String
is the message in case of failure; you can use that if you want to print that such-and-such wasn't greater than so-and-so.
You could also add hamcrest-all
as a dependency to use matchers. See https://code.google.com/p/hamcrest/wiki/Tutorial:
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
assertThat("timestamp",
Long.parseLong(previousTokenValues[1]),
greaterThan(Long.parseLong(currentTokenValues[1])));
That gives an error like:
java.lang.AssertionError: timestamp
Expected: a value greater than <456L>
but: <123L> was less than <456L>
On OSX Mojave 10.14, go
is typically installed at /usr/local/go
.
Hence, setup these ENVs and you should be good to go.
export GOPATH=/usr/local/go && export GOBIN=/usr/local/go/bin
Also, add these to your bash_profile
or zsh_profile
if it works.
echo "export GOPATH=/usr/local/go && export GOBIN=/usr/local/go/bin" >> ~/.bash_profile && source ~/.bash_profile
Use the std::getline()
from <string>
.
istream & getline(istream & is,std::string& str)
So, for your case it would be:
std::getline(read,x);
I wanted to add to the discussion above but don't have the reputation to comment.
Python 3.8 is not quite released yet, but it will even include the reversed()
function on dictionaries (removing another difference from OrderedDict
.
Dict and dictviews are now iterable in reversed insertion order using reversed(). (Contributed by Rémi Lapeyre in bpo-33462.) See what's new in python 3.8
I don't see any mention of the equality operator or other features of OrderedDict
so they are still not entirely the same.
You can add a new branch test
on local and then use:
git branch --set-upstream-to=origin/test test
As of this date, the correct way according to the dynamic routing docs is:
this.$route.params.yourProperty
instead of
this.$route.query.yourProperty
You should be able to access the query using dot notation now.
If you want to access say you are receiving a GET request at /checkEmail?type=email&utm_source=xxxx&email=xxxxx&utm_campaign=XX
and you want to fetch out the query used.
var type = req.query.type,
email = req.query.email,
utm = {
source: req.query.utm_source,
campaign: req.query.utm_campaign
};
Params are used for the self defined parameter for receiving request, something like (example):
router.get('/:userID/food/edit/:foodID', function(req, res){
//sample GET request at '/xavg234/food/edit/jb3552'
var userToFind = req.params.userID;//gets xavg234
var foodToSearch = req.params.foodID;//gets jb3552
User.findOne({'userid':userToFind}) //dummy code
.then(function(user){...})
.catch(function(err){console.log(err)});
});
python supports arbitrarily large integers naturally:
In [1]: 59**3*61**4*2*3*5*7*3*5*7
Out[1]: 62702371781194950
In [2]: _ % 61**4
Out[2]: 0
A new standard for this is the Resize Observer api, available in Chrome 64.
function outputsize() {_x000D_
width.value = textbox.offsetWidth_x000D_
height.value = textbox.offsetHeight_x000D_
}_x000D_
outputsize()_x000D_
_x000D_
new ResizeObserver(outputsize).observe(textbox)
_x000D_
Width: <output id="width">0</output><br>_x000D_
Height: <output id="height">0</output><br>_x000D_
<textarea id="textbox">Resize me</textarea><br>
_x000D_
Spec: https://wicg.github.io/ResizeObserver
Polyfills: https://github.com/WICG/ResizeObserver/issues/3
Firefox Issue: https://bugzil.la/1272409
Safari Issue: http://wkb.ug/157743
Current Support: http://caniuse.com/#feat=resizeobserver
you are doing it wrong, you have first split the string using space as a delimiter using String.split() and populate the char array with charcters.
or even simpler just use String.charAt()
in the loop to populate array like below:
String ini="Hi there";
char[] array=new char[ini.length()];
for(int count=0;count<array.length;count++){
array[count] = ini.charAt(count);
System.out.print(" "+array[count]);
}
or one liner would be
String ini="Hi there";
char[] array=ini.toCharArray();
Replace @RestController
with @Controller
.
It looks like in the ECMAScript 6 proposal there are the Array
methods find()
and findIndex()
. MDN also offers polyfills which you can include to get the functionality of these across all browsers.
function isPrime(element, index, array) {
var start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) return false;
}
return (element > 1);
}
console.log( [4, 6, 8, 12].find(isPrime) ); // undefined, not found
console.log( [4, 5, 8, 12].find(isPrime) ); // 5
function isPrime(element, index, array) {
var start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) return false;
}
return (element > 1);
}
console.log( [4, 6, 8, 12].findIndex(isPrime) ); // -1, not found
console.log( [4, 6, 7, 12].findIndex(isPrime) ); // 2
You could also speed things up with a while
loop (see here: http://jsperf.com/javascript-while-vs-for-loops). Also much more terse and legible IMHO:
i = 10
while(i--)
//- iterate here
div= i
I got the same error. In my case I had multiple div with same id in a page. I renamed the another id of the div used and fixed the issue.
So confirm whether the element:
Only one proposed solution keeps the default-value
when some-value:null
was set explicitly (POJO readability is lost there and it's clumsy)
Here's how one can keep the default-value
and never set it to null
@JsonProperty("some-value")
public String someValue = "default-value";
@JsonSetter("some-value")
public void setSomeValue(String s) {
if (s != null) {
someValue = s;
}
}
From the docs (note: MSDN is a handy resource when you want to know what things do!):
Use the ExecuteScalar method to retrieve a single value (for example, an aggregate value) from a database. This requires less code than using the ExecuteReader method, and then performing the operations that you need to generate the single value using the data returned by a SqlDataReader.
Sends the CommandText to the Connection and builds a SqlDataReader.
... and from SqlDataReader ...
Provides a way of reading a forward-only stream of rows from a SQL Server database. This class cannot be inherited.
You can use the ExecuteNonQuery to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database without using a DataSet by executing UPDATE, INSERT, or DELETE statements.
Maybe more simple;
var top = window.pageYOffset || document.documentElement.scrollTop,
left = window.pageXOffset || document.documentElement.scrollLeft;
Credits: so.dom.js#L492
I had the same issue when trying to select the correct item in a spinner populated using a cursorLoader. I retrieved the id of the item I wanted to select first from table 1 and then used a CursorLoader to populate the spinner. In the onLoadFinished I cycled through the cursor populating the spinner's adapter until I found the item that matched the id I already had. Then assigned the row number of the cursor to the spinner's selected position. It would be nice to have a similar function to pass in the id of the value you wish to select in the spinner when populating details on a form containing saved spinner results.
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
adapter.swapCursor(cursor);
cursor.moveToFirst();
int row_count = 0;
int spinner_row = 0;
while (spinner_row < 0 || row_count < cursor.getCount()){ // loop until end of cursor or the
// ID is found
int cursorItemID = bCursor.getInt(cursor.getColumnIndexOrThrow(someTable.COLUMN_ID));
if (knownID==cursorItemID){
spinner_row = row_count; //set the spinner row value to the same value as the cursor row
}
cursor.moveToNext();
row_count++;
}
}
spinner.setSelection(spinner_row ); //set the selected item in the spinner
}
To search the commit log (across all branches) for the given text:
git log --all --grep='Build 0051'
To search the actual content of commits through a repo's history, use:
git grep 'Build 0051' $(git rev-list --all)
to show all instances of the given text, the containing file name, and the commit sha1.
Finally, as a last resort in case your commit is dangling and not connected to history at all, you can search the reflog itself with the -g
flag (short for --walk-reflogs
:
git log -g --grep='Build 0051'
EDIT: if you seem to have lost your history, check the reflog
as your safety net. Look for Build 0051 in one of the commits listed by
git reflog
You may have simply set your HEAD
to a part of history in which the 'Build 0051' commit is not visible, or you may have actually blown it away. The git-ready reflog article may be of help.
To recover your commit from the reflog: do a git checkout of the commit you found (and optionally make a new branch or tag of it for reference)
git checkout 77b1f718d19e5cf46e2fab8405a9a0859c9c2889
# alternative, using reflog (see git-ready link provided)
# git checkout HEAD@{10}
git checkout -b build_0051 # make a new branch with the build_0051 as the tip
You can stash
(save the changes in temporary box) then, back to master
branch HEAD.
$ git add .
$ git stash
$ git checkout master
Jump Over Commits Back and Forth:
Go to a specific commit-sha
.
$ git checkout <commit-sha>
If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.
# checkout a new branch, add, commit, push
$ git checkout -b <branch-name>
$ git add .
$ git commit -m 'Commit message'
$ git push origin HEAD # push the current branch to remote
$ git checkout master # back to master branch now
If you have changes in the specific commit and don't want to keep the changes, you can do stash
or reset
then checkout to master
(or, any other branch).
# stash
$ git add -A
$ git stash
$ git checkout master
# reset
$ git reset --hard HEAD
$ git checkout master
After checking out a specific commit if you have no uncommitted change(s) then, just back to master
or other
branch.
$ git status # see the changes
$ git checkout master
# or, shortcut
$ git checkout - # back to the previous state
I think this should do it..
Select
ProductName,
WeekNumber,
sum(sale)
from
(
SELECT
ProductName,
DATEDIFF(week, '2011-05-30', date) AS WeekNumber,
sale
FROM table
)
GROUP BY
ProductName,
WeekNumber
I have a similar problem, and I remove the RuntimeFrameworkVersion, and the problem was fixed.
Try to remove 1.1.1 or
Those who are using VS2012
Goto project > Properties > Web
Check Use Local IIS Web server
Check Use IIS Express
Project Url http://localhost:PORT/
Run this command line on your preferred shell session:
db2 "select tabname from syscat.tables where owner = 'DB2INST1'"
Maybe you'd like to modify the owner name, and need to check the list of current owners?
db2 "select distinct owner from syscat.tables"
Anybody facing problemn while creating jniLibs cpp is shown ..just add ndk ..
You can convert the list to a set. A set cannot have duplicates. So if all the elements in the original list are identical, the set will have just one element.
if len(set(input_list)) == 1:
# input_list has all identical elements.
In order to delete a cookie set the expires
date to something in the past. A function that does this would be.
var delete_cookie = function(name) {
document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
};
Then to delete a cookie named roundcube_sessauth
just do.
delete_cookie('roundcube_sessauth');
I just do it like this:
CvCapture *capture = cvCreateFileCapture("rtsp://camera-address");
Also make sure this dll is available at runtime else cvCreateFileCapture will return NULL
opencv_ffmpeg200d.dll
The camera needs to allow unauthenticated access too, usually set via its web interface. MJPEG format worked via rtsp but MPEG4 didn't.
hth
Si
The best practice is to use a style sheet specifically for printing, and and set its media
attribute to print
.
In it, show/hide the elements that you want to be printed on paper.
<link rel="stylesheet" type="text/css" href="print.css" media="print" />
You could use a Polygon Clipping algorithm to find the intersection between two polygons. However these tend to be complicated algorithms when all of the edge cases are taken into account.
One implementation of polygon clipping that you can use your favorite search engine to look for is Weiler-Atherton. wikipedia article on Weiler-Atherton
Alan Murta has a complete implementation of a polygon clipper GPC.
Edit:
Another approach is to first divide each polygon into a set of triangles, which are easier to deal with. The Two-Ears Theorem by Gary H. Meisters does the trick. This page at McGill does a good job of explaining triangle subdivision.
You can simply use ORS dynamically like this:
awk '{ORS="" ; print($1" "$2" "$3" "$4" "$5" "); ORS="\n"; print($6-=2*$6)}' file_in > file_out
I tried the program below and saw different string each time
package main
import (
"fmt"
"math/rand"
"time"
)
func RandomString(count int){
rand.Seed(time.Now().UTC().UnixNano())
for(count > 0 ){
x := Random(65,91)
fmt.Printf("%c",x)
count--;
}
}
func Random(min, max int) (int){
return min+rand.Intn(max-min)
}
func main() {
RandomString(12)
}
And the output on my console is
D:\james\work\gox>go run rand.go
JFBYKAPEBCRC
D:\james\work\gox>go run rand.go
VDUEBIIDFQIB
D:\james\work\gox>go run rand.go
VJYDQPVGRPXM
Version 3.6+: Use a formatted string literal, f-string for short
print(f"{i}. {key} appears {wordBank[key]} times.")
with loss tolerant
Do you mean "with loss tolerance" ?
Basically, UDP is not "loss tolerant". You can send 100 packets to someone, and they might only get 95 of those packets, and some might be in the wrong order.
For things like video streaming, and multiplayer gaming, where it is better to miss a packet than to delay all the other packets behind it, this is the obvious choice
For most other things though, a missing or 'rearranged' packet is critical. You'd have to write some extra code to run on top of UDP to retry if things got missed, and enforce correct order. This would add a small bit of overhead in certain places.
Thankfully, some very very smart people have done this, and they called it TCP.
Think of it this way: If a packet goes missing, would you rather just get the next packet as quickly as possible and continue (use UDP), or do you actually need that missing data (use TCP). The overhead won't matter unless you're in a really edge-case scenario.
You must be in the same directory of Gemfile
Trailing whitespace:
It is extra spaces (and tabs) at the end of line
^^^^^ here
Strip them:
#!/usr/bin/env python2
"""\
strip trailing whitespace from file
usage: stripspace.py <file>
"""
import sys
if len(sys.argv[1:]) != 1:
sys.exit(__doc__)
content = ''
outsize = 0
inp = outp = sys.argv[1]
with open(inp, 'rb') as infile:
content = infile.read()
with open(outp, 'wb') as output:
for line in content.splitlines():
newline = line.rstrip(" \t")
outsize += len(newline) + 1
output.write(newline + '\n')
print("Done. Stripped %s bytes." % (len(content)-outsize))
Edit
It has been pointed out that there exists (at least as of 3.0) a pure Spring MVC mechanism by which one could get this data. I will not detail it here, as it is the answer of another user. See @AdamGent's answer for details, and don't forget to upvote it.
In the Spring 3.2 documentation this mechanism is mentioned on both the RequestMapping
JavaDoc page and the RequestParam
JavaDoc page, but prior, it is only mentioned in the RequestMapping
page. In 2.5 documentation there is no mention of this mechanism.
This is likely the preferred approach for most developers as it removes (at least this) binding to the HttpServletRequest
object defined by the servlet-api jar.
/Edit
You should have access to the requests query string via request.getQueryString()
.
In addition to getQueryString, the query parameters can also be retrieved from request.getParameterMap() as a Map.
Take a look at rogerdudler/eclipse-ui-themes . In the readme there is a link to a file that you need to extract into your eclipse/dropins
folder.
When you have done that go to
Window -> Preferences -> General -> Appearance
And change the theme from GTK (or what ever it is currently) to Dark Juno
(or Dark).
That will change the UI to a nice dark theme but to get the complete look and feel you can get the Eclipse Color Theme plugin from eclipsecolorthemes.org. The easiest way is to add this update URI to "Help -> Install New Software" and install it from there.
This adds a "Color Theme" menu item under
Window -> Preferences -> Appearance
Where you can select from a large range of editor themes. My preferred one to use with PyDev is Wombat. For Java Solarized Dark
This will increase any date by exactly one
String untildate="2011-10-08";//can take any date in current format
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
Calendar cal = Calendar.getInstance();
cal.setTime( dateFormat.parse(untildate));
cal.add( Calendar.DATE, 1 );
String convertedDate=dateFormat.format(cal.getTime());
System.out.println("Date increase by one.."+convertedDate);
The dat file has some lines of extra information before the actual data. Skip them with the skip
argument:
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)
An easy way to check this if you are unfamiliar with the dataset is to first use readLines
to check a few lines, as below:
readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
n=10)
# [1] "Ozone data from CZ03 2009" "Local time: GMT + 0"
# [3] "" "Date Hour Value"
# [5] "01.01.2009 00:00 34.3" "01.01.2009 01:00 31.9"
# [7] "01.01.2009 02:00 29.9" "01.01.2009 03:00 28.5"
# [9] "01.01.2009 04:00 32.9" "01.01.2009 05:00 20.5"
Here, we can see that the actual data starts at [4]
, so we know to skip the first three lines.
If you really only wanted the Value
column, you could do that by:
as.vector(
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)$Value)
Again, readLines
is useful for helping us figure out the actual name of the columns we will be importing.
But I don't see much advantage to doing that over reading the whole dataset in and extracting later.
Use this:
replace series of newlines with an empty string:
$string = preg_replace("/[\\n\\r]+/", "", $string);
or you probably want to replace newlines with a single space:
$string = preg_replace("/[\\n\\r]+/", " ", $string);
Make sure you are using volumes for all the persistent data (configuration, logs, or application data) which you store on the containers related to the state of the processes inside that container. Update your Dockerfile and rebuild the image with the changes you wanted, and restart the containers with your volumes mounted at their appropriate place.
Have you tried simply opening them in OpenOffice.org?
I had a similar problem some time ago and found that Excel and Calc didn't understand each other's encryption, and so allowed direct access to just about everything.
This was a while ago, so if that wasn't just a fluke on my part it also may have been patched.
That's exactly how you use it. There is a possibility that the address you have does not correspond to something directly in your source code though.
For example:
$ cat t.c
#include <stdio.h>
int main()
{
printf("hello\n");
return 0;
}
$ gcc -g t.c
$ addr2line -e a.out 0x400534
/tmp/t.c:3
$ addr2line -e a.out 0x400550
??:0
0x400534
is the address of main
in my case. 0x400408
is also a valid function address in a.out
, but it's a piece of code generated/imported by GCC, that has no debug info. (In this case, __libc_csu_init
. You can see the layout of your executable with readelf -a your_exe
.)
Other times when addr2line
will fail is if you're including a library that has no debug information.
it looks like this is the way to do! as simple as that
with this line you are joining together the all text parts within the current element
''.join(htmlelement.find(text=True))
While I agree with the other answers regarding the RoleManager, I would advice to examine the possibility to implement Authorization through Claims (Expressing Roles as Claims).
Starting with the .NET Framework 4.5, Windows Identity Foundation (WIF) has been fully integrated into the .NET Framework.
In claims-aware applications, the role is expressed by a role claim type that should be available in the token. When the IsInRole() method is called, there is a check made to see if the current user has that role.
The role claim type is expressed using the following URI: "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
So instead of using the RoleManager, you can "add a user to a role" from the UserManager, doing something like this:
var um = new UserManager();
um.AddClaimAsync(1, new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", "administrator"));
With the above lines you have added a role claim with the value "administrator" to the user with the id "1"...
Claims authorization, as suggested by MSFT, can simplify and increase the performance of authentication and authorization processes eliminating some back-end queries every time authorization takes place.
Using Claims you may not need the RoleStore anymore. (AspNetRoles, AspNetUserRoles)
The problem with your code is in your loop in Check_Circular. You are advancing through the list using n1 by going one node at a time. By reassigning n2 to n2.next.next you are advancing through it two at a time.
When you do that, n2.next.next may be null, so n2 will be null after the assignment. When the loop repeats and it checks if n2.next is not null, it throws the NPE because it can't get to next since n2 is already null.
You want to do something like what Alex posted instead.
ListView myListView = (ListView) rootView.findViewById(R.id.myListView);
ArrayList<String> myStringArray1 = new ArrayList<String>();
myStringArray1.add("something");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);
Try it like this
public OnClickListener moreListener = new OnClickListener() {
@Override
public void onClick(View v) {
adapter = null;
myStringArray1.add("Andrea");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
};
To get a list of all model classes, you can use ActiveRecord::Base.subclasses
e.g.
ActiveRecord::Base.subclasses.map { |cl| cl.name }
ActiveRecord::Base.subclasses.find { |cl| cl.name == "Foo" }
I just added "-?" parameter. It makes Psexec copy executable to remote machine. So it works without access errors.
You're talking about template literals.
They allow for both multiline strings and string interpolation.
Multiline strings:
console.log(`foo_x000D_
bar`);_x000D_
// foo_x000D_
// bar
_x000D_
String interpolation:
var foo = 'bar';_x000D_
console.log(`Let's meet at the ${foo}`);_x000D_
// Let's meet at the bar
_x000D_
You can access any LayoutParams
from code using View.getLayoutParams
. You just have to be very aware of what LayoutParams
your accessing. This is normally achieved by checking the containing ViewGroup
if it has a LayoutParams
inner child then that's the one you should use. In your case it's RelativeLayout.LayoutParams
. You'll be using RelativeLayout.LayoutParams#addRule(int verb)
and RelativeLayout.LayoutParams#addRule(int verb, int anchor)
You can get to it via code:
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)button.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.LEFT_OF, R.id.id_to_be_left_of);
button.setLayoutParams(params); //causes layout update
more generally, this could also look like this:
import multiprocessing
def chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
numberOfThreads = 4
if __name__ == '__main__':
jobs = []
for i, param in enumerate(params):
p = multiprocessing.Process(target=f, args=(i,param))
jobs.append(p)
for i in chunks(jobs,numberOfThreads):
for j in i:
j.start()
for j in i:
j.join()
Of course, that way is quite cruel (since it waits for every process in a junk until it continues with the next chunk). Still it works well for approx equal run times of the function calls.
In Java, an initializer with the declaration means the field is always initialized the same way, regardless of which constructor is used (if you have more than one) or the parameters of your constructors (if they have arguments), although a constructor might subsequently change the value (if it is not final). So using an initializer with a declaration suggests to a reader that the initialized value is the value that the field has in all cases, regardless of which constructor is used and regardless of the parameters passed to any constructor. Therefore use an initializer with the declaration only if, and always if, the value for all constructed objects is the same.
>>> import time
>>> print(time.strftime('%a %H:%M:%S'))
Mon 06:23:14
I know this is and oldie but i had this issue recently with the latest versions of Tomcat and Eclipse on Windows 10.
It was a permissions issue. All i had to do was navigate to the Tomcat install directory and open the folder. I was prompted to access the folder as an Administrator.
After this the versions were recognised by Eclipse and I could add the new runtime.
The simplest method is to run your program (unmodified) in Cygwin console.
The second simplest method is to run you program (also unmodified) in the ordinary Windows console, pipelining its output through tee.exe (from Cygwin or Git distribution). Tee.exe will recognize the escape codes and call appropriate WinAPI functions.
Something like:
java MyClass | tee.exe log.txt
java MyClass | tee.exe /dev/null
SELECT p.MEMBSHIP_ID
FROM user_payments as p
WHERE USER_ID = 1 AND PAYM_DATE = (
SELECT MAX(p2.PAYM_DATE)
FROM user_payments as p2
WHERE p2.USER_ID = p.USER_ID
)
I believe that codex.wordpress.org is your best reference to handle this task very well depends on your needs
check out these two pages on WordPress Codex:
If anyone is facing this issue in Mysql there is no need to change varchar to nvarchar you can just change the collation of the column to utf8
Update the child to have the attribute 'key' equal to the name. The component will re-render every time the key changes.
Child {
render() {
return <div key={this.props.bar}>{this.props.bar}</div>
}
}
The select box arrow is a native ui element, it depends on the desktop theme or the web browser. Use a jQuery plugin (e.g. Select2, Chosen) or CSS.
By adding and tuning some configuration options listed in the API documentation, you can create a lot of different styles. For instance, here is a version that removes most of the extra blank space by setting the chartArea.width
to 100% and chartArea.height
to 80% and moving the legend.position
to bottom:
// Set chart options
var options = {'title': 'How Much Pizza I Ate Last Night',
'width': 350,
'height': 400,
'chartArea': {'width': '100%', 'height': '80%'},
'legend': {'position': 'bottom'}
};
If you want to tune it more, try changing these values or using other properties from the link above.
The regex you're looking for is ^[A-Za-z.\s_-]+$
^
asserts that the regular expression must match at the beginning of the subject[]
is a character class - any character that matches inside this expression is allowedA-Z
allows a range of uppercase charactersa-z
allows a range of lowercase characters.
matches a period
rather than a range of characters\s
matches whitespace (spaces and tabs)_
matches an underscore-
matches a dash (hyphen); we have it as the last character in the character class so it doesn't get interpreted as being part of a character range. We could also escape it (\-
) instead and put it anywhere in the character class, but that's less clear+
asserts that the preceding expression (in our case, the character class) must match one or more times$
Finally, this asserts that we're now at the end of the subjectWhen you're testing regular expressions, you'll likely find a tool like regexpal helpful. This allows you to see your regular expression match (or fail to match) your sample data in real time as you write it.
this can be solved under MacOS X by installing pyqt with brew
brew install pyqt
Simply use
<span onClick={() => this.props.history.goBack()}>Back</span>
this way is a bit more flexible than using all()
:
my_list = [[1, 2, 0], [1, 2, 0], [1, 2, 0]]
all_zeros = False if False in [x[2] == 0 for x in my_list] else True
any_zeros = True if True in [x[2] == 0 for x in my_list] else False
or more succinctly:
all_zeros = not False in [x[2] == 0 for x in my_list]
any_zeros = 0 in [x[2] for x in my_list]
Usually you can plug a Query's result (which is basically a table) as the FROM clause source of another query, so something like this will be written:
SELECT COUNT(*), SUM(SUBQUERY.AGE) from
(
SELECT availables.bookdate AS Date, DATEDIFF(now(),availables.updated_at) as Age
FROM availables
INNER JOIN rooms
ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
GROUP BY availables.bookdate
) AS SUBQUERY
I guess the issue here is that you are updating INV_DISCOUNT and the INV_TOTAL uses the INV_DISCOUNT. so that is the issue here. You can use returning clause of update statement to use the new INV_DISCOUNT and use it to update INV_TOTAL.
this is a generic example let me know if this explains the point i mentioned
CREATE OR REPLACE PROCEDURE SingleRowUpdateReturn
IS
empName VARCHAR2(50);
empSalary NUMBER(7,2);
BEGIN
UPDATE emp
SET sal = sal + 1000
WHERE empno = 7499
RETURNING ename, sal
INTO empName, empSalary;
DBMS_OUTPUT.put_line('Name of Employee: ' || empName);
DBMS_OUTPUT.put_line('New Salary: ' || empSalary);
END;
Messa's answer only works if the server isn't bothering to check the content-type header. You'll need to specify a content-type header if you want it to really work. Here's Messa's answer modified to include a content-type header:
import json
import urllib2
data = json.dumps([1, 2, 3])
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
response = f.read()
f.close()
For anyone who is looking a way to watch a specific file to exist in VBS:
Function bIsFileDownloaded(strPath, timeout)
Dim FSO, fileIsDownloaded
set FSO = CreateObject("Scripting.FileSystemObject")
fileIsDownloaded = false
limit = DateAdd("s", timeout, Now)
Do While Now < limit
If FSO.FileExists(strPath) Then : fileIsDownloaded = True : Exit Do : End If
WScript.Sleep 1000
Loop
Set FSO = Nothing
bIsFileDownloaded = fileIsDownloaded
End Function
Usage:
FileName = "C:\test.txt"
fileIsDownloaded = bIsFileDownloaded(FileName, 5) ' keep watching for 5 seconds
If fileIsDownloaded Then
WScript.Echo Now & " File is Downloaded: " & FileName
Else
WScript.Echo Now & " Timeout, file not found: " & FileName
End If
I found this trick out recently. Whack an @ at the start of a line that may produce an warning/error.
As if by magic, they dissapear.
declare @MyNumber int
set @MyNumber = 123
select 'My number is ' + CAST(@MyNumber as nvarchar(20))
Here is another python code to check whether closed segments intersect. It is the rewritten version of the C++ code in http://www.cdn.geeksforgeeks.org/check-if-two-given-line-segments-intersect/. This implementation covers all special cases (e.g. all points colinear).
def on_segment(p, q, r):
'''Given three colinear points p, q, r, the function checks if
point q lies on line segment "pr"
'''
if (q[0] <= max(p[0], r[0]) and q[0] >= min(p[0], r[0]) and
q[1] <= max(p[1], r[1]) and q[1] >= min(p[1], r[1])):
return True
return False
def orientation(p, q, r):
'''Find orientation of ordered triplet (p, q, r).
The function returns following values
0 --> p, q and r are colinear
1 --> Clockwise
2 --> Counterclockwise
'''
val = ((q[1] - p[1]) * (r[0] - q[0]) -
(q[0] - p[0]) * (r[1] - q[1]))
if val == 0:
return 0 # colinear
elif val > 0:
return 1 # clockwise
else:
return 2 # counter-clockwise
def do_intersect(p1, q1, p2, q2):
'''Main function to check whether the closed line segments p1 - q1 and p2
- q2 intersect'''
o1 = orientation(p1, q1, p2)
o2 = orientation(p1, q1, q2)
o3 = orientation(p2, q2, p1)
o4 = orientation(p2, q2, q1)
# General case
if (o1 != o2 and o3 != o4):
return True
# Special Cases
# p1, q1 and p2 are colinear and p2 lies on segment p1q1
if (o1 == 0 and on_segment(p1, p2, q1)):
return True
# p1, q1 and p2 are colinear and q2 lies on segment p1q1
if (o2 == 0 and on_segment(p1, q2, q1)):
return True
# p2, q2 and p1 are colinear and p1 lies on segment p2q2
if (o3 == 0 and on_segment(p2, p1, q2)):
return True
# p2, q2 and q1 are colinear and q1 lies on segment p2q2
if (o4 == 0 and on_segment(p2, q1, q2)):
return True
return False # Doesn't fall in any of the above cases
Below is a test function to verify that it works.
import matplotlib.pyplot as plt
def test_intersect_func():
p1 = (1, 1)
q1 = (10, 1)
p2 = (1, 2)
q2 = (10, 2)
fig, ax = plt.subplots()
ax.plot([p1[0], q1[0]], [p1[1], q1[1]], 'x-')
ax.plot([p2[0], q2[0]], [p2[1], q2[1]], 'x-')
print(do_intersect(p1, q1, p2, q2))
p1 = (10, 0)
q1 = (0, 10)
p2 = (0, 0)
q2 = (10, 10)
fig, ax = plt.subplots()
ax.plot([p1[0], q1[0]], [p1[1], q1[1]], 'x-')
ax.plot([p2[0], q2[0]], [p2[1], q2[1]], 'x-')
print(do_intersect(p1, q1, p2, q2))
p1 = (-5, -5)
q1 = (0, 0)
p2 = (1, 1)
q2 = (10, 10)
fig, ax = plt.subplots()
ax.plot([p1[0], q1[0]], [p1[1], q1[1]], 'x-')
ax.plot([p2[0], q2[0]], [p2[1], q2[1]], 'x-')
print(do_intersect(p1, q1, p2, q2))
p1 = (0, 0)
q1 = (1, 1)
p2 = (1, 1)
q2 = (10, 10)
fig, ax = plt.subplots()
ax.plot([p1[0], q1[0]], [p1[1], q1[1]], 'x-')
ax.plot([p2[0], q2[0]], [p2[1], q2[1]], 'x-')
print(do_intersect(p1, q1, p2, q2))
You could use pandas plot as @Bharath suggest:
import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)
Output:
Updated:
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Updated Pandas 0.21.0+ reindex_axis
is deprecated, use reindex
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Output:
Try This
Write code in your service
import {Observable, of} from 'rxjs';
import json file
import Product from "./database/product.json";
getProduct(): Observable<any> {
return of(Product).pipe(delay(1000));
}
In component
get_products(){
this.sharedService.getProduct().subscribe(res=>{
console.log(res);
})
}
No Go doesn't have a ternary operator, using if/else syntax is the idiomatic way.
Why does Go not have the ?: operator?
There is no ternary testing operation in Go. You may use the following to achieve the same result:
if expr { n = trueVal } else { n = falseVal }
The reason
?:
is absent from Go is that the language's designers had seen the operation used too often to create impenetrably complex expressions. Theif-else
form, although longer, is unquestionably clearer. A language needs only one conditional control flow construct.— Frequently Asked Questions (FAQ) - The Go Programming Language
Might be a little late with the answer but you need to supply the MIME type attribute in the video tag: type="application/x-mpegURL". The video tag I use for a 16:9 stream looks like this.
<video width="352" height="198" controls>
<source src="playlist.m3u8" type="application/x-mpegURL">
</video>
Arrays have numerical indexes. So,
a = new Array();
a['a1']='foo';
a['a2']='bar';
and
b = new Array(2);
b['b1']='foo';
b['b2']='bar';
are not adding elements to the array, but adding .a1
and .a2
properties to the a
object (arrays are objects too). As further evidence, if you did this:
a = new Array();
a['a1']='foo';
a['a2']='bar';
console.log(a.length); // outputs zero because there are no items in the array
Your third option:
c=['c1','c2','c3'];
is assigning the variable c
an array with three elements. Those three elements can be accessed as: c[0]
, c[1]
and c[2]
. In other words, c[0] === 'c1'
and c.length === 3
.
Javascript does not use its array functionality for what other languages call associative arrays where you can use any type of key in the array. You can implement most of the functionality of an associative array by just using an object in javascript where each item is just a property like this.
a = {};
a['a1']='foo';
a['a2']='bar';
It is generally a mistake to use an array for this purpose as it just confuses people reading your code and leads to false assumptions about how the code works.
If you migrate Visual Studio 2012 to 2013, then open *.csproj project file with edior.
and check 'Project' tag's ToolsVersion element.
Change its value from 4.0 to 12.0
From
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" ...
To
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="12.0" ...
Or If you build with msbuild then just specify VisualStudioVersion property
msbuild /p:VisualStudioVersion=12.0
Try escaping the slash: someString.replace(/\//g, "-");
By the way - /
is a (forward-)slash; \
is a backslash.
Set the containing element/div to a height. Otherwise your asking the browser to set the height to 100% of an unknown value and it can't.
More info here: http://webdesign.about.com/od/csstutorials/f/set-css-height-100-percent.htm
Sometime @AMissico answer is not enough. In my case, I couldn't find the error in the Output windows so I decided to create a log file and analyze it, by doing the following steps:
Saving the build log to a file... https://msdn.microsoft.com/en-us/library/ms171470.aspx
msbuild MyProject.proj /fl /flp:logfile=MyProjectOutput.log;verbosity=detailed
Find the text: warning MS...
or the specific warning info: (e.g. line 9293) Found conflicts between different versions...
and the full detail of the conflict error will be above of this message (e.g. line 9277) There was a conflicts between...
Visual Studio 2013
Yes of course, function are objects and can be passed, but of course you must declare it:
function firstFunction(){
//some code
var callbackfunction = function(data){
//do something with the data returned from the ajax request
}
//a callback function is written for $.post() to execute
secondFunction("var1","var2",callbackfunction);
}
an interesting thing is that your callback function has also access to every variable you might have declared inside firstFunction() (variables in javascript have local scope).
I experienced the same error while using Windows 7 x64, Eclipse, and JDK 1.6.0_30. In the JDK installation folder there is a jre
folder. This threw me off at first as I was adding the aforementioned jars to the JDK's lib/security folder with no luck. Full path:
C:\Program Files\Java\jdk1.6.0_30\jre\lib\security
Download and extract the files contained in the jce
folder of this archive into that folder.
no >
is a child selector.
the one you want is +
so try h1.hc-reform + p
browser support isn't great
With Eloquent it is easy to create multiple where check:
First: (Use simple where)
$users = User::where('name', $request['name'])
->where('surname', $request['surname'])
->where('address', $request['address'])
...
->get();
Second: (Group your where inside an array)
$users = User::where([
['name', $request['name']],
['surname', $request['surname']],
['address', $request['address']],
...
])->get();
You can also use conditional (=, <>, etc.) inside where like this:
$users = User::where('name', '=', $request['name'])
->where('surname', '=', $request['surname'])
->where('address', '<>', $request['address'])
...
->get();
if you do not have any database in your application simply disable the auto-config of datasource by adding below annotation.
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
There is a sum() method in underscore-java library.
Code example:
import com.github.underscore.lodash.U;
public class Main {
public static void main(String[] args) {
int sum = U.sum(java.util.Arrays.asList(1, 2, 3, 4));
System.out.println(sum);
// -> 10
}
}
Is a completely different (but still free) application an option? I use HxD, and it serves me better than the Notepad++ plugin. It can calculate hashes, open memory of a process, it is fast at opening files of any size, and it works exceptionally well with the clipboard.
I used to use the Notepad++ plugin, but not anymore.
The essential idea here is to select the data you want to sum, and then sum them. This selection of data can be done in several different ways, a few of which are shown below.
Arguably the most common way to select the values is to use Boolean indexing.
With this method, you find out where column 'a' is equal to 1
and then sum the corresponding rows of column 'b'. You can use loc
to handle the indexing of rows and columns:
>>> df.loc[df['a'] == 1, 'b'].sum()
15
The Boolean indexing can be extended to other columns. For example if df
also contained a column 'c' and we wanted to sum the rows in 'b' where 'a' was 1 and 'c' was 2, we'd write:
df.loc[(df['a'] == 1) & (df['c'] == 2), 'b'].sum()
Another way to select the data is to use query
to filter the rows you're interested in, select column 'b' and then sum:
>>> df.query("a == 1")['b'].sum()
15
Again, the method can be extended to make more complicated selections of the data:
df.query("a == 1 and c == 2")['b'].sum()
Note this is a little more concise than the Boolean indexing approach.
The alternative approach is to use groupby
to split the DataFrame into parts according to the value in column 'a'. You can then sum each part and pull out the value that the 1s added up to:
>>> df.groupby('a')['b'].sum()[1]
15
This approach is likely to be slower than using Boolean indexing, but it is useful if you want check the sums for other values in column a
:
>>> df.groupby('a')['b'].sum()
a
1 15
2 8
string result = arr.Aggregate("", (s, i) => s + i.ToString());
(Disclaimer: If you have a lot of digits (hundreds, at least) and you care about performance, I suggest eschewing this method and using a StringBuilder
, as in JaredPar's answer.)
There is also an option to run code directly from the CLI, not the *.ts
file itself.
It's perfectly described in the ts-node manual.
ts-node
globally via npm, yarn, or whatever you like.ts-node -e 'console.log("Hello, world!")'
(you may also add the -p
flag for printing code)This little command is perfect for checking, does everything installed fine. And for finding some other error, relevant with tsconfig.json
options.
During debugging I find it useful to put a table at the bottom of each of my pages to show all ModelState errors.
<table class="model-state">
@foreach (var item in ViewContext.ViewData.ModelState)
{
if (item.Value.Errors.Any())
{
<tr>
<td><b>@item.Key</b></td>
<td>@((item.Value == null || item.Value.Value == null) ? "<null>" : item.Value.Value.RawValue)</td>
<td>@(string.Join("; ", item.Value.Errors.Select(x => x.ErrorMessage)))</td>
</tr>
}
}
</table>
<style>
table.model-state
{
border-color: #600;
border-width: 0 0 1px 1px;
border-style: solid;
border-collapse: collapse;
font-size: .8em;
font-family: arial;
}
table.model-state td
{
border-color: #600;
border-width: 1px 1px 0 0;
border-style: solid;
margin: 0;
padding: .25em .75em;
background-color: #FFC;
}
</style>
gem cleanup
uses system commands. Installed gems are just directories in the filesystem. If you want to batch delete, use rm -R
.
gem environment
and note the value of GEM PATHS
cd <your-gem-paths>/gems
ls -1 |grep rjb- |xargs rm -R
You don't need to use a subclass of Thread
to make this work - take a look at the simple example I'm posting below to see how:
from threading import Thread
from time import sleep
def threaded_function(arg):
for i in range(arg):
print("running")
sleep(1)
if __name__ == "__main__":
thread = Thread(target = threaded_function, args = (10, ))
thread.start()
thread.join()
print("thread finished...exiting")
Here I show how to use the threading module to create a thread which invokes a normal function as its target. You can see how I can pass whatever arguments I need to it in the thread constructor.
According to the documentation the related method to android:backgroundTint
is setBackgroundTintList(ColorStateList list)
Update
Follow this link to know how create a Color State List Resource.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:color="#your_color_here" />
</selector>
then load it using
setBackgroundTintList(contextInstance.getResources().getColorStateList(R.color.your_xml_name));
where contextInstance
is an instance of a Context
using AppCompart
btnTag.setSupportButtonTintList(ContextCompat.getColorStateList(Activity.this, R.color.colorPrimary));
This class was compiled with a JDK more recent than the one used for execution.
The easiest is to install a more recent JRE on the computer where you execute the program. If you think you installed a recent one, check the JAVA_HOME and PATH environment variables.
Version 49 is java 1.5. That means the class was compiled with (or for) a JDK which is yet old. You probably tried to execute the class with JDK 1.4. You really should use one more recent (1.6 or 1.7, see java version history).
In Swift 5
var array: [String] = ["Aman", "Sumit", "Aman", "Sumit", "Mohan", "Mohan", "Amit"]
let uniq = Array(Set(array))
print(uniq)
Output Will be
["Sumit", "Mohan", "Amit", "Aman"]
One more way is::
Write a method in your adapter lets say public void callBack(){}.
Now while creating an object for adapter in activity override this method. Override method will be called when you call the method in adapter.
Myadapter adapter = new Myadapter() {
@Override
public void callBack() {
// dosomething
}
};
Try https://github.com/tmpvar/jsdom - you give it some HTML and it gives you a DOM.
Sometimes I also faced the problem of scrolling with Selenium. So I used javaScriptExecuter to achieve this.
For scrolling down:
WebDriver driver = new ChromeDriver();
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("window.scrollBy(0, 250)", "");
Or, also
js.executeScript("scroll(0, 250);");
For scrolling up:
js.executeScript("window.scrollBy(0,-250)", "");
Or,
js.executeScript("scroll(0, -250);");
You can also write to a file like this:
$logFilePath = '../logs/debug.text';
ob_start();
// if you want to concatenate:
if (file_exists($logFilePath)) {
include($logFilePath);
}
// for timestamp
$currentTime = date(DATE_RSS);
// echo log statement(s) here
echo "\n\n$currentTime - [log statement here]";
$logFile = fopen($logFilePath, 'w');
fwrite($logFile, ob_get_contents());
fclose($logFile);
ob_end_flush();
Make sure the proper permissions are set so php can access and write to the file (775
).
var x = document.getElementById("parent").querySelector("#child");
// don't forget a #
or
var x = document.querySelector("#parent").querySelector("#child");
or
var x = document.querySelector("#parent #child");
or
var x = document.querySelector("#parent");
var y = x.querySelector("#child");
eg.
var x = document.querySelector("#div1").querySelector("#edit2");
A little more than was requsted but I use the extra timer code to track and alert if CPU usage is 90% or higher for a sustained period of 1 minute or longer.
public class Form1
{
int totalHits = 0;
public object getCPUCounter()
{
PerformanceCounter cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
// will always start at 0
dynamic firstValue = cpuCounter.NextValue();
System.Threading.Thread.Sleep(1000);
// now matches task manager reading
dynamic secondValue = cpuCounter.NextValue();
return secondValue;
}
private void Timer1_Tick(Object sender, EventArgs e)
{
int cpuPercent = (int)getCPUCounter();
if (cpuPercent >= 90)
{
totalHits = totalHits + 1;
if (totalHits == 60)
{
Interaction.MsgBox("ALERT 90% usage for 1 minute");
totalHits = 0;
}
}
else
{
totalHits = 0;
}
Label1.Text = cpuPercent + " % CPU";
//Label2.Text = getRAMCounter() + " RAM Free";
Label3.Text = totalHits + " seconds over 20% usage";
}
}
This could cause for any new terminal, the agent id is different. You need to add the Private key for the agent
$ ssh-add <path to your private key>
These are utf-8 encoded characters. Use utf8_decode() to convert them to normal ISO-8859-1 characters.
I think this should point you towards the right direction:
import java.beans.*
for (PropertyDescriptor pd : Introspector.getBeanInfo(Foo.class).getPropertyDescriptors()) {
if (pd.getReadMethod() != null && !"class".equals(pd.getName()))
System.out.println(pd.getReadMethod().invoke(foo));
}
Note that you could create BeanInfo or PropertyDescriptor instances yourself, i.e. without using Introspector. However, Introspector does some caching internally which is normally a Good Thing (tm). If you're happy without a cache, you can even go for
// TODO check for non-existing readMethod
Object value = new PropertyDescriptor("name", Person.class).getReadMethod().invoke(person);
However, there are a lot of libraries that extend and simplify the java.beans API. Commons BeanUtils is a well known example. There, you'd simply do:
Object value = PropertyUtils.getProperty(person, "name");
BeanUtils comes with other handy stuff. i.e. on-the-fly value conversion (object to string, string to object) to simplify setting properties from user input.
In Windows nslookup
the command is
ls -d somedomain.com > outfile.txt
which stores the subdomain list in outfile.txt
few domains these days allow this
I think the wait/notify/notifyAll methods don't belong on the Object class as it pollutes all objects with methods that are rarely used. They make much more sense on a dedicated Lock class. So from this point of view, perhaps it's better to use a tool that is explicitly designed for the job at hand - ie ReentrantLock.
void foo<TOne, TTwo>()
where TOne : BaseOne
where TTwo : BaseTwo
More info here:
http://msdn.microsoft.com/en-us/library/d5x73970.aspx
You must use some of the C # conversion systems:
string to boolean: True to true
string str = "True";
bool mybool = System.Convert.ToBoolean(str);
boolean to string: true to True
bool mybool = true;
string str = System.Convert.ToString(mybool);
//or
string str = mybool.ToString();
bool.Parse
expects one parameter which in this case is str, even .
Convert.ToBoolean
expects one parameter.
bool.TryParse
expects two parameters, one entry (str) and one out (result).
If TryParse
is true, then the conversion was correct, otherwise an error occurred
string str = "True";
bool MyBool = bool.Parse(str);
//Or
string str = "True";
if(bool.TryParse(str, out bool result))
{
//Correct conversion
}
else
{
//Incorrect, an error has occurred
}
It's better practise, safer and more polite to detect if the process is running and tell the user to close it manually. Of course you could also add a timeout and kill the process if they've gone away...
File one:
angular.module('myApp.controllers', []);
File two:
angular.module('myApp.controllers').controller('Ctrl1', ['$scope', '$http', function($scope, $http){
}]);
File three:
angular.module('myApp.controllers').controller('Ctrl2', ['$scope', '$http', function($scope, $http){
}]);
Include in that order. I recommend 3 files so the module declaration is on its own.
As for folder structure there are many many many opinions on the subject, but these two are pretty good
Probably because you're using unsafe code.
Are you doing something with pointers or unmanaged assemblies somewhere?
Try converting the entry to a string first. As long as the database column type is a date it will be formated as a date.
self.date || self.exif_date_time_original.to_s
public static TargetClassJson downloadPaletteJson(String url) throws IOException {
if (StringUtils.isBlank(url)) {
return null;
}
String genreJson = IOUtils.toString(new URL(url).openStream());
return new Gson().fromJson(genreJson, TargetClassJson.class);
}
Mac version: $ ld -v 2, don't know how to get detailed paths. output
Library search paths:
/usr/lib
/usr/local/lib
Framework search paths:
/Library/Frameworks/
/System/Library/Frameworks/
Why don't try to use bootstrap's solutions. They are perfect if you don't want to meddle with tables and floats.
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/> <!--- This line is just linking the bootstrap thingie in the file. The real thing starts below -->_x000D_
_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col-sm-4">_x000D_
One of three columns_x000D_
</div>_x000D_
<div class="col-sm-4">_x000D_
One of three columns_x000D_
</div>_x000D_
<div class="col-sm-4">_x000D_
One of three columns_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
No meddling with complex CSS, and the best thing is that you can edit the width of the columns by changing the number. You can find more examples at https://getbootstrap.com/docs/4.0/layout/grid/
I did a kind of terminal emulator with Bootstrap
and Javascript
because I needed some dynamic to add easily new items, and I put the prompt from Javascript
.
HTML
:
<div class="panel panel-default">
<div class="panel-heading">Comandos SQL ejecutados</div>
<div class="panel-body panel-terminal-body">
<ul id="ulCommand"></ul>
</div>
</div>
Javascript
:
function addCommand(command){
//Creating the li tag
var li = document.createElement('li');
//Creating the img tag
var prompt = document.createElement('img');
//Setting the image
prompt.setAttribute('src','./lib/custom/img/terminal-prompt-white.png');
//Setting the width (like the font)
prompt.setAttribute('width','15px');
//Setting height as auto
prompt.setAttribute('height','auto');
//Adding the prompt to the list item
li.appendChild(prompt);
//Creating a span tag to add the command
//li.appendChild('el comando'); por que no es un nodo
var span = document.createElement('span');
//Adding the text to the span tag
span.innerHTML = command;
//Adding the span to the list item
li.appendChild(span);
//At the end, adding the list item to the list (ul)
document.getElementById('ulCommand').appendChild(li);
}
CSS
:
.panel-terminal-body {
background-color: #423F3F;
color: #EDEDED;
padding-left: 50px;
padding-right: 50px;
padding-top: 15px;
padding-bottom: 15px;
height: 300px;
}
.panel-terminal-body ul {
list-style: none;
}
I hope this help you.
I called ContextCompat.startForegroundService(this, intent)
to start the service then
In service onCreate
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= 26) {
String CHANNEL_ID = "my_channel_01";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("")
.setContentText("").build();
startForeground(1, notification);
}
}
You are trying to read xls
with explicit implementation poi classes for xlsx
.
G:\Selenium Jar Files\TestData\Data.xls
Either use HSSFWorkbook
and HSSFSheet
classes or make your implementation more generic by using shared interfaces, like;
Change:
XSSFWorkbook workbook = new XSSFWorkbook(file);
To:
org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(file);
And Change:
XSSFSheet sheet = workbook.getSheetAt(0);
To:
org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
as 'Praveen M P' said you can install font-awesome as a package. if you have yarn you can run:
yarn add font-awesome
If you don't have yarn do as Praveen said and do:
npm install --save font-awesome
this will add the package to your projects dependencies and install the package in your node_modules folder. in your App.js file add
import 'font-awesome/css/font-awesome.min.css'
Try this to Change content of div using jQuery.
See more @ Change content of div using jQuery
$(document).ready(function(){
$("#Textarea").keyup(function(){
// Getting the current value of textarea
var currentText = $(this).val();
// Setting the Div content
$(".output").text(currentText);
});
});
I just created a project which explain what is the difference between all subjects:
https://github.com/piecioshka/rxjs-subject-vs-behavior-vs-replay-vs-async
The location of jfxrt.jar in Oracle Java 7 is:
<JRE_HOME>/lib/jfxrt.jar
The location of jfxrt.jar in Oracle Java 8 is:
<JRE_HOME>/lib/ext/jfxrt.jar
The <JRE_HOME>
will depend on where you installed the Oracle Java and may differ between Linux distributions and installations.
jfxrt.jar is not in the Linux OpenJDK 7 (which is what you are using).
An open source package which provides JavaFX 8 for Debian based systems such as Ubuntu is available. To install this package it is necessary to install both the Debian OpenJDK 8 package and the Debian OpenJFX package. I don't run Debian, so I'm not sure where the Debian OpenJFX package installs jfxrt.jar.
Use Oracle Java 8.
With Oracle Java 8, JavaFX is both included in the JDK and is on the default classpath. This means that JavaFX classes will automatically be found both by the compiler during the build and by the runtime when your users use your application. So using Oracle Java 8 is currently the best solution to your issue.
OpenJDK for Java 8 could include JavaFX (as JavaFX for Java 8 is now open source), but it will depend on the OpenJDK package assemblers as to whether they choose to include JavaFX 8 with their distributions. I hope they do, as it should help remove the confusion you experienced in your question and it also provides a great deal more functionality in OpenJDK.
My understanding is that although JavaFX has been included with the standard JDK since version JDK 7u6
Yes, but only the Oracle JDK.
The JavaFX version bundled with Java 7 was not completely open source so it could not be included in the OpenJDK (which is what you are using).
In you need to use Java 7 instead of Java 8, you could download the Oracle JDK for Java 7 and use that. Then JavaFX will be included with Java 7. Due to the way Oracle configured Java 7, JavaFX won't be on the classpath. If you use Java 7, you will need to add it to your classpath and use appropriate JavaFX packaging tools to allow your users to run your application. Some tools such as e(fx)clipse and NetBeans JavaFX project type will take care of classpath issues and packaging tasks for you.
Set the ReadOnly attribute to true.
Or if you want the combobox to appear and display the list of "available" values, you could handle the ValueChanged event and force it back to your immutable value.
$("body").on('change', '#location', function(e) {
var option = $('option:selected', this).attr('myTag');
});
using json.loads
:
>>> import json
>>> h = '{"foo":"bar", "foo2":"bar2"}'
>>> d = json.loads(h)
>>> d
{u'foo': u'bar', u'foo2': u'bar2'}
>>> type(d)
<type 'dict'>
I think this is the most elegant, as it also does not try to move ..
:
mv /source/path/{.[!.],}* /destination/path
If you already using jQuery simple:
<input type="file" onChange="$(this).closest('form').submit()"/>
Here's a clear picture:
Assuming we have branch-A and branch-B
We want to merge branch-B into branch-A
on branch-B -> A: switch to branch-A
on branch-A: git merge branch-B
class C:
a = 5
b = [1,2,3]
def foobar():
b = "hi"
for attr, value in C.__dict__.iteritems():
print "Attribute: " + str(attr or "")
print "Value: " + str(value or "")
Prints:
python test.py
Attribute: a
Value: 5
Attribute: foobar
Value: <function foobar at 0x7fe74f8bfc08>
Attribute: __module__
Value: __main__
Attribute: b
Value: [1, 2, 3]
Attribute: __doc__
Value:
check the @viewchild
in your .ts
@ViewChild('ngOtpInput') ngOtpInput:any;
set the below code in your method were you want the fields to be clear.
yourMethod(){
this.ngOtpInput.setValue(yourValue);
}
Inline:
<input name="number" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')">
_x000D_
Unobtrusive style (with jQuery):
$('input[name="number"]').keyup(function(e)_x000D_
{_x000D_
if (/\D/g.test(this.value))_x000D_
{_x000D_
// Filter non-digits from input value._x000D_
this.value = this.value.replace(/\D/g, '');_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input name="number">
_x000D_
You can also try to use get()
, for example:
connection = manager.connect.get("I2Cx")
which won't raise a KeyError
in case the key doesn't exist.
You may also use second argument to specify the default value, if the key is not present.
If you need to re-type this several times, you can do like I did once. Get your columns` names into rows in excel sheet (write down at the end of each column name (=) which is easy in notepad++) on the right side make a column to copy and paste your value that will correspond to the new entries at each column. Then on the right of them in an independent column put the commas as designed
Then you will have to copy your values into the middle column each time then just paste then and run
I do not know an easier solution
First off, that's not JSON. It's a JavaScript object literal. JSON is a string representation of data, that just so happens to very closely resemble JavaScript syntax.
Second, you have an object. They are unsorted. The order of the elements cannot be guaranteed. If you want guaranteed order, you need to use an array. This will require you to change your data structure.
One option might be to make your data look like this:
var json = [{
"name": "user1",
"id": 3
}, {
"name": "user2",
"id": 6
}, {
"name": "user3",
"id": 1
}];
Now you have an array of objects, and we can sort it.
json.sort(function(a, b){
return a.id - b.id;
});
The resulting array will look like:
[{
"name": "user3",
"id" : 1
}, {
"name": "user1",
"id" : 3
}, {
"name": "user2",
"id" : 6
}];
Edit: Sorry, this won't work for you. I just remembered the line color thing is in 4.2. I ran into this problem in the past and my fix was to upgrade gnuplot.
You can control the color with set style line as well. "lt 3" will give you a dashed line while "lt 1" will give you a solid line. To add color, you can use "lc rgb 'color'". This should do what you need:
set style line 1 lt 1 lw 3 pt 3 lc rgb "red"
set style line 2 lt 3 lw 3 pt 3 lc rgb "red"
set style line 3 lt 1 lw 3 pt 3 lc rgb "blue"
set style line 4 lt 3 lw 3 pt 3 lc rgb "blue"
Please try this
<?php
$json_string = 'http://www.domain.com/jsondata.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata, true);
echo "<pre>"; print_r($obj['Result']);
?>
I had the same issue, and I couldn't comment on @Sven Marnach answer (not enough rep, gosh I remember when Stackoverflow first started...) anyway.
Adding a list of random numbers to a 10 X 10 matrix.
myNpArray = np.zeros([1, 10])
for x in range(1,11,1):
randomList = [list(np.random.randint(99, size=10))]
myNpArray = np.vstack((myNpArray, randomList))
myNpArray = myNpArray[1:]
Using np.zeros() an array is created with 1 x 10 zeros.
array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])
Then a list of 10 random numbers is created using np.random and assigned to randomList. The loop stacks it 10 high. We just have to remember to remove the first empty entry.
myNpArray
array([[31., 10., 19., 78., 95., 58., 3., 47., 30., 56.],
[51., 97., 5., 80., 28., 76., 92., 50., 22., 93.],
[64., 79., 7., 12., 68., 13., 59., 96., 32., 34.],
[44., 22., 46., 56., 73., 42., 62., 4., 62., 83.],
[91., 28., 54., 69., 60., 95., 5., 13., 60., 88.],
[71., 90., 76., 53., 13., 53., 31., 3., 96., 57.],
[33., 87., 81., 7., 53., 46., 5., 8., 20., 71.],
[46., 71., 14., 66., 68., 65., 68., 32., 9., 30.],
[ 1., 35., 96., 92., 72., 52., 88., 86., 94., 88.],
[13., 36., 43., 45., 90., 17., 38., 1., 41., 33.]])
So in a function:
def array_matrix(random_range, array_size):
myNpArray = np.zeros([1, array_size])
for x in range(1, array_size + 1, 1):
randomList = [list(np.random.randint(random_range, size=array_size))]
myNpArray = np.vstack((myNpArray, randomList))
return myNpArray[1:]
a 7 x 7 array using random numbers 0 - 1000
array_matrix(1000, 7)
array([[621., 377., 931., 180., 964., 885., 723.],
[298., 382., 148., 952., 430., 333., 956.],
[398., 596., 732., 422., 656., 348., 470.],
[735., 251., 314., 182., 966., 261., 523.],
[373., 616., 389., 90., 884., 957., 826.],
[587., 963., 66., 154., 111., 529., 945.],
[950., 413., 539., 860., 634., 195., 915.]])
From the links the others have posted, I'm not seeing an option. -- I just use powershell to kill it -- you can save this to a Stop-IisExpress.ps1 file:
get-process | where { $_.ProcessName -like "IISExpress" } | stop-process
There's no harm in it -- Visual Studio will just pop a new one up when it wants one.
In ES6, you can do like this.
var key = "name";
var person = {[key]:"John"}; // same as var person = {"name" : "John"}
console.log(person); // should print Object { name="John"}
var key = "name";_x000D_
var person = {[key]:"John"};_x000D_
console.log(person); // should print Object { name="John"}
_x000D_
Its called Computed Property Names, its implemented using bracket notation( square brackets) []
Example: { [variableName] : someValue }
Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed and used as the property name.
For ES5, try something like this
var yourObject = {};
yourObject[yourKey] = "yourValue";
console.log(yourObject );
example:
var person = {};
var key = "name";
person[key] /* this is same as person.name */ = "John";
console.log(person); // should print Object { name="John"}
var person = {};_x000D_
var key = "name";_x000D_
_x000D_
person[key] /* this is same as person.name */ = "John";_x000D_
_x000D_
console.log(person); // should print Object { name="John"}
_x000D_
Take selected value:
worksheet name = ordls
form control list box name = DEPDB1
selectvalue = ordls.Shapes("DEPDB1").ControlFormat.List(ordls.Shapes("DEPDB1").ControlFormat.Value)
I tried following options to fix this issue and it worked.
For example to install express I used following command.
npm install express --registry http://registry.npmjs.org/
or
npm install express -g --registry http://registry.npmjs.org/
If you want to install locally in any specific folder then use below command. Below command will install express on path C:\Sample\Example1
.
C:\Sample1\Example1> npm install /Sample/Example1 express --registry http://registry.npmjs.org/
Note: If you are installing locally in a specific location then first go to that directory using command and then run above command. If you are not inside that directory and giving only path in command that will not work.
If you get package.json
missing error then run below command before installing package locally
C:\Sample\Example1> npm init
above command will create package.json
file. No need to provide any data. just hit enter.
Note: If you are behind a firewall then you may need to set a proxy.
If I were you, I would use BABEL: http://babel.pocoo.org/en/latest/index.html
I got the same issue here using Docker, I've tried every single step and didn't work well, always getting locale error, so I decided to use BABEL, and everything worked well.
If you want to push elements that are in a array at the beginning of you array use <func>.apply(<this>, <Array of args>)
:
const arr = [1, 2];
arr.unshift.apply(arr, [3, 4]);
console.log(arr); // [3, 4, 1, 2]
_x000D_
You don't give a reproducible example but your warning message tells you exactly what the problem is.
memb
only has a length of 10. I'm guessing the length of dih_y2$MemberID
isn't a multiple of 10. When using ==
, R spits out a warning if it isn't a multiple to let you know that it's probably not doing what you're expecting it to do. ==
does element-wise checking for equality. I suspect what you want to do is find which of the elements of dih_y2$MemberID
are also in the vector memb
. To do this you would want to use the %in%
operator.
dih_col <- which(dih_y2$MemeberID %in% memb)
I am not completely sure what you're trying to achieve by seeking to a specific offset and attempting to load individual values manually, the typical usage of the pickle
module is:
# save data to a file
with open('myfile.pickle','wb') as fout:
pickle.dump([1,2,3],fout)
# read data from a file
with open('myfile.pickle') as fin:
print pickle.load(fin)
# output
>> [1, 2, 3]
If you dumped a list, you'll load a list, there's no need to load each item individually.
you're saying that you got an error before you were seeking to the -5000 offset, maybe the file you're trying to read is corrupted.
If you have access to the original data, I suggest you try saving it to a new file and reading it as in the example.