When you read()
the file, you may get a newline character '\n'
in your string. Try either
if UserInput.strip() == 'List contents':
or
if 'List contents' in UserInput:
Also note that your second file open
could also use with
:
with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile: if UserInput.strip() == 'List contents': # or if s in f: UserInputFile.write("ls") else: print "Didn't work"
DateTime
inherits its equals
method from AbstractInstant
. It is implemented as such
public boolean equals(Object readableInstant) { // must be to fulfil ReadableInstant contract if (this == readableInstant) { return true; } if (readableInstant instanceof ReadableInstant == false) { return false; } ReadableInstant otherInstant = (ReadableInstant) readableInstant; return getMillis() == otherInstant.getMillis() && FieldUtils.equals(getChronology(), otherInstant.getChronology()); }
Notice the last line comparing chronology. It's possible your instances' chronologies are different.
About the removal of componentWillReceiveProps
: you should be able to handle its uses with a combination of getDerivedStateFromProps
and componentDidUpdate
, see the React blog post for example migrations. And yes, the object returned by getDerivedStateFromProps
updates the state similarly to an object passed to setState
.
In case you really need the old value of a prop, you can always cache it in your state with something like this:
state = {
cachedSomeProp: null
// ... rest of initial state
};
static getDerivedStateFromProps(nextProps, prevState) {
// do things with nextProps.someProp and prevState.cachedSomeProp
return {
cachedSomeProp: nextProps.someProp,
// ... other derived state properties
};
}
Anything that doesn't affect the state can be put in componentDidUpdate
, and there's even a getSnapshotBeforeUpdate
for very low-level stuff.
UPDATE: To get a feel for the new (and old) lifecycle methods, the react-lifecycle-visualizer package may be helpful.
sudo apt-get install php-pear php7.x-dev
x is your php version like 7.2 the php7.2-dev
apt-get install libmcrypt-dev libreadline-dev
pecl install mcrypt-1.0.1
then add "extension=mcrypt.so" in "/etc/php/7.2/apache2/php.ini"
here php.ini is depends on your php installatio and apache used php version.
For me it Worked after following the below steps
Step-1 Go to Devices and Simulator
Step-2 Deselect Show as run destination and Connect via network Options
Wait for Few seconds to Load the Xcode, If you want you can restart Xcode also.
Step-3 Follow the same steps and got to Devices and Simulators
Tick back both the options and it will be normal to install your app back.
Depending on where you are in the kestrel pipeline - if you have access to IConfiguration
(Startup.cs
constructor) or IWebHostEnvironment
(formerly IHostingEnvironment
) you can either inject the IWebHostEnvironment
into your constructor or just request the key from the configuration.
IWebHostEnvironment
in Startup.cs
Constructorpublic Startup(IConfiguration configuration, IWebHostEnvironment env)
{
var contentRoot = env.ContentRootPath;
}
public Startup(IConfiguration configuration)
{
var contentRoot = configuration.GetValue<string>(WebHostDefaults.ContentRootKey);
}
Go to the file location where the POM is stored and open cmd. Then type "mvn --v" to check the maven version and java runtime provided. Check runtime attribute and if it is "C:\Program Files\Java\jre1.8.0_191" or even close to a JRE, go to environment variables and add a new "system variable" called "JAVA_HOME" with a value "C:\Program Files\Java\jdk1.8.0_191".
Reopen the cmd and then "clean install" the project.
Your comparison function between old value and new value is having some issue. It is better not to complicate things so much, as it will increase your debugging effort later. You should keep it simple.
The best way is to create a person-component
and watch every person separately inside its own component, as shown below:
<person-component :person="person" v-for="person in people"></person-component>
Please find below a working example for watching inside person component. If you want to handle it on parent side, you may use $emit
to send an event upwards, containing the id
of modified person.
Vue.component('person-component', {_x000D_
props: ["person"],_x000D_
template: `_x000D_
<div class="person">_x000D_
{{person.name}}_x000D_
<input type='text' v-model='person.age'/>_x000D_
</div>`,_x000D_
watch: {_x000D_
person: {_x000D_
handler: function(newValue) {_x000D_
console.log("Person with ID:" + newValue.id + " modified")_x000D_
console.log("New age: " + newValue.age)_x000D_
},_x000D_
deep: true_x000D_
}_x000D_
}_x000D_
});_x000D_
_x000D_
new Vue({_x000D_
el: '#app',_x000D_
data: {_x000D_
people: [_x000D_
{id: 0, name: 'Bob', age: 27},_x000D_
{id: 1, name: 'Frank', age: 32},_x000D_
{id: 2, name: 'Joe', age: 38}_x000D_
]_x000D_
}_x000D_
});
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<body>_x000D_
<div id="app">_x000D_
<p>List of people:</p>_x000D_
<person-component :person="person" v-for="person in people"></person-component>_x000D_
</div>_x000D_
</body>
_x000D_
A cleaner alternative would be the following:
Due to the fact that every async function is technically a promise
You can add catches to functions when calling them with await
async function a(){
let error;
// log the error on the parent
await b().catch((err)=>console.log('b.failed'))
// change an error variable
await c().catch((err)=>{error=true; console.log(err)})
// return whatever you want
return error ? d() : null;
}
a().catch(()=>console.log('main program failed'))
No need for try catch, as all promises errors are handled, and you have no code errors, you can omit that in the parent!!
Lets say you are working with mongodb, if there is an error you might prefer to handle it in the function calling it than making wrappers, or using try catches.
Eric's answer helpfully explains that the trouble comes from comparing a Pandas Series (containing a NumPy array) to a Python string. Unfortunately, his two workarounds both just suppress the warning.
To write code that doesn't cause the warning in the first place, explicitly compare your string to each element of the Series and get a separate bool for each. For example, you could use map
and an anonymous function.
myRows = df[df['Unnamed: 5'].map( lambda x: x == 'Peter' )].index.tolist()
Date
is Comparable
& Equatable
(as of Swift 3)This answer complements @Ankit Thakur's answer.
Since Swift 3 the Date
struct (based on the underlying NSDate
class) adopts the Comparable
and Equatable
protocols.
Comparable
requires that Date
implement the operators: <
, <=
, >
, >=
.Equatable
requires that Date
implement the ==
operator.Equatable
allows Date
to use the default implementation of the !=
operator (which is the inverse of the Equatable
==
operator implementation).The following sample code exercises these comparison operators and confirms which comparisons are true with print
statements.
import Foundation
func describeComparison(date1: Date, date2: Date) -> String {
var descriptionArray: [String] = []
if date1 < date2 {
descriptionArray.append("date1 < date2")
}
if date1 <= date2 {
descriptionArray.append("date1 <= date2")
}
if date1 > date2 {
descriptionArray.append("date1 > date2")
}
if date1 >= date2 {
descriptionArray.append("date1 >= date2")
}
if date1 == date2 {
descriptionArray.append("date1 == date2")
}
if date1 != date2 {
descriptionArray.append("date1 != date2")
}
return descriptionArray.joined(separator: ", ")
}
let now = Date()
describeComparison(date1: now, date2: now.addingTimeInterval(1))
// date1 < date2, date1 <= date2, date1 != date2
describeComparison(date1: now, date2: now.addingTimeInterval(-1))
// date1 > date2, date1 >= date2, date1 != date2
describeComparison(date1: now, date2: now)
// date1 <= date2, date1 >= date2, date1 == date2
Avro is a row-based storage format for Hadoop.
Parquet is a column-based storage format for Hadoop.
If your use case typically scans or retrieves all of the fields in a row in each query, Avro is usually the best choice.
If your dataset has many columns, and your use case typically involves working with a subset of those columns rather than entire records, Parquet is optimized for that kind of work.
In case anybody wants to use the latest Version (v5.7.2)
Please find my latest version (inspired by Victors answer).
It includes all Free Icons of the "Regular"-Set: https://fontawesome.com/icons?d=gallery&s=regular&m=free
Index.html
<head>
...
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
...
</head>
CSS:
select {
font-family: 'Lato', 'Font Awesome 5 Free';
font-weight: 900;
}
HTML:
<select id="icon">
<option value="address-book"> address-book</option>
<option value="address-card"> address-card</option>
<option value="angry"> angry</option>
<option value="arrow-alt-circle-down"> arrow-alt-circle-down</option>
<option value="arrow-alt-circle-left"> arrow-alt-circle-left</option>
<option value="arrow-alt-circle-right"> arrow-alt-circle-right</option>
<option value="arrow-alt-circle-up"> arrow-alt-circle-up</option>
<option value="bell"> bell</option>
<option value="bell-slash"> bell-slash</option>
<option value="bookmark"> bookmark</option>
<option value="building"> building</option>
<option value="calendar"> calendar</option>
<option value="calendar-alt"> calendar-alt</option>
<option value="calendar-check"> calendar-check</option>
<option value="calendar-minus"> calendar-minus</option>
<option value="calendar-plus"> calendar-plus</option>
<option value="calendar-times"> calendar-times</option>
<option value="caret-square-down"> caret-square-down</option>
<option value="caret-square-left"> caret-square-left</option>
<option value="caret-square-right"> caret-square-right</option>
<option value="caret-square-up"> caret-square-up</option>
<option value="chart-bar"> chart-bar</option>
<option value="check-circle"> check-circle</option>
<option value="check-square"> check-square</option>
<option value="circle"> circle</option>
<option value="clipboard"> clipboard</option>
<option value="clock"> clock</option>
<option value="clone"> clone</option>
<option value="closed-captioning"> closed-captioning</option>
<option value="comment"> comment</option>
<option value="comment-alt"> comment-alt</option>
<option value="comment-dots"> comment-dots</option>
<option value="comments"> comments</option>
<option value="compass"> compass</option>
<option value="copy"> copy</option>
<option value="copyright"> copyright</option>
<option value="credit-card"> credit-card</option>
<option value="dizzy"> dizzy</option>
<option value="dot-circle"> dot-circle</option>
<option value="edit"> edit</option>
<option value="envelope">󴃠 envelope </option>
<option value="envelope-open"> envelope-open</option>
<option value="eye"> eye</option>
<option value="eye-slash"> eye-slash</option>
<option value="file"> file</option>
<option value="file-alt"> file-alt</option>
<option value="file-archive"> file-archive</option>
<option value="file-audio"> file-audio</option>
<option value="file-code"> file-code</option>
<option value="file-excel"> file-excel </option>
<option value="file-image"> file-image</option>
<option value="file-pdf"> file-pdf</option>
<option value="file-powerpoint"> file-powerpoint</option>
<option value="file-video"> file-video</option>
<option value="file-word"> file-word</option>
<option value="flag"> flag</option>
<option value="flushed"> flushed</option>
<option value="folder"> folder</option>
<option value="folder-open"> folder-open </option>
<option value="frown"> frown</option>
<option value="frown-open"> frown-open</option>
<option value="futbol"> futbol</option>
<option value="gem"> gem</option>
<option value="grimace"> grimace</option>
<option value="grin"> grin</option>
<option value="grin-alt"> grin-alt</option>
<option value="grin-beam"> grin-beam</option>
<option value="grin-beam-sweet"> grin-beam-sweet </option>
<option value="grin-hearts"> grin-hearts</option>
<option value="grin-squint"> grin-squint</option>
<option value="grin-squint-tears"> grin-squint-tears</option>
<option value="grin-stars"> grin-stars</option>
<option value="grin-tears"> grin-tears</option>
<option value="grin-tongue"> grin-tongue</option>
<option value="grin-tongue-squint"> grin-tongue-squint</option>
<option value="grin-tongue-wink"> grin-tongue-wink</option>
<option value="grin-wink"> grin-wink </option>
<option value="hand-lizard"> hand-lizard</option>
<option value="hand-paper"> hand-paper</option>
<option value="hand-peace"> hand-peace</option>
<option value="hand-point-down"> hand-point-down</option>
<option value="hand-point-left"> hand-point-left</option>
<option value="hand-point-right"> hand-point-right</option>
<option value="hand-point-up"> hand-point-up</option>
<option value="hand-pointer"> hand-pointer</option>
<option value="hand-rock"> hand-rock </option>
<option value="hand-scissors"> hand-scissors</option>
<option value="hand-spock"> hand-spock</option>
<option value="handshake"> handshake</option>
<option value="hdd"> hdd</option>
<option value="heart"> heart</option>
<option value="home"> home</option>
<option value="hospital"> hospital</option>
<option value="hourglass"> hourglass</option>
<option value="id-badge"> id-badge</option>
<option value="id-card"> id-card </option>
<option value="image"> image</option>
<option value="images"> images</option>
<option value="keyboard"> keyboard</option>
<option value="kiss"> kiss</option>
<option value="kiss-beam"> kiss-beam</option>
<option value="kiss-wink-heart"> kiss-wink-heart</option>
<option value="laugh"> laugh</option>
<option value="laugh-beam"> laugh-beam</option>
<option value="laugh-squint"> laugh-squint </option>
<option value="laugh-wink"> laugh-wink</option>
<option value="lemon"> lemon</option>
<option value="life-ring"> life-ring</option>
<option value="lightbulb"> lightbulb</option>
<option value="list-alt"> list-alt</option>
<option value="map"> map</option>
<option value="meh"> meh</option>
<option value="meh-blank"> meh-blank</option>
<option value="meh-rolling-eyes"> meh-rolling-eyes </option>
<option value="minus-square"> minus-square</option>
<option value="money-bill-alt"> money-bill-alt</option>
<option value="moon"> moon</option>
<option value="newspaper"> newspaper</option>
<option value="object-group"> object-group</option>
<option value="object-upgroup"> object-upgroup</option>
<option value="paper-plane"> paper-plane</option>
<option value="pause-circle"> pause-circle</option>
<option value="play-circle"> play-circle </option>
<option value="plus-square"> plus-square</option>
<option value="question-circle"> question-circle</option>
<option value="registered"> registered</option>
<option value="sad-cry"> sad-cry</option>
<option value="sad-tear"> sad-tear</option>
<option value="save"> save</option>
<option value="share-square"> share-square</option>
<option value="smile"> smile</option>
<option value="smile-beam"> smile-beam </option>
<option value="smile-wink"> smile-wink</option>
<option value="snowflake"> snowflake</option>
<option value="square"> square</option>
<option value="star"> star</option>
<option value="star-half"> star-half</option>
<option value="sticky-note"> sticky-note</option>
<option value="stop-circle"> stop-circle</option>
<option value="sun"> sun</option>
<option value="surprise"> surprise </option>
<option value="thumbs-down"> thumbs-down</option>
<option value="thumbs-up">󱅤 thumbs-up</option>
<option value="times-circle"> times-circle</option>
<option value="tired"> tired</option>
<option value="trash-alt"> trash-alt</option>
<option value="user"> user</option>
<option value="user-circle"> user-circle</option>
<option value="window-close"> window-close</option>
<option value="window-maximize"> window-maximize </option>
<option value="window-minimize"> window-minimize</option>
<option value="window-restore"> window-restore</option>
</select>
Same problem here, during pushing image:
unauthorized: authentication required
What I did:
docker login --username=yourhubusername [email protected]
Which it printed:
--email is deprecated (but login succeeded still)
Solution: use the latest login syntax.
docker login
It will ask for both username and password interactively. Then the image push just works.
Even after using the new syntax, my ~/.docker/config.json
looks like this after logged in:
{
"auths": {
"https://index.docker.io/v1/": {}
},
"credsStore": "osxkeychain"
}
So the credential is in macOS' keychain.
If you want to just check if they are identical or not, a == b
should give you true / false with ordering taken into account.
In case you want to compare elements, you can use numpy for comparison
c = (numpy.array(a) == numpy.array(b))
Here, c will contain an array with 3 elements all of which are true (for your example). In the event elements of a and b don't match, then the corresponding elements in c will be false.
That error message is coming from docker and it not necessarily related to AWS as I have gotten same error when not using AWS ... its just saying docker is not getting authorization to proceed from whatever source of auth it happens to be using
In my case, in test I removed directory ~/.docker and got that error ... after I bounced my local docker registry then docker push was fine
Here is an example for all six boolean comparison operators (<, ==, >, >=, !=, <=):
BigDecimal big10 = new BigDecimal(10);
BigDecimal big20 = new BigDecimal(20);
System.out.println(big10.compareTo(big20) < -1); // false
System.out.println(big10.compareTo(big20) <= -1); // true
System.out.println(big10.compareTo(big20) == -1); // true
System.out.println(big10.compareTo(big20) >= -1); // true
System.out.println(big10.compareTo(big20) > -1); // false
System.out.println(big10.compareTo(big20) != -1); // false
System.out.println(big10.compareTo(big20) < 0); // true
System.out.println(big10.compareTo(big20) <= 0); // true
System.out.println(big10.compareTo(big20) == 0); // false
System.out.println(big10.compareTo(big20) >= 0); // false
System.out.println(big10.compareTo(big20) > 0); // false
System.out.println(big10.compareTo(big20) != 0); // true
System.out.println(big10.compareTo(big20) < 1); // true
System.out.println(big10.compareTo(big20) <= 1); // true
System.out.println(big10.compareTo(big20) == 1); // false
System.out.println(big10.compareTo(big20) >= 1); // false
System.out.println(big10.compareTo(big20) > 1); // false
System.out.println(big10.compareTo(big20) != 1); // true
For the Platform Independent Users or Windows users, what you can do is:
import runtime:
import (
"runtime"
"strings"
)
and then trim the string like this:
if runtime.GOOS == "windows" {
input = strings.TrimRight(input, "\r\n")
} else {
input = strings.TrimRight(input, "\n")
}
now you can compare it like that:
if strings.Compare(input, "a") == 0 {
//....yourCode
}
This is a better approach when you're making use of STDIN on multiple platforms.
This happens because on windows lines end with "\r\n"
which is known as CRLF, but on UNIX lines end with "\n"
which is known as LF and that's why we trim "\n"
on unix based operating systems while we trim "\r\n"
on windows.
Direct get a count of row
Using Eloquent
//Useing Eloquent
$count = Model::count();
//example
$count1 = Wordlist::count();
Using query builder
//Using query builder
$count = \DB::table('table_name')->count();
//example
$count2 = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)->count();
Here is another solution using Lodash:
var _ = require('lodash');
var result1 = [
{id:1, name:'Sandra', type:'user', username:'sandra'},
{id:2, name:'John', type:'admin', username:'johnny2'},
{id:3, name:'Peter', type:'user', username:'pete'},
{id:4, name:'Bobby', type:'user', username:'be_bob'}
];
var result2 = [
{id:2, name:'John', email:'[email protected]'},
{id:4, name:'Bobby', email:'[email protected]'}
];
// filter all those that do not match
var result = types1.filter(function(o1){
// if match found return false
return _.findIndex(types2, {'id': o1.id, 'name': o1.name}) !== -1 ? false : true;
});
console.log(result);
In Lumen's .env file, specify the timezones. For India, it would be like:
APP_TIMEZONE = 'Asia/Calcutta'
DB_TIMEZONE = '+05:30'
You can use indexOf(). Like:
var Color = ["blue", "black", "brown", "gold"];
var a = Color.indexOf("brown");
alert(a);
The indexOf() method searches the array for the specified item, and returns its position. And return -1 if the item is not found.
If you want to search from end to start, use the lastIndexOf() method:
var Color = ["blue", "black", "brown", "gold"];
var a = Color.lastIndexOf("brown");
alert(a);
The search will start at the specified position, or at the end if no start position is specified, and end the search at the beginning of the array.
Returns -1 if the item is not found.
This: "\0"
is a string, not a character. A character uses single quotes, like '\0'
.
Assuming you have Files a.txt and b.txt with
cat a.txt
a
b
c
d
1
3
5
cat b.txt
a
1
2
6
7
Keep in mind NR and FNR are awk built-in variables. NR - Gives the total number of records processed. (in this case both in a.txt and b.txt) FNR - Gives the total number of records for each input file (records in either a.txt or b.txt)
awk 'NR==FNR{a[$0];}{if($0 in a)print FILENAME " " NR " " FNR " " $0}' a.txt b.txt
a.txt 1 1 a
a.txt 2 2 b
a.txt 3 3 c
a.txt 4 4 d
a.txt 5 5 1
a.txt 6 6 3
a.txt 7 7 5
b.txt 8 1 a
b.txt 9 2 1
lets Add "next" to skip the first matched with NR==FNR
in b.txt and in a.txt
awk 'NR==FNR{a[$0];next}{if($0 in a)print FILENAME " " NR " " FNR " " $0}' a.txt b.txt
b.txt 8 1 a
b.txt 9 2 1
in b.txt but not in a.txt
awk 'NR==FNR{a[$0];next}{if(!($0 in a))print FILENAME " " NR " " FNR " " $0}' a.txt b.txt
b.txt 10 3 2
b.txt 11 4 6
b.txt 12 5 7
awk 'NR==FNR{a[$0];next}!($0 in a)' a.txt b.txt
2
6
7
Here is the simple explanation of Redux over Flux. Redux does not have a dispatcher.It relies on pure functions called reducers. It does not need a dispatcher. Each actions are handled by one or more reducers to update the single store. Since data is immutable, reducers returns a new updated state that updates the store
For more information Flux vs Redux
cls
$exactadminfile = "C:\temp\files\admin" #First folder to check the file
$userfile = "C:\temp\files\user" #Second folder to check the file
$filenames=Get-Content "C:\temp\files\files-to-watch.txt" #Reading the names of the files to test the existance in one of the above locations
foreach ($filename in $filenames) {
if (!(Test-Path $exactadminfile\$filename) -and !(Test-Path $userfile\$filename)) { #if the file is not there in either of the folder
Write-Warning "$filename absent from both locations"
} else {
Write-Host " $filename File is there in one or both Locations" #if file exists there at both locations or at least in one location
}
}
I took a stab a Adam Boduch's code to output a deep diff - this is entirely untested but the pieces are there:
function diff (obj1, obj2, path) {
obj1 = obj1 || {};
obj2 = obj2 || {};
return _.reduce(obj1, function(result, value, key) {
var p = path ? path + '.' + key : key;
if (_.isObject(value)) {
var d = diff(value, obj2[key], p);
return d.length ? result.concat(d) : result;
}
return _.isEqual(value, obj2[key]) ? result : result.concat(p);
}, []);
}
diff({ foo: 'lol', bar: { baz: true }}, {}) // returns ["foo", "bar.baz"]
The first answer is good for understanding how it works. But I wanted to understand how I should be using it in practice.
SUMMARY
class_weight="balanced"
works decent in the absence of you wanting to optimize manuallyclass_weight="balanced"
you capture more true events (higher TRUE recall) but also you are more likely to get false alerts (lower TRUE precision)
NB
The result might differ when using RF or GBM. sklearn does not have class_weight="balanced"
for GBM but lightgbm has LGBMClassifier(is_unbalance=False)
CODE
# scikit-learn==0.21.3
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, classification_report
import numpy as np
import pandas as pd
# case: moderate imbalance
X, y = datasets.make_classification(n_samples=50*15, n_features=5, n_informative=2, n_redundant=0, random_state=1, weights=[0.8]) #,flip_y=0.1,class_sep=0.5)
np.mean(y) # 0.2
LogisticRegression(C=1e9).fit(X,y).predict(X).mean() # 0.184
(LogisticRegression(C=1e9).fit(X,y).predict_proba(X)[:,1]>0.5).mean() # 0.184 => same as first
LogisticRegression(C=1e9,class_weight={0:0.5,1:0.5}).fit(X,y).predict(X).mean() # 0.184 => same as first
LogisticRegression(C=1e9,class_weight={0:2,1:8}).fit(X,y).predict(X).mean() # 0.296 => seems to make things worse?
LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X).mean() # 0.292 => seems to make things worse?
roc_auc_score(y,LogisticRegression(C=1e9).fit(X,y).predict(X)) # 0.83
roc_auc_score(y,LogisticRegression(C=1e9,class_weight={0:2,1:8}).fit(X,y).predict(X)) # 0.86 => about the same
roc_auc_score(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)) # 0.86 => about the same
# case: strong imbalance
X, y = datasets.make_classification(n_samples=50*15, n_features=5, n_informative=2, n_redundant=0, random_state=1, weights=[0.95])
np.mean(y) # 0.06
LogisticRegression(C=1e9).fit(X,y).predict(X).mean() # 0.02
(LogisticRegression(C=1e9).fit(X,y).predict_proba(X)[:,1]>0.5).mean() # 0.02 => same as first
LogisticRegression(C=1e9,class_weight={0:0.5,1:0.5}).fit(X,y).predict(X).mean() # 0.02 => same as first
LogisticRegression(C=1e9,class_weight={0:1,1:20}).fit(X,y).predict(X).mean() # 0.25 => huh??
LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X).mean() # 0.22 => huh??
(LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict_proba(X)[:,1]>0.5).mean() # same as last
roc_auc_score(y,LogisticRegression(C=1e9).fit(X,y).predict(X)) # 0.64
roc_auc_score(y,LogisticRegression(C=1e9,class_weight={0:1,1:20}).fit(X,y).predict(X)) # 0.84 => much better
roc_auc_score(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)) # 0.85 => similar to manual
roc_auc_score(y,(LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict_proba(X)[:,1]>0.5).astype(int)) # same as last
print(classification_report(y,LogisticRegression(C=1e9).fit(X,y).predict(X)))
pd.crosstab(y,LogisticRegression(C=1e9).fit(X,y).predict(X),margins=True)
pd.crosstab(y,LogisticRegression(C=1e9).fit(X,y).predict(X),margins=True,normalize='index') # few prediced TRUE with only 28% TRUE recall and 86% TRUE precision so 6%*28%~=2%
print(classification_report(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)))
pd.crosstab(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X),margins=True)
pd.crosstab(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X),margins=True,normalize='index') # 88% TRUE recall but also lot of false positives with only 23% TRUE precision, making total predicted % TRUE > actual % TRUE
I noticed that AS transfers too much data from/to HDD. It is very annoying, especially when starting to write a new line of code. So, I think, better will be reinstalling a hard disk with SSD. I have i5 with 6 Gb of memory, and the CPU seldom loads more than 50% even at build time. So, the most weak place is HDD.
Instead of initializing the variables with arbitrary values (for example int smallest = 9999, largest = 0
) it is safer to initialize the variables with the largest and smallest values representable by that number type (that is int smallest = Integer.MAX_VALUE, largest = Integer.MIN_VALUE
).
Since your integer array cannot contain a value larger than Integer.MAX_VALUE
and smaller than Integer.MIN_VALUE
your code works across all edge cases.
I've tried different solutions. First was:
a_df=np.unique(df[['col1','col2']], axis=0)
and it works well for not object data Another way to do this and to avoid error (for object columns type) is to apply drop_duplicates()
a_df=df.drop_duplicates(['col1','col2'])[['col1','col2']]
You can also use SQL to do this, but it worked very slow in my case:
from pandasql import sqldf
q="""SELECT DISTINCT col1, col2 FROM df;"""
pysqldf = lambda q: sqldf(q, globals())
a_df = pysqldf(q)
A custom action can handle this problem. And I found that it is not so complicated.
is_set = set() #global set reference
class IsStored(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
is_set.add(self.dest) # save to global reference
setattr(namespace, self.dest + '_set', True) # or you may inject directly to namespace
setattr(namespace, self.dest, values) # implementation of store_action
# You cannot inject directly to self.dest until you have a custom class
parser.add_argument("--myarg", type=int, default=1, action=IsStored)
params = parser.parse_args()
print(params.myarg, 'myarg' in is_set)
print(hasattr(params, 'myarg_set'))
SUPER-SHIFT-p > File: Revert File
is the only way
(where SUPER
is Command
on Mac and Ctrl
on PC)
By 'the same' I mean that there are is no item in array1 that is not contained in array2.
You could use flatten() and difference() for this, which works well if you don't care if there are items in array2
that aren't in array1
. It sounds like you're asking is array1 a subset of array2?
var array1 = [['a', 'b'], ['b', 'c']];
var array2 = [['b', 'c'], ['a', 'b']];
function isSubset(source, target) {
return !_.difference(_.flatten(source), _.flatten(target)).length;
}
isSubset(array1, array2); // ? true
array1.push('d');
isSubset(array1, array2); // ? false
isSubset(array2, array1); // ? true
You could use startOf('day')
method to compare just the date
Example :
var dateToCompare = moment("06/04/2015 18:30:00");
var today = moment(new Date());
dateToCompare.startOf('day').isSame(today.startOf('day'));
LocalDate ld ....;
LocalDateTime ldtime ...;
ld.isEqual(LocalDate.from(ldtime));
The error is:
Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])
In JSON, platforms
look like this:
"platforms": [
{
"platform": "iphone"
},
{
"platform": "ipad"
},
{
"platform": "android_phone"
},
{
"platform": "android_tablet"
}
]
So try change your pojo to something like this:
private List platforms;
public List getPlatforms(){
return this.platforms;
}
public void setPlatforms(List platforms){
this.platforms = platforms;
}
EDIT: you will need change mobile_networks
too. Will look like this:
private List mobile_networks;
public List getMobile_networks() {
return mobile_networks;
}
public void setMobile_networks(List mobile_networks) {
this.mobile_networks = mobile_networks;
}
var mydate = "2017-06-28T00:00:00";
var weekDayName = moment(mydate).format('ddd');
console.log(weekDayName);
Result: Wed
var mydate = "2017-06-28T00:00:00";
var weekDayName = moment(mydate).format('dddd');
console.log(weekDayName);
Result: Wednesday
I was looking into this and loved the approach from peege using a for loop! (because I'm learning VBA at the moment)
However, if we are trying to match "any" value of another column, how about using nested loops like the following?
Sub MatchAndColor()
Dim lastRow As Long
Dim sheetName As String
sheetName = "Sheet1" 'Insert your sheet name here
lastRow = Sheets(sheetName).Range("A" & Rows.Count).End(xlUp).Row
For lRowA = 1 To lastRow 'Loop through all rows
For lRowB = 1 To lastRow
If Sheets(sheetName).Cells(lRowA, "A") = Sheets(sheetName).Cells(lRowB, "B") Then
Sheets(sheetName).Cells(lRowA, "A").Interior.ColorIndex = 3 'Set Color to RED
End If
Next lRowB
Next lRowA
End Sub
I'm posting this answer for anyone using C# that wants a fully functional, well-tested answer that demonstrates using query instead of scan. In particular, this answer handles more than 1MB size of items to count.
public async Task<int> GetAvailableCount(string pool_type, string pool_key)
{
var queryRequest = new QueryRequest
{
TableName = PoolsDb.TableName,
ConsistentRead = true,
Select = Select.COUNT,
KeyConditionExpression = "pool_type_plus_pool_key = :type_plus_key",
ExpressionAttributeValues = new Dictionary<string, AttributeValue> {
{":type_plus_key", new AttributeValue { S = pool_type + pool_key }}
},
};
var t0 = DateTime.UtcNow;
var result = await Client.QueryAsync(queryRequest);
var count = result.Count;
var iter = 0;
while ( result.LastEvaluatedKey != null && result.LastEvaluatedKey.Values.Count > 0)
{
iter++;
var lastkey = result.LastEvaluatedKey.Values.ToList()[0].S;
_logger.LogDebug($"GetAvailableCount {pool_type}-{pool_key} iteration {iter} instance key {lastkey}");
queryRequest.ExclusiveStartKey = result.LastEvaluatedKey;
result = await Client.QueryAsync(queryRequest);
count += result.Count;
}
_logger.LogDebug($"GetAvailableCount {pool_type}-{pool_key} returned {count} after {iter} iterations in {(DateTime.UtcNow - t0).TotalMilliseconds} ms.");
return count;
}
}
An absolute xpath in HTML DOM starts with /html e.g.
/html/body/div[5]/div[2]/div/div[2]/div[2]/h2[1]
and a relative xpath finds the closed id to the dom element and generates xpath starting from that element e.g.
.//*[@id='answers']/h2[1]/a[1]
You can use firepath (firebug) for generating both types of xpaths
It won't make any difference which xpath you use in selenium, the former may be faster than the later one (but it won't be observable)
Absolute xpaths are prone to more regression as slight change in DOM makes them invalid or refer to a wrong element
Hello I was searching for a solution to reverse sorting a two dimensional numpy array, and I couldn't find anything that worked, but I think I have stumbled on a solution which I am uploading just in case anyone is in the same boat.
x=np.sort(array)
y=np.fliplr(x)
np.sort sorts ascending which is not what you want, but the command fliplr flips the rows left to right! Seems to work!
Hope it helps you out!
I guess it's similar to the suggest about -np.sort(-a) above but I was put off going for that by comment that it doesn't always work. Perhaps my solution won't always work either however I have tested it with a few arrays and seems to be OK.
var searchArray = function(arr, str){
// If there are no items in the array, return an empty array
if(typeof arr === 'undefined' || arr.length === 0) return [];
// If the string is empty return all items in the array
if(typeof str === 'undefined' || str.length === 0) return arr;
// Create a new array to hold the results.
var res = [];
// Check where the start (*) is in the string
var starIndex = str.indexOf('*');
// If the star is the first character...
if(starIndex === 0) {
// Get the string without the star.
str = str.substr(1);
for(var i = 0; i < arr.length; i++) {
// Check if each item contains an indexOf function, if it doesn't it's not a (standard) string.
// It doesn't necessarily mean it IS a string either.
if(!arr[i].indexOf) continue;
// Check if the string is at the end of each item.
if(arr[i].indexOf(str) === arr[i].length - str.length) {
// If it is, add the item to the results.
res.push(arr[i]);
}
}
}
// Otherwise, if the star is the last character
else if(starIndex === str.length - 1) {
// Get the string without the star.
str = str.substr(0, str.length - 1);
for(var i = 0; i < arr.length; i++){
// Check indexOf function
if(!arr[i].indexOf) continue;
// Check if the string is at the beginning of each item
if(arr[i].indexOf(str) === 0) {
// If it is, add the item to the results.
res.push(arr[i]);
}
}
}
// In any other case...
else {
for(var i = 0; i < arr.length; i++){
// Check indexOf function
if(!arr[i].indexOf) continue;
// Check if the string is anywhere in each item
if(arr[i].indexOf(str) !== -1) {
// If it is, add the item to the results
res.push(arr[i]);
}
}
}
// Return the results as a new array.
return res;
}
var birds = ['bird1','somebird','bird5','bird-big','abird-song'];
var res = searchArray(birds, 'bird*');
// Results: bird1, bird5, bird-big
var res = searchArray(birds, '*bird');
// Results: somebird
var res = searchArray(birds, 'bird');
// Results: bird1, somebird, bird5, bird-big, abird-song
There is an long list of caveats to a method like this, and a long list of 'what ifs' that are not taken into account, some of which are mentioned in other answers. But for a simple use of star syntax this may be a good starting point.
Lodash _.isEqual
allows you to do that:
var_x000D_
remoteJSON = {"allowExternalMembers": "false", "whoCanJoin": "CAN_REQUEST_TO_JOIN"},_x000D_
localJSON = {"whoCanJoin": "CAN_REQUEST_TO_JOIN", "allowExternalMembers": "false"};_x000D_
_x000D_
console.log( _.isEqual(remoteJSON, localJSON) );
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
_x000D_
Compare Side-By-Side looks like the most convenient to me though it's not the most popular:
UPD: I need to add that this plugin can freeze ST while comparing big files. It is certainly not the best decision if you are going to compare large texts.
.compare()
returns an integer, which is a measure of the difference between the two strings.
0
indicates that the two strings compare as equal. operator==
simply returns a boolean, indicating whether the strings are equal or not.
If you don't need the extra detail, you may as well just use ==
.
if you use recompose
, use mapProps
to make new props derived from incoming props
Edit for example:
import { compose, mapProps } from 'recompose';
const SomeComponent = ({ url, onComplete }) => (
{url ? (
<View />
) : null}
)
export default compose(
mapProps(({ url, storeUrl, history, ...props }) => ({
...props,
onClose: () => {
history.goBack();
},
url: url || storeUrl,
})),
)(SomeComponent);
As long as you override equals()
on each key and value contained in the map, then m1.equals(m2)
should be reliable to check for maps equality.
The same result can be obtained also by comparing toString()
of each map as you suggested, but using equals()
is a more intuitive approach.
May not be your specific situation, but if you store arrays in the map, may be a little tricky, because they must be compared value by value, or using Arrays.equals()
. More details about this see here.
Set the margin for body at 0 and that will fix it.
body {
margin: 0;
}
This is the best way to make add images/screenshots of your app and keep your repository look clean.
Create a screenshot
folder in your repository and add the images you want to display.
Now go to README.md
and add this HTML code to form a table.
#### Flutter App Screenshots
<table>
<tr>
<td>First Screen Page</td>
<td>Holiday Mention</td>
<td>Present day in purple and selected day in pink</td>
</tr>
<tr>
<td><img src="screenshots/Screenshot_1582745092.png" width=270 height=480></td>
<td><img src="screenshots/Screenshot_1582745125.png" width=270 height=480></td>
<td><img src="screenshots/Screenshot_1582745139.png" width=270 height=480></td>
</tr>
</table>
In the <td><img src="(COPY IMAGE PATH HERE)" width=270 height=480></td>
** To get the image path --> Go to the screenshot
folder and open the image
and on the right most side, you will find Copy path
button.
You will get a table like this in your repository--->
The main issue that is mentioned by others but not called out enough is that -O3
does nothing at all in Swift (and never has) so when compiled with that it is effectively non-optimised (-Onone
).
Option names have changed over time so some other answers have obsolete flags for the build options. Correct current options (Swift 2.2) are:
-Onone // Debug - slow
-O // Optimised
-O -whole-module-optimization //Optimised across files
Whole module optimisation has a slower compile but can optimise across files within the module i.e. within each framework and within the actual application code but not between them. You should use this for anything performance critical)
You can also disable safety checks for even more speed but with all assertions and preconditions not just disabled but optimised on the basis that they are correct. If you ever hit an assertion this means that you are into undefined behaviour. Use with extreme caution and only if you determine that the speed boost is worthwhile for you (by testing). If you do find it valuable for some code I recommend separating that code into a separate framework and only disabling the safety checks for that module.
First things first, you need to loop to < a.length
rather than a.length - 1
. As this is strictly less than you need to include the upper bound.
So, to check all pairs of elements you can do:
for (int i = 0; i < a.length; i++) {
for (int k = 0; k < a.length; k++) {
if (a[i] != a[k]) {
//do stuff
}
}
}
But this will compare, for example a[2]
to a[3]
and then a[3]
to a[2]
. Given that you are checking !=
this seems wasteful.
A better approach would be to compare each element i
to the rest of the array:
for (int i = 0; i < a.length; i++) {
for (int k = i + 1; k < a.length; k++) {
if (a[i] != a[k]) {
//do stuff
}
}
}
So if you have the indices [1...5] the comparison would go
1 -> 2
1 -> 3
1 -> 4
1 -> 5
2 -> 3
2 -> 4
2 -> 5
3 -> 4
3 -> 5
4 -> 5
So you see pairs aren't repeated. Think of a circle of people all needing to shake hands with each other.
Add jQuery and make sure only one link for jQuery cause more than one doesn't work...
Unable to run vagrant up because it gets stuck and times out? I recently had a "water in laptop incident" and had to migrate to a new one(on a MAC by the way). I successfully got all my projects up and running beside the one, which was using vagrant.
$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Clearing any previously set forwarded ports...
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
default: Adapter 1: nat
default: Adapter 2: hostonly
==> default: Forwarding ports...
default: 8000 (guest) => 8877 (host) (adapter 1)
default: 8001 (guest) => 8878 (host) (adapter 1)
default: 8080 (guest) => 7777 (host) (adapter 1)
default: 5432 (guest) => 2345 (host) (adapter 1)
default: 5000 (guest) => 8855 (host) (adapter 1)
default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
default: SSH address: 127.0.0.1:2222
default: SSH username: vagrant
default: SSH auth method: private key
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
default: Warning: Authentication failure. Retrying...
It couldn't authenticate, retried again and again and eventually gave up.
This is how I got it back in shape in 3 steps:
1 - Find the IdentityFile
used by Vagrant:
$ vagrant ssh-config
Host default
HostName 127.0.0.1
User vagrant
Port 2222
UserKnownHostsFile /dev/null
StrictHostKeyChecking no
PasswordAuthentication no
IdentityFile /Users/ned/.vagrant.d/insecure_private_key
IdentitiesOnly yes
LogLevel FATAL
2 - Check the public key in the IdentityFile
:
$ ssh-keygen -y -f <path-to-insecure_private_key>
It'd output something like this:
ssh-rsa AAAAB3Nyc2EAAA...9gE98OHlnVYCzRdK8jlqm8hQ==
3 - Log in to the Vagrant guest with the password vagrant
:
ssh -p 2222 -o UserKnownHostsFile=/dev/null [email protected]
The authenticity of host '[127.0.0.1]:2222 ([127.0.0.1]:2222)' can't be established.
RSA key fingerprint is dc:48:73:c3:18:e4:9d:34:a2:7d:4b:20:6a:e7:3d:3e.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '[127.0.0.1]:2222' (RSA) to the list of known hosts.
[email protected]'s password: vagrant
Welcome to Ubuntu 16.04.1 LTS (GNU/Linux 4.4.0-31-generic x86_64)
...
NOTE: if vagrant guest is configured to disallow password authentication you need to open VBox' GUI, double click guest name, login as vagrant/vagrant
, then sudo -s
and edit /etc/ssh/sshd_config
and look for PasswordAuthentication no
line (usually at the end of the file), replace no
with yes
and restart sshd (i.e. systemctl reload sshd
or /etc/init.d/sshd restart
).
4 - Add the public key to the /home/vagrant/authorized_keys
file.
$ echo "ssh-rsa AA2EAAA...9gEdK8jlqm8hQ== vagrant" > /home/vagrant/.ssh/authorized_keys
5 - Exit (CTRL+d) and stop the Vagrant guest and then bring it back up.
IMPORTANT if you use any provisioning tools (i.e. Ansible etc) disable it before restarting your guest as Vagrant will think your guest is not provisioned because of use of insecure private key. It will reinstall the key and then run your provisioner!
$ vagrant halt
$ vagrant up
Hopefully you will have your arms in the air now...
I got this, with just a minor amend, from Ned Batchelders article - Ned you are a champ!
To implement the fix, first expand out the existing web.config compilation section that looks like this by default:
<compilation debug="true" targetFramework="4.5"/>
Once expanded, I then added the following new configuration XML as I was instructed:
<assemblies>
<add assembly="System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</assemblies>
The final web.config tags should look like this:
<compilation debug="true" targetFramework="4.5">
<assemblies>
<add assembly="System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</assemblies>
</compilation>
In C the char type has a numeric value so the > operator will work just fine for example
#include <stdio.h>
main() {
char a='z';
char b='h';
if ( a > b ) {
printf("%c greater than %c\n",a,b);
}
}
This seems to be due to an incompatibility with the vbguest vagrant plugin and the latest version(s) of vagrant. It is trying to update the guest additions and failing to do it completely/properly.
I struggled with this recently with and older project.
I managed to track down the problem after checking what version of the dll that actually was in the bin folder.
I had a post-build script that copied dependent assemblies from a dll library folder to the bin folder. A common setup from the days before nuget.
So every time I built the post-build script replaced the correct version of Json.net with the older one
An unmodifiable map may still change. It is only a view on a modifiable map, and changes in the backing map will be visible through the unmodifiable map. The unmodifiable map only prevents modifications for those who only have the reference to the unmodifiable view:
Map<String, String> realMap = new HashMap<String, String>();
realMap.put("A", "B");
Map<String, String> unmodifiableMap = Collections.unmodifiableMap(realMap);
// This is not possible: It would throw an
// UnsupportedOperationException
//unmodifiableMap.put("C", "D");
// This is still possible:
realMap.put("E", "F");
// The change in the "realMap" is now also visible
// in the "unmodifiableMap". So the unmodifiableMap
// has changed after it has been created.
unmodifiableMap.get("E"); // Will return "F".
In contrast to that, the ImmutableMap of Guava is really immutable: It is a true copy of a given map, and nobody may modify this ImmutableMap in any way.
Update:
As pointed out in a comment, an immutable map can also be created with the standard API using
Map<String, String> immutableMap =
Collections.unmodifiableMap(new LinkedHashMap<String, String>(realMap));
This will create an unmodifiable view on a true copy of the given map, and thus nicely emulates the characteristics of the ImmutableMap
without having to add the dependency to Guava.
var startDate = moment(startDateVal, "DD.MM.YYYY");//Date format
var endDate = moment(endDateVal, "DD.MM.YYYY");
var isAfter = moment(startDate).isAfter(endDate);
if (isAfter) {
window.showErrorMessage("Error Message");
$(elements.endDate).focus();
return false;
}
There are many good answers here, and I couldn't read it all, but, I just came by to gave my little contribution too. I had 2 different problems:
vagrant up
wasn't able to find my ssh 'id_rsa' (because I didn't have it yet, at that time):
I ran ssh-keygen -t rsa -b 4096 -C "[email protected]"
, based on this GitHub's article, and voilá, steped through that;
Then, I got the same problem of this question "Warning: Connection timed out. Retrying...", eternally...: So, after reading a lot, I've restarted my system and looked at my BIOS (F2 to get there, on PC), and there were Virtualization disabled. I've enabled that, saved, and started the system once again, to check if it has changed anything.
After that, vagrant up
worked like a charm! It's 4am but it is running! How cool, hã? :D As I know there are very few masochist developers like me, that would try this at Windows, specially at Windows 10, I just couldn't not to forget coming here and left my word... another important information, is that, I was trying to set-up Laravel 5, using Homestead, VirtualBox, composer etc. It has worked. So, hope this answer helps like this question and answers helped me. My best wishes. G-bye!
- It is a very easy to use method in C++11.
- We can use std::chrono::high_resolution_clock from header
- We can write a method to print the method execution time in a much readable form.
For example, to find the all the prime numbers between 1 and 100 million, it takes approximately 1 minute and 40 seconds. So the execution time get printed as:
Execution Time: 1 Minutes, 40 Seconds, 715 MicroSeconds, 715000 NanoSeconds
The code is here:
#include <iostream>
#include <chrono>
using namespace std;
using namespace std::chrono;
typedef high_resolution_clock Clock;
typedef Clock::time_point ClockTime;
void findPrime(long n, string file);
void printExecutionTime(ClockTime start_time, ClockTime end_time);
int main()
{
long n = long(1E+8); // N = 100 million
ClockTime start_time = Clock::now();
// Write all the prime numbers from 1 to N to the file "prime.txt"
findPrime(n, "C:\\prime.txt");
ClockTime end_time = Clock::now();
printExecutionTime(start_time, end_time);
}
void printExecutionTime(ClockTime start_time, ClockTime end_time)
{
auto execution_time_ns = duration_cast<nanoseconds>(end_time - start_time).count();
auto execution_time_ms = duration_cast<microseconds>(end_time - start_time).count();
auto execution_time_sec = duration_cast<seconds>(end_time - start_time).count();
auto execution_time_min = duration_cast<minutes>(end_time - start_time).count();
auto execution_time_hour = duration_cast<hours>(end_time - start_time).count();
cout << "\nExecution Time: ";
if(execution_time_hour > 0)
cout << "" << execution_time_hour << " Hours, ";
if(execution_time_min > 0)
cout << "" << execution_time_min % 60 << " Minutes, ";
if(execution_time_sec > 0)
cout << "" << execution_time_sec % 60 << " Seconds, ";
if(execution_time_ms > 0)
cout << "" << execution_time_ms % long(1E+3) << " MicroSeconds, ";
if(execution_time_ns > 0)
cout << "" << execution_time_ns % long(1E+6) << " NanoSeconds, ";
}
I had the same "TypeError: an integer is required" error message when attempting to write. Thanks, the .encode() solved it for me. I'm running python 3.4 on a Dell D530 running 32 bit Windows XP Pro.
I'm omitting the com port settings here:
>>>import serial
>>>ser = serial.Serial(5)
>>>ser.close()
>>>ser.open()
>>>ser.write("1".encode())
1
>>>
Non VBA Solution:
Use Conditional Formatting rule with formula: =ISNA(A1)
(to highlight cells with all errors - not only #N/A
, use =ISERROR(A1)
)
VBA Solution:
Your code loops through 50 mln cells. To reduce number of cells, I use .SpecialCells(xlCellTypeFormulas, 16)
and .SpecialCells(xlCellTypeConstants, 16)
to return only cells with errors (note, I'm using If cell.Text = "#N/A" Then
)
Sub ColorCells()
Dim Data As Range, Data2 As Range, cell As Range
Dim currentsheet As Worksheet
Set currentsheet = ActiveWorkbook.Sheets("Comparison")
With currentsheet.Range("A2:AW" & Rows.Count)
.Interior.Color = xlNone
On Error Resume Next
'select only cells with errors
Set Data = .SpecialCells(xlCellTypeFormulas, 16)
Set Data2 = .SpecialCells(xlCellTypeConstants, 16)
On Error GoTo 0
End With
If Not Data2 Is Nothing Then
If Not Data Is Nothing Then
Set Data = Union(Data, Data2)
Else
Set Data = Data2
End If
End If
If Not Data Is Nothing Then
For Each cell In Data
If cell.Text = "#N/A" Then
cell.Interior.ColorIndex = 4
End If
Next
End If
End Sub
Note, to highlight cells witn any error (not only "#N/A"
), replace following code
If Not Data Is Nothing Then
For Each cell In Data
If cell.Text = "#N/A" Then
cell.Interior.ColorIndex = 3
End If
Next
End If
with
If Not Data Is Nothing Then Data.Interior.ColorIndex = 3
UPD: (how to add CF rule through VBA)
Sub test()
With ActiveWorkbook.Sheets("Comparison").Range("A2:AW" & Rows.Count).FormatConditions
.Delete
.Add Type:=xlExpression, Formula1:="=ISNA(A1)"
.Item(1).Interior.ColorIndex = 3
End With
End Sub
The error message explains it pretty well:
ValueError: The truth value of an array with more than one element is ambiguous.
Use a.any() or a.all()
What should bool(np.array([False, False, True]))
return? You can make several plausible arguments:
(1) True
, because bool(np.array(x))
should return the same as bool(list(x))
, and non-empty lists are truelike;
(2) True
, because at least one element is True
;
(3) False
, because not all elements are True
;
and that's not even considering the complexity of the N-d case.
So, since "the truth value of an array with more than one element is ambiguous", you should use .any()
or .all()
, for example:
>>> v = np.array([1,2,3]) == np.array([1,2,4])
>>> v
array([ True, True, False], dtype=bool)
>>> v.any()
True
>>> v.all()
False
and you might want to consider np.allclose
if you're comparing arrays of floats:
>>> np.allclose(np.array([1,2,3+1e-8]), np.array([1,2,3]))
True
You have to look at the bigger problem. How to write the directives that solve one problem. You should try directive use-form-error. Would it help to solve this problem, and many others.
<form name="ExampleForm">
<label>Password</label>
<input ng-model="password" required />
<br>
<label>Confirm password</label>
<input ng-model="confirmPassword" required />
<div use-form-error="isSame" use-error-expression="password && confirmPassword && password!=confirmPassword" ng-show="ExampleForm.$error.isSame">Passwords Do Not Match!</div>
</form>
Live example jsfiddle
Reading Hadley and Arun's answers one gets the impression that those who prefer dplyr
's syntax would have in some cases to switch over to data.table
or compromise for long running times.
But as some have already mentioned, dplyr
can use data.table
as a backend. This is accomplished using the dtplyr
package which recently had it's version 1.0.0 release. Learning dtplyr
incurs practically zero additional effort.
When using dtplyr
one uses the function lazy_dt()
to declare a lazy data.table, after which standard dplyr
syntax is used to specify operations on it. This would look something like the following:
new_table <- mtcars2 %>%
lazy_dt() %>%
filter(wt < 5) %>%
mutate(l100k = 235.21 / mpg) %>% # liters / 100 km
group_by(cyl) %>%
summarise(l100k = mean(l100k))
new_table
#> Source: local data table [?? x 2]
#> Call: `_DT1`[wt < 5][, `:=`(l100k = 235.21/mpg)][, .(l100k = mean(l100k)),
#> keyby = .(cyl)]
#>
#> cyl l100k
#> <dbl> <dbl>
#> 1 4 9.05
#> 2 6 12.0
#> 3 8 14.9
#>
#> # Use as.data.table()/as.data.frame()/as_tibble() to access results
The new_table
object is not evaluated until calling on it as.data.table()
/as.data.frame()
/as_tibble()
at which point the underlying data.table
operation is executed.
I've recreated a benchmark analysis done by data.table
author Matt Dowle back at December 2018 which covers the case of operations over large numbers of groups. I've found that dtplyr
indeed enables for the most part those who prefer the dplyr
syntax to keep using it while enjoying the speed offered by data.table
.
First of all, note you are not using the variable correctly:
if [ "pass_tc11" != "" ]; then
# ^
# missing $
Anyway, to check if a variable is empty or not you can use -z
--> the string is empty:
if [ ! -z "$pass_tc11" ]; then
echo "hi, I am not empty"
fi
or -n
--> the length is non-zero:
if [ -n "$pass_tc11" ]; then
echo "hi, I am not empty"
fi
From man test
:
-z STRING
the length of STRING is zero
-n STRING
the length of STRING is nonzero
$ [ ! -z "$var" ] && echo "yes"
$
$ var=""
$ [ ! -z "$var" ] && echo "yes"
$
$ var="a"
$ [ ! -z "$var" ] && echo "yes"
yes
$ var="a"
$ [ -n "$var" ] && echo "yes"
yes
If you wanted to use the DB facade:
DB::table('table_name')->whereNotNull('sent_at')->get();
On the formula menu just Select "Default Values for Nulls" then just add all the fields like the below:
{@Table.Field1} + {@Table.Field2} + {@Table.Field3} + {@Table.Field4} + {@Table.Field5}
In a comment to one of the answers you mention that to_date with a format doesn't help. In another comment you explain that the table is accessed via DBLINK.
So obviously the other system contains an invalid date that Oracle cannot accept. Fix this in the other dbms (or whatever you dblink to) and your query will work.
Having said this, I agree with the others: always use to_date with a format to convert a string literal to a date. Also never use only two digits for a year. For example '23/04/49' means 2049 in your system (format RR), but it confuses the reader (as you see from the answers suggesting a format with YY).
public boolean compareMap(Map<String, String> map1, Map<String, String> map2) {
if (map1 == null || map2 == null)
return false;
for (String ch1 : map1.keySet()) {
if (!map1.get(ch1).equalsIgnoreCase(map2.get(ch1)))
return false;
}
for (String ch2 : map2.keySet()) {
if (!map2.get(ch2).equalsIgnoreCase(map1.get(ch2)))
return false;
}
return true;
}
for i,j in enumerate(words): # i---index of word----j
#now you got index of your words (present in i)
print(i)
Use the time package to work with time information in Go.
Time instants can be compared using the Before, After, and Equal methods. The Sub method subtracts two instants, producing a Duration. The Add method adds a Time and a Duration, producing a Time.
Play example:
package main
import (
"fmt"
"time"
)
func inTimeSpan(start, end, check time.Time) bool {
return check.After(start) && check.Before(end)
}
func main() {
start, _ := time.Parse(time.RFC822, "01 Jan 15 10:00 UTC")
end, _ := time.Parse(time.RFC822, "01 Jan 16 10:00 UTC")
in, _ := time.Parse(time.RFC822, "01 Jan 15 20:00 UTC")
out, _ := time.Parse(time.RFC822, "01 Jan 17 10:00 UTC")
if inTimeSpan(start, end, in) {
fmt.Println(in, "is between", start, "and", end, ".")
}
if !inTimeSpan(start, end, out) {
fmt.Println(out, "is not between", start, "and", end, ".")
}
}
Following up on sas's answer, PHP 5.4, Symfony 2.8, I had to use
ini_set('date.timezone','<whatever timezone string>');
instead of date_default_timezone_set
. I also added a call to ini_set
to the top of a custom web/config.php
to get that check to succeed.
If you want to do it with multiline/multiple command/s then you can do this:
output=$( bash <<EOF
#multiline/multiple command/s
EOF
)
Or:
output=$(
#multiline/multiple command/s
)
Example:
#!/bin/bash
output="$( bash <<EOF
echo first
echo second
echo third
EOF
)"
echo "$output"
Output:
first
second
third
TL;DR
Java caches boxed Integer instances from -128
to 127
. Since you are using ==
to compare objects references instead of values, only cached objects will match. Either work with long
unboxed primitive values or use .equals()
to compare your Long
objects.
Long (pun intended) version
Why there is problem in comparing Long variable with value greater than 127? If the data type of above variable is primitive (long) then code work for all values.
Java caches Integer objects instances from the range -128 to 127. That said:
127
(cached), the same object instance will be pointed by all references. (N variables, 1 instance)128
(not cached), you will have an object instance pointed by every reference. (N variables, N instances)That's why this:
Long val1 = 127L;
Long val2 = 127L;
System.out.println(val1 == val2);
Long val3 = 128L;
Long val4 = 128L;
System.out.println(val3 == val4);
Outputs this:
true
false
For the 127L value, since both references (val1 and val2) point to the same object instance in memory (cached), it returns true
.
On the other hand, for the 128 value, since there is no instance for it cached in memory, a new one is created for any new assignments for boxed values, resulting in two different instances (pointed by val3 and val4) and returning false
on the comparison between them.
That happens solely because you are comparing two Long
object references, not long
primitive values, with the ==
operator. If it wasn't for this Cache mechanism, these comparisons would always fail, so the real problem here is comparing boxed values with ==
operator.
Changing these variables to primitive long
types will prevent this from happening, but in case you need to keep your code using Long
objects, you can safely make these comparisons with the following approaches:
System.out.println(val3.equals(val4)); // true
System.out.println(val3.longValue() == val4.longValue()); // true
System.out.println((long)val3 == (long)val4); // true
(Proper null checking is necessary, even for castings)
IMO, it's always a good idea to stick with .equals() methods when dealing with Object comparisons.
Reference links:
You are using Lists, concrete ArrayList. ArrayList also implements Collection interface. Collection interface has sort method which is used to sort the elements present in the specified list of Collection in ascending order. This will be the quickest and possibly the best way for your case.
Sorting a list in ascending order can be performed as default operation on this way:
Collections.sort(list);
Sorting a list in descending order can be performed on this way:
Collections.reverse(list);
According to these facts, your solution has to be written like this:
public class tes
{
public static void main(String args[])
{
List<Integer> lList = new ArrayList<Integer>();
lList.add(4);
lList.add(1);
lList.add(7);
lList.add(2);
lList.add(9);
lList.add(1);
lList.add(5);
Collections.sort(lList);
for(int i=0; i<lList.size();i++ )
{
System.out.println(lList.get(i));
}
}
}
More about Collections you can read here.
You can also use any()
, map()
like so:
if any(map(l.startswith, x)):
pass # Do something
Or alternatively, using a generator expression:
if any(l.startswith(s) for s in x)
pass # Do something
Bit late on this thread. angular.equals does deep check, however does anyone know that why its behave differently if one of the member contain "$" in prefix ?
You can try this Demo with following input
var obj3 = {}
obj3.a= "b";
obj3.b={};
obj3.b.$c =true;
var obj4 = {}
obj4.a= "b";
obj4.b={};
obj4.b.$c =true;
angular.equals(obj3,obj4);
This is easy. You just need to put inside .form-control
this:
.form-control{
-webkit-appearance:none;
-moz-appearance: none;
-ms-appearance: none;
-o-appearance: none;
appearance: none;
}
This will remove browser's appearance and allow your CSS.
The database must have a name (example DB1), try this one:
OracleConnection con = new OracleConnection("data source=DB1;user id=fastecit;password=fastecit");
In case the TNS is not defined you can also try this one:
OracleConnection con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=DB1)));
User Id=fastecit;Password=fastecit");
For whatever reason $('.panel-collapse').collapse({'toggle': true, 'parent': '#accordion'});
only seems to work the first time and it only works to expand the collapsible. (I tried to start with a expanded collapsible and it wouldn't collapse.)
It could just be something that runs once the first time you initialize collapse with those parameters.
You will have more luck using the show
and hide
methods.
Here is an example:
$(function() {
var $active = true;
$('.panel-title > a').click(function(e) {
e.preventDefault();
});
$('.collapse-init').on('click', function() {
if(!$active) {
$active = true;
$('.panel-title > a').attr('data-toggle', 'collapse');
$('.panel-collapse').collapse('hide');
$(this).html('Click to disable accordion behavior');
} else {
$active = false;
$('.panel-collapse').collapse('show');
$('.panel-title > a').attr('data-toggle','');
$(this).html('Click to enable accordion behavior');
}
});
});
Update
Granted KyleMit seems to have a way better handle on this then me. I'm impressed with his answer and understanding.
I don't understand what's going on or why the show
seemed to be toggling in some places.
But After messing around for a while.. Finally came with the following solution:
$(function() {
var transition = false;
var $active = true;
$('.panel-title > a').click(function(e) {
e.preventDefault();
});
$('#accordion').on('show.bs.collapse',function(){
if($active){
$('#accordion .in').collapse('hide');
}
});
$('#accordion').on('hidden.bs.collapse',function(){
if(transition){
transition = false;
$('.panel-collapse').collapse('show');
}
});
$('.collapse-init').on('click', function() {
$('.collapse-init').prop('disabled','true');
if(!$active) {
$active = true;
$('.panel-title > a').attr('data-toggle', 'collapse');
$('.panel-collapse').collapse('hide');
$(this).html('Click to disable accordion behavior');
} else {
$active = false;
if($('.panel-collapse.in').length){
transition = true;
$('.panel-collapse.in').collapse('hide');
}
else{
$('.panel-collapse').collapse('show');
}
$('.panel-title > a').attr('data-toggle','');
$(this).html('Click to enable accordion behavior');
}
setTimeout(function(){
$('.collapse-init').prop('disabled','');
},800);
});
});
Although its very late but I recently had the same issue.
Issue is because dir .
is changing as xyz.tar.gz
is created after running the command. There are two solutions:
Solution 1:
tar
will not mind if the archive is created in any directory inside .
. There can be reasons why can't create the archive outside the work space. Worked around it by creating a temporary directory for putting the archive as:
mkdir artefacts
tar -zcvf artefacts/archive.tar.gz --exclude=./artefacts .
echo $?
0
Solution 2: This one I like. create the archive file before running tar:
touch archive.tar.gz
tar --exclude=archive.tar.gz -zcvf archive.tar.gz .
echo $?
0
The second result set
have only one column but it should have 3 columns for it to be contented to the first result set
(columns must match when you use UNION
)
Try to add ID
as first column and PartOf_LOC_id
to your result set
, so you can do the UNION
.
;
WITH q AS ( SELECT ID ,
Location ,
PartOf_LOC_id
FROM tblLocation t
WHERE t.ID = 1 -- 1 represents an example
UNION ALL
SELECT t.ID ,
parent.Location + '>' + t.Location ,
t.PartOf_LOC_id
FROM tblLocation t
INNER JOIN q parent ON parent.ID = t.LOC_PartOf_ID
)
SELECT *
FROM q
# THIS WORK FOR ME
# Get all diferent values
df3 = pd.merge(df1, df2, how='outer', indicator='Exist')
df3 = df3.loc[df3['Exist'] != 'both']
# If you like to filter by a common ID
df3 = pd.merge(df1, df2, on="Fruit", how='outer', indicator='Exist')
df3 = df3.loc[df3['Exist'] != 'both']
Try to use "#" before and after of the date and be sure of your system date format. maybe "YYYYMMDD O YYYY-MM-DD O MM-DD-YYYY O USING '/ O \' "
Ex:
select id,numbers_from,created_date,amount_numbers,SMS_text
from Test_Table
where
created_date <= #2013-04-12#
2 + 2 = 5(*)
(for some floating-precision values of 2)
This problem frequently arises when we think of"floating point" as a way to increase precision. Then we run afoul of the "floating" part, which means there is no guarantee of which numbers can be represented.
So while we might easily be able to represent "1.0, -1.0, 0.1, -0.1" as we get to larger numbers we start to see approximations - or we should, except we often hide them by truncating the numbers for display.
As a result, we might think the computer is storing "0.003" but it may instead be storing "0.0033333333334".
What happens if you perform "0.0003 - 0.0002"? We expect .0001, but the actual values being stored might be more like "0.00033" - "0.00029" which yields "0.000004", or the closest representable value, which might be 0, or it might be "0.000006".
With current floating point math operations, it is not guaranteed that (a / b) * b == a.
#include <stdio.h>
// defeat inline optimizations of 'a / b * b' to 'a'
extern double bodge(int base, int divisor) {
return static_cast<double>(base) / static_cast<double>(divisor);
}
int main() {
int errors = 0;
for (int b = 1; b < 100; ++b) {
for (int d = 1; d < 100; ++d) {
// b / d * d ... should == b
double res = bodge(b, d) * static_cast<double>(d);
// but it doesn't always
if (res != static_cast<double>(b))
++errors;
}
}
printf("errors: %d\n", errors);
}
ideone reports 599 instances where (b * d) / d != b using just the 10,000 combinations of 1 <= b <= 100 and 1 <= d <= 100 .
The solution described in the FAQ is essentially to apply a granularity constraint - to test if (a == b +/- epsilon)
.
An alternative approach is to avoid the problem entirely by using fixed point precision or by using your desired granularity as the base unit for your storage. E.g. if you want times stored with nanosecond precision, use nanoseconds as your unit of storage.
C++11 introduced std::ratio as the basis for fixed-point conversions between different time units.
I've used dompdf with some success before. Although it can be a bit fussy about malformed HTML and there are still some CSS methods that aren't supported (e.g. css float does not work).
Download the package from github, and place it into a folder called dompdf
in your application/thirdparty
directory.
You can then create a helper with some functions to use the dompdf library, here is an example:
dompdf_helper.php
:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
function pdf_create($html, $filename='', $stream=TRUE)
{
include APPPATH.'thirdparty/dompdf/dompdf_config.inc.php';
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
if ($stream) {
$dompdf->stream($filename.".pdf", array("Attachment" => 0));
} else {
return $dompdf->output();
}
}
You simply pass the pdf_create
method your HTML as a string, the filename for the pdf file it will generate, and then an optional thirdparameter. The third parameter is a true/false flag to determine if it should save the file to your server before prompting the user to download it or not.
To have unique Categories:
var uniqueCategories = repository.GetAllProducts()
.Select(p=>p.Category)
.Distinct();
You need to provide a valid strict weak ordering comparison for the type stored in the queue, Person
in this case. The default is to use std::less<T>
, which resolves to something equivalent to operator<
. This relies on it's own stored type having one. So if you were to implement
bool operator<(const Person& lhs, const Person& rhs);
it should work without any further changes. The implementation could be
bool operator<(const Person& lhs, const Person& rhs)
{
return lhs.age < rhs.age;
}
If the the type does not have a natural "less than" comparison, it would make more sense to provide your own predicate, instead of the default std::less<Person>
. For example,
struct LessThanByAge
{
bool operator()(const Person& lhs, const Person& rhs) const
{
return lhs.age < rhs.age;
}
};
then instantiate the queue like this:
std::priority_queue<Person, std::vector<Person>, LessThanByAge> pq;
Concerning the use of std::greater<Person>
as comparator, this would use the equivalent of operator>
and have the effect of creating a queue with the priority inverted WRT the default case. It would require the presence of an operator>
that can operate on two Person
instances.
Me did not nothing, just copied development Bin folder DLLs to online deployed Bin folder and it worked fine for me.
Use the range
type. If the user enter a date:
select *
from table
where
update_date
<@
tsrange('2013-05-03', '2013-05-03'::date + 1, '[)');
If the user enters timestamps then you don't need the ::date + 1
part
http://www.postgresql.org/docs/9.2/static/rangetypes.html
http://www.postgresql.org/docs/9.2/static/functions-range.html
You probably want to have LI rather than the UL have the background-color:
.selected li {
background-color: red;
}
Then you want to have a dynamic class for the UL:
<ul ng-repeat="vote in votes" ng-click="setSelected()" class="{{selected}}">
Now you need to update the $scope.selected when clicking the row:
$scope.setSelected = function() {
console.log("show", arguments, this);
this.selected = 'selected';
}
and then un-select the previously highlighted row:
$scope.setSelected = function() {
// console.log("show", arguments, this);
if ($scope.lastSelected) {
$scope.lastSelected.selected = '';
}
this.selected = 'selected';
$scope.lastSelected = this;
}
Working solution:
Responding to the Forum Thread for the sake of completeness. Amazon has stopped using the the ECU - Elastic Compute Units and moved on to a vCPU based measure. So ignoring the ECU you pretty much can start comparing the EC2 Instances' sizes as CPU (Clock Speed), number of CPUs, RAM, storage etc.
Every instance families' instance configurations are published as number of vCPU and what is the physical processor. Detailed info and screenshot obstained from here http://aws.amazon.com/ec2/instance-types/#instance-type-matrix
You could insert something like this:
personPlay = "B";
while (!personPlay.equals("R") && !personPlay.equals("P") && !personPlay.equals("S")) {
//Get player's play from input-- note that this is
// stored as a string
System.out.println("Enter your play: ");
personPlay = scan.next();
//Make player's play uppercase for ease of comparison
personPlay = personPlay.toUpperCase();
if (!personPlay.equals("R") && !personPlay.equals("P") && !personPlay.equals("S"))
System.out.println("Invalid move. Try again.");
}
svg.selectAll("rect")
.attr('x',function(d,i){
// get x coord
console.log(this.getBBox().x, 'or', d3.select(this).attr('x'))
})
.attr('y',function(d,i){
// get y coord
console.log(this.getBBox().y)
})
.attr('dx',function(d,i){
// get dx coord
console.log(parseInt(d3.select(this).attr('dx')))
})
pip list
List installed packages: show ALL installed packages that even pip installed implictly
pip freeze
List installed packages: - list of packages that are installed using pip command
pip freeze has --all
flag to show all the packages.
Other difference is the output it renders, that you can check by running the commands.
Fix bugs with the first's answer:
def longestSubstringFinder(string1, string2):
answer = ""
len1, len2 = len(string1), len(string2)
for i in range(len1):
for j in range(len2):
lcs_temp=0
match=''
while ((i+lcs_temp < len1) and (j+lcs_temp<len2) and string1[i+lcs_temp] == string2[j+lcs_temp]):
match += string2[j+lcs_temp]
lcs_temp+=1
if (len(match) > len(answer)):
answer = match
return answer
print longestSubstringFinder("dd apple pie available", "apple pies")
print longestSubstringFinder("cov_basic_as_cov_x_gt_y_rna_genes_w1000000", "cov_rna15pcs_as_cov_x_gt_y_rna_genes_w1000000")
print longestSubstringFinder("bapples", "cappleses")
print longestSubstringFinder("apples", "apples")
There is also one nice thing some people might not know about:
echo $(( a < b ? a : b ))
This code will print the smallest number out of a
and b
Use:
select convert(nvarchar(10), CREATED_TS, 101)
or
select format(cast(CREATED_TS as date), 'MM/dd/yyyy') -- MySQL 3.23 and above
When to use Maps instead of plain JavaScript Objects ?
The plain JavaScript Object { key: 'value' } holds structured data. But plain JS object has its limitations :
Only strings and symbols can be used as keys of Objects. If we use any other things say, numbers as keys of an object then during accessing those keys we will see those keys will be converted into strings implicitly causing us to lose consistency of types. const names= {1: 'one', 2: 'two'}; Object.keys(names); // ['1', '2']
There are chances of accidentally overwriting inherited properties from prototypes by writing JS identifiers as key names of an object (e.g. toString, constructor etc.)
Another object cannot be used as key of an object, so no extra information can be written for an object by writing that object as key of another object and value of that another object will contain the extra information
Objects are not iterators
The size of an object cannot be determined directly
These limitations of Objects are solved by Maps but we must consider Maps as complement for Objects instead of replacement. Basically Map is just array of arrays but we must pass that array of arrays to the Map object as argument with new keyword otherwise only for array of arrays the useful properties and methods of Map aren't available. And remember key-value pairs inside the array of arrays or the Map must be separated by commas only, no colons like in plain objects.
3 tips to decide whether to use a Map or an Object :
Use maps over objects when keys are unknown until run time because keys formed by user input or unknowingly can break the code which uses the object if those keys overwrite the inherited properties of the object, so map is safer in those cases. Also use maps when all keys are the same type and all maps are the same type.
Use maps if there is a need to store primitive values as keys.
Use objects if we need to operate on individual elements.
Benefits of using Maps are :
1. Map accepts any key type and preserves the type of key :
We know that if the object's key is not a string or symbol then JS implicitly transforms it into a string. On the contrary, Map accepts any type of keys : string, number, boolean, symbol etc. and Map preserves the original key type. Here we will use number as key inside a Map and it will remain a number :
const numbersMap= new Map();
numbersMap.set(1, 'one');
numbersMap.set(2, 'two');
const keysOfMap= [...numbersMap.keys()];
console.log(keysOfMap); // [1, 2]
Inside a Map we can even use an entire object as a key. There may be times when we want to store some object related data, without attaching this data inside the object itself so that we can work with lean objects but want to store some information about the object. In those cases we need to use Map so that we can make Object as key and related data of the object as value.
const foo= {name: foo};
const bar= {name: bar};
const kindOfMap= [[foo, 'Foo related data'], [bar, 'Bar related data']];
But the downside of this approach is the complexity of accessing the value by key, as we have to loop through the entire array to get the desired value.
function getBy Key(kindOfMap, key) {
for (const [k, v] of kindOfMap) {
if(key === k) {
return v;
}
}
return undefined;
}
getByKey(kindOfMap, foo); // 'Foo related data'
We can solve this problem of not getting direct access to the value by using a proper Map.
const foo= {name: 'foo'};
const bar= {name: 'bar'};
const myMap= new Map();
myMap.set(foo, 'Foo related data');
myMap.set(bar, 'Bar related data');
console.log(myMap.get(foo)); // 'Foo related data'
We could have done this using WeakMap, just have to write, const myMap= new WeakMap( ). The differences between Map and WeakMap are that WeakMap allows for garbage collection of keys (here objects) so it prevents memory leaks, WeakMap accepts only objects as keys, and WeakMap has reduced set of methods.
2. Map has no restriction over key names :
For plain JS objects we can accidentally overwrite property inherited from the prototype and it can be dangerous. Here we will overwrite the toString( ) property of the actor object :
const actor= {
name: 'Harrison Ford',
toString: 'Actor: Harrison Ford'
};
Now let's define a fn isPlainObject( ) to determine if the supplied argument is a plain object and this fn uses toString( ) method to check it :
function isPlainObject(value) {
return value.toString() === '[object Object]';
}
isPlainObject(actor); // TypeError : value.toString is not a function
// this is because inside actor object toString property is a string instead of inherited method from prototype
The Map does not have any restrictions on the key names, we can use key names like toString, constructor etc. Here although actorMap object has a property named toString but the method toString( ) inherited from prototype of actorMap object works perfectly.
const actorMap= new Map();
actorMap.set('name', 'Harrison Ford');
actorMap.set('toString', 'Actor: Harrison Ford');
function isMap(value) {
return value.toString() === '[object Map]';
}
console.log(isMap(actorMap)); // true
If we have a situation where user input creates keys then we must take those keys inside a Map instead of a plain object. This is because user may choose a custom field name like, toString, constructor etc. then such key names in a plain object can potentially break the code that later uses this object. So the right solution is to bind the user interface state to a map, there is no way to break the Map :
const userCustomFieldsMap= new Map([['color', 'blue'], ['size', 'medium'], ['toString', 'A blue box']]);
3. Map is iterable :
To iterate a plain object's properties we need Object.entries( ) or Object.keys( ). The Object.entries(plainObject) returns an array of key value pairs extracted from the object, we can then destructure those keys and values and can get normal keys and values output.
const colorHex= {
'white': '#FFFFFF',
'black': '#000000'
}
for(const [color, hex] of Object.entries(colorHex)) {
console.log(color, hex);
}
//
'white' '#FFFFFF'
'black' '#000000'
As Maps are iterable that's why we do not need entries( ) methods to iterate over a Map and destructuring of key, value array can be done directly on the Map as inside a Map each element lives as an array of key value pairs separated by commas.
const colorHexMap= new Map();
colorHexMap.set('white', '#FFFFFF');
colorHexMap.set('black', '#000000');
for(const [color, hex] of colorHexMap) {
console.log(color, hex);
}
//'white' '#FFFFFF' 'black' '#000000'
Also map.keys( ) returns an iterator over keys and map.values( ) returns an iterator over values.
4. We can easily know the size of a Map
We cannot directly determine the number of properties in a plain object. We need a helper fn like, Object.keys( ) which returns an array with keys of the object then using length property we can get the number of keys or the size of the plain object.
const exams= {'John Rambo': '80%', 'James Bond': '60%'};
const sizeOfObj= Object.keys(exams).length;
console.log(sizeOfObj); // 2
But in the case of Maps we can have direct access to the size of the Map using map.size property.
const examsMap= new Map([['John Rambo', '80%'], ['James Bond', '60%']]);
console.log(examsMap.size);
Basically shared folders are renamed to synced folder from v1 to v2 (docs), under the bonnet it is still using vboxsf
between host and guest (there is known performance issues if there are large numbers of files/directories).
/vagrant
in guestVagrant is mounting the current working directory (where Vagrantfile
resides) as /vagrant
in the guest, this is the default behaviour.
See docs
NOTE: By default, Vagrant will share your project directory (the directory with the Vagrantfile) to /vagrant.
You can disable this behaviour by adding cfg.vm.synced_folder ".", "/vagrant", disabled: true
in your Vagrantfile
.
Based on the output /tmp
on host was NOT mounted during up time.
Use VAGRANT_INFO=debug vagrant up
or VAGRANT_INFO=debug vagrant reload
to start the VM for more output regarding why the synced folder is not mounted. Could be a permission issue (mode bits of /tmp
on host should be drwxrwxrwt
).
I did a test quick test using the following and it worked (I used opscode bento raring vagrant base box)
config.vm.synced_folder "/tmp", "/tmp/src"
output
$ vagrant reload
[default] Attempting graceful shutdown of VM...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) eth0
2) vmnet8
3) lxcbr0
4) vmnet1
What interface should the network bridge to? 1
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Configuring and enabling network interfaces...
[default] Mounting shared folders...
[default] -- /vagrant
[default] -- /tmp/src
Within the VM, you can see the mount info /tmp/src on /tmp/src type vboxsf (uid=900,gid=900,rw)
.
You go around making your webpage, and keep on putting {{data bindings}} whenever you feel you would have dynamic data. Angular will then provide you a $scope handler, which you can populate (statically or through calls to the web server).
This is a good understanding of data-binding. I think you've got that down.
For simple DOM manipulation, which doesnot involve data manipulation (eg: color changes on mousehover, hiding/showing elements on click), jQuery or old-school js is sufficient and cleaner. This assumes that the model in angular's mvc is anything that reflects data on the page, and hence, css properties like color, display/hide, etc changes dont affect the model.
I can see your point here about "simple" DOM manipulation being cleaner, but only rarely and it would have to be really "simple". I think DOM manipulation is one the areas, just like data-binding, where Angular really shines. Understanding this will also help you see how Angular considers its views.
I'll start by comparing the Angular way with a vanilla js approach to DOM manipulation. Traditionally, we think of HTML as not "doing" anything and write it as such. So, inline js, like "onclick", etc are bad practice because they put the "doing" in the context of HTML, which doesn't "do". Angular flips that concept on its head. As you're writing your view, you think of HTML as being able to "do" lots of things. This capability is abstracted away in angular directives, but if they already exist or you have written them, you don't have to consider "how" it is done, you just use the power made available to you in this "augmented" HTML that angular allows you to use. This also means that ALL of your view logic is truly contained in the view, not in your javascript files. Again, the reasoning is that the directives written in your javascript files could be considered to be increasing the capability of HTML, so you let the DOM worry about manipulating itself (so to speak). I'll demonstrate with a simple example.
<div rotate-on-click="45"></div>
First, I'd just like to comment that if we've given our HTML this functionality via a custom Angular Directive, we're already done. That's a breath of fresh air. More on that in a moment.
function rotate(deg, elem) {
$(elem).css({
webkitTransform: 'rotate('+deg+'deg)',
mozTransform: 'rotate('+deg+'deg)',
msTransform: 'rotate('+deg+'deg)',
oTransform: 'rotate('+deg+'deg)',
transform: 'rotate('+deg+'deg)'
});
}
function addRotateOnClick($elems) {
$elems.each(function(i, elem) {
var deg = 0;
$(elem).click(function() {
deg+= parseInt($(this).attr('rotate-on-click'), 10);
rotate(deg, this);
});
});
}
addRotateOnClick($('[rotate-on-click]'));
app.directive('rotateOnClick', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var deg = 0;
element.bind('click', function() {
deg+= parseInt(attrs.rotateOnClick, 10);
element.css({
webkitTransform: 'rotate('+deg+'deg)',
mozTransform: 'rotate('+deg+'deg)',
msTransform: 'rotate('+deg+'deg)',
oTransform: 'rotate('+deg+'deg)',
transform: 'rotate('+deg+'deg)'
});
});
}
};
});
Pretty light, VERY clean and that's just a simple manipulation! In my opinion, the angular approach wins in all regards, especially how the functionality is abstracted away and the dom manipulation is declared in the DOM. The functionality is hooked onto the element via an html attribute, so there is no need to query the DOM via a selector, and we've got two nice closures - one closure for the directive factory where variables are shared across all usages of the directive, and one closure for each usage of the directive in the link
function (or compile
function).
Two-way data binding and directives for DOM manipulation are only the start of what makes Angular awesome. Angular promotes all code being modular, reusable, and easily testable and also includes a single-page app routing system. It is important to note that jQuery is a library of commonly needed convenience/cross-browser methods, but Angular is a full featured framework for creating single page apps. The angular script actually includes its own "lite" version of jQuery so that some of the most essential methods are available. Therefore, you could argue that using Angular IS using jQuery (lightly), but Angular provides much more "magic" to help you in the process of creating apps.
This is a great post for more related information: How do I “think in AngularJS” if I have a jQuery background?
The above points are aimed at the OP's specific concerns. I'll also give an overview of the other important differences. I suggest doing additional reading about each topic as well.
Angular is a framework, jQuery is a library. Frameworks have their place and libraries have their place. However, there is no question that a good framework has more power in writing an application than a library. That's exactly the point of a framework. You're welcome to write your code in plain JS, or you can add in a library of common functions, or you can add a framework to drastically reduce the code you need to accomplish most things. Therefore, a more appropriate question is:
Good frameworks can help architect your code so that it is modular (therefore reusable), DRY, readable, performant and secure. jQuery is not a framework, so it doesn't help in these regards. We've all seen the typical walls of jQuery spaghetti code. This isn't jQuery's fault - it's the fault of developers that don't know how to architect code. However, if the devs did know how to architect code, they would end up writing some kind of minimal "framework" to provide the foundation (achitecture, etc) I discussed a moment ago, or they would add something in. For example, you might add RequireJS to act as part of your framework for writing good code.
Here are some things that modern frameworks are providing:
Before I further discuss Angular, I'd like to point out that Angular isn't the only one of its kind. Durandal, for example, is a framework built on top of jQuery, Knockout, and RequireJS. Again, jQuery cannot, by itself, provide what Knockout, RequireJS, and the whole framework built on top them can. It's just not comparable.
If you need to destroy a planet and you have a Death Star, use the Death star.
Building on my previous points about what frameworks provide, I'd like to commend the way that Angular provides them and try to clarify why this is matter of factually superior to jQuery alone.
In my above example, it is just absolutely unavoidable that jQuery has to hook onto the DOM in order to provide functionality. That means that the view (html) is concerned about functionality (because it is labeled with some kind of identifier - like "image slider") and JavaScript is concerned about providing that functionality. Angular eliminates that concept via abstraction. Properly written code with Angular means that the view is able to declare its own behavior. If I want to display a clock:
<clock></clock>
Done.
Yes, we need to go to JavaScript to make that mean something, but we're doing this in the opposite way of the jQuery approach. Our Angular directive (which is in it's own little world) has "augumented" the html and the html hooks the functionality into itself.
Angular gives you a straightforward way to structure your code. View things belong in the view (html), augmented view functionality belongs in directives, other logic (like ajax calls) and functions belong in services, and the connection of services and logic to the view belongs in controllers. There are some other angular components as well that help deal with configuration and modification of services, etc. Any functionality you create is automatically available anywhere you need it via the Injector subsystem which takes care of Dependency Injection throughout the application. When writing an application (module), I break it up into other reusable modules, each with their own reusable components, and then include them in the bigger project. Once you solve a problem with Angular, you've automatically solved it in a way that is useful and structured for reuse in the future and easily included in the next project. A HUGE bonus to all of this is that your code will be much easier to test.
THANK GOODNESS. The aforementioned jQuery spaghetti code resulted from a dev that made something "work" and then moved on. You can write bad Angular code, but it's much more difficult to do so, because Angular will fight you about it. This means that you have to take advantage (at least somewhat) to the clean architecture it provides. In other words, it's harder to write bad code with Angular, but more convenient to write clean code.
Angular is far from perfect. The web development world is always growing and changing and there are new and better ways being put forth to solve problems. Facebook's React and Flux, for example, have some great advantages over Angular, but come with their own drawbacks. Nothing's perfect, but Angular has been and is still awesome for now. Just as jQuery once helped the web world move forward, so has Angular, and so will many to come.
The three forms of looping are nearly identical. The enhanced for
loop:
for (E element : list) {
. . .
}
is, according to the Java Language Specification, identical in effect to the explicit use of an iterator with a traditional for
loop. In the third case, you can only modify the list contents by removing the current element and, then, only if you do it through the remove
method of the iterator itself. With index-based iteration, you are free to modify the list in any way. However, adding or removing elements that come before the current index risks having your loop skipping elements or processing the same element multiple times; you need to adjust the loop index properly when you make such changes.
In all cases, element
is a reference to the actual list element. None of the iteration methods makes a copy of anything in the list. Changes to the internal state of element
will always be seen in the internal state of the corresponding element on the list.
Essentially, there are only two ways to iterate over a list: by using an index or by using an iterator. The enhanced for loop is just a syntactic shortcut introduced in Java 5 to avoid the tedium of explicitly defining an iterator. For both styles, you can come up with essentially trivial variations using for
, while
or do while
blocks, but they all boil down to the same thing (or, rather, two things).
EDIT: As @iX3 points out in a comment, you can use a ListIterator
to set the current element of a list as you are iterating. You would need to use List#listIterator()
instead of List#iterator()
to initialize the loop variable (which, obviously, would have to be declared a ListIterator
rather than an Iterator
).
The QueryString collection is used to retrieve the variable values in the HTTP query string.
The HTTP query string is specified by the values following the question mark (?), like this:
Link with a query string
The line above generates a variable named txt with the value "this is a query string test".
Query strings are also generated by form submission, or by a user typing a query into the address bar of the browser.
And see this sample : http://www.codeproject.com/Articles/5876/Passing-variables-between-pages-using-QueryString
refer this : http://www.dotnetperls.com/querystring
you can collect More details in google .
You may use the ==
operator to compare unicode objects for equality.
>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>>
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>>
But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode
object to a str
object, like so:
>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False
See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.
Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.
I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."
Very similar to this question, and I would suggest the same formula in column D, albeit a few changes to the ranges:
=IFERROR(VLOOKUP(C1, A:B, 2, 0), "")
If you wanted to use match, you'd have to use INDEX
as well, like so:
=IFERROR(INDEX(B:B, MATCH(C1, A:A, 0)), "")
but this is really lengthy to me and you need to know how to properly use two functions (or three, if you don't know how IFERROR
works)!
Note: =IFERROR()
can be a substitute of =IF()
and =ISERROR()
in some cases :)
Here is another one:
http://www.essentialobjects.com/Products/WebBrowser/Default.aspx
This one is also based on the latest Chrome engine but it's much easier to use than CEF. It's a single .NET dll that you can simply reference and use.
DECLARE @INPUT VARCHAR(5) = '0.12',@INPUT_1 VARCHAR(5)='0.12x';
select CONVERT(float, @INPUT) YOUR_QUERY ,
case when isnumeric(@INPUT_1)=1 THEN CONVERT(float, @INPUT_1) ELSE 0 END AS YOUR_QUERY_ANSWERED
above will return values
however below query wont work
DECLARE @INPUT VARCHAR(5) = '0.12',@INPUT_1 VARCHAR(5)='0.12x';
select CONVERT(float, @INPUT) YOUR_QUERY ,
case when isnumeric(@INPUT_1)=1 THEN CONVERT(float, @INPUT_1) ELSE **@INPUT_1** END AS YOUR_QUERY_ANSWERED
as @INPUT_1 actually has varchar in it.
So your output column must have a varchar in it.
Modified @Surendra Jnawali' code. It fails
if current time is 23:40:00 i.e greater than start time and less than equals to 23:59:59.
All credit goes to the real owner
This is how it should be :This works perfect
public static boolean isTimeBetweenTwoTime(String argStartTime,
String argEndTime, String argCurrentTime) throws ParseException {
String reg = "^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$";
//
if (argStartTime.matches(reg) && argEndTime.matches(reg)
&& argCurrentTime.matches(reg)) {
boolean valid = false;
// Start Time
java.util.Date startTime = new SimpleDateFormat("HH:mm:ss")
.parse(argStartTime);
Calendar startCalendar = Calendar.getInstance();
startCalendar.setTime(startTime);
// Current Time
java.util.Date currentTime = new SimpleDateFormat("HH:mm:ss")
.parse(argCurrentTime);
Calendar currentCalendar = Calendar.getInstance();
currentCalendar.setTime(currentTime);
// End Time
java.util.Date endTime = new SimpleDateFormat("HH:mm:ss")
.parse(argEndTime);
Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endTime);
//
if (currentTime.compareTo(endTime) < 0) {
currentCalendar.add(Calendar.DATE, 1);
currentTime = currentCalendar.getTime();
}
if (startTime.compareTo(endTime) < 0) {
startCalendar.add(Calendar.DATE, 1);
startTime = startCalendar.getTime();
}
//
if (currentTime.before(startTime)) {
System.out.println(" Time is Lesser ");
valid = false;
} else {
if (currentTime.after(endTime)) {
endCalendar.add(Calendar.DATE, 1);
endTime = endCalendar.getTime();
}
System.out.println("Comparing , Start Time /n " + startTime);
System.out.println("Comparing , End Time /n " + endTime);
System.out
.println("Comparing , Current Time /n " + currentTime);
if (currentTime.before(endTime)) {
System.out.println("RESULT, Time lies b/w");
valid = true;
} else {
valid = false;
System.out.println("RESULT, Time does not lies b/w");
}
}
return valid;
} else {
throw new IllegalArgumentException(
"Not a valid time, expecting HH:MM:SS format");
}
}
RESULT
Comparing , Start Time /n Thu Jan 01 23:00:00 IST 1970
Comparing , End Time /n Fri Jan 02 02:00:00 IST 1970
Comparing , Current Time /n Fri Jan 02 01:50:00 IST 1970
RESULT, Time lies b/w
You can (should) use CROSS JOIN
. Following query will be equivalent to yours:
SELECT
table1.columnA
, table2.columnA
FROM table1
CROSS JOIN table2
WHERE table1.columnA = 'Some value'
or you can even use INNER JOIN with some always true conditon:
FROM table1
INNER JOIN table2 ON 1=1
You do not define a binding in your service's config, so you are getting the default values for wsHttpBinding
, and the default value for securityMode\transport
for that binding is Message
.
Try copying your binding configuration from the client's config to your service config and assign that binding to the endpoint via the bindingConfiguration
attribute:
<bindings>
<wsHttpBinding>
<binding name="ota2010AEndpoint"
.......>
<readerQuotas maxDepth="32" ... />
<reliableSession ordered="true" .... />
<security mode="Transport">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="Windows" negotiateServiceCredential="true"
establishSecurityContext="true" />
</security>
</binding>
</wsHttpBinding>
</bindings>
(Snipped parts of the config to save space in the answer).
<service name="Synxis" behaviorConfiguration="SynxisWCF">
<endpoint address="" name="wsHttpEndpoint"
binding="wsHttpBinding"
bindingConfiguration="ota2010AEndpoint"
contract="Synxis" />
This will then assign your defined binding (with Transport security) to the endpoint.
HashSet hs = new HashSet();
hs.addAll(arrayList);
arrayList.clear();
arrayList.addAll(hs);
the "algorithmic" way:
import math
def isPalindrome(inputString):
if inputString == None:
return False
strLength = len(inputString)
for i in range(math.floor(strLength)):
if inputString[i] != inputString[strLength - 1 - i]:
return False
return True
insertion sort:
1.In the insertion sort swapping is not required.
2.the time complexity of insertion sort is O(n)for best case and O(n^2) worst case.
3.less complex as compared to bubble sort.
4.example: insert books in library, arrange cards.
bubble sort: 1.Swapping required in bubble sort.
2.the time complexity of bubble sort is O(n)for best case and O(n^2) worst case.
3.more complex as compared to insertion sort.
This is a well-known nuisance when posting multiline commands in R. (You can get different behavior when you source()
a script to when you copy-and-paste the lines, both with multiline and comments)
ggplot(...) + geom_whatever1(...) +
geom_whatever2(...) +
stat_whatever3(...) +
geom_title(...) + scale_y_log10(...)
Error in "+ geom_whatever2(...) invalid argument to unary operator"
cf. answer to "Split code over multiple lines in an R script"
SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:
TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS"). REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar. INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC. Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions.
Having said that, I would use INTEGER and store seconds since Unix epoch (1970-01-01 00:00:00 UTC).
The first part is similar to Constantine, you can get the boolean of which rows are empty*:
In [21]: ne = (df1 != df2).any(1)
In [22]: ne
Out[22]:
0 False
1 True
2 True
dtype: bool
Then we can see which entries have changed:
In [23]: ne_stacked = (df1 != df2).stack()
In [24]: changed = ne_stacked[ne_stacked]
In [25]: changed.index.names = ['id', 'col']
In [26]: changed
Out[26]:
id col
1 score True
2 isEnrolled True
Comment True
dtype: bool
Here the first entry is the index and the second the columns which has been changed.
In [27]: difference_locations = np.where(df1 != df2)
In [28]: changed_from = df1.values[difference_locations]
In [29]: changed_to = df2.values[difference_locations]
In [30]: pd.DataFrame({'from': changed_from, 'to': changed_to}, index=changed.index)
Out[30]:
from to
id col
1 score 1.11 1.21
2 isEnrolled True False
Comment None On vacation
* Note: it's important that df1
and df2
share the same index here. To overcome this ambiguity, you can ensure you only look at the shared labels using df1.index & df2.index
, but I think I'll leave that as an exercise.
There is a statement you can issue at the module level:
Option Compare Text
This makes all "text comparisons" case insensitive. This means the following code will show the message "this is true":
Option Compare Text
Sub testCase()
If "UPPERcase" = "upperCASE" Then
MsgBox "this is true: option Compare Text has been set!"
End If
End Sub
See for example http://www.ozgrid.com/VBA/vba-case-sensitive.htm . I'm not sure it will completely solve the problem for all instances (such as the Application.Match
function) but it will take care of all the if a=b
statements. As for Application.Match
- you may want to convert the arguments to either upper case or lower case using the LCase
function.
As I knowit, encapsulation is hiding data of classes in themselves, and only making it accessible via setters / getters, if they must be accessed from the outer world.
Abstraction is the class design for itself.
Means, how You create Your class tree, which methods are general ones, which are inherited, which can be overridden,which attributes are only on private level, or on protected, how Do You build up Your class inheritance tree, Do You use final classes, abtract classes, interface-implementation.
Abstraction is more placed the oo-design phase, while encapsulation also enrolls into developmnent-phase.
Looking at the Volley perspective here are some advantages for your requirement:
Volley, on one hand, is totally focused on handling individual, small HTTP requests. So if your HTTP request handling has some quirks, Volley probably has a hook for you. If, on the other hand, you have a quirk in your image handling, the only real hook you have is ImageCache. "It’s not nothing, but it’s not a lot!, either". but it has more other advantages like Once you define your requests, using them from within a fragment or activity is painless unlike parallel AsyncTasks
Pros and cons of Volley:
So what’s nice about Volley?
The networking part isn’t just for images. Volley is intended to be an integral part of your back end. For a fresh project based off of a simple REST service, this could be a big win.
NetworkImageView is more aggressive about request cleanup than Picasso, and more conservative in its GC usage patterns. NetworkImageView relies exclusively on strong memory references, and cleans up all request data as soon as a new request is made for an ImageView, or as soon as that ImageView moves offscreen.
Performance. This post won’t evaluate this claim, but they’ve clearly taken some care to be judicious in their memory usage patterns. Volley also makes an effort to batch callbacks to the main thread to reduce context switching.
Volley apparently has futures, too. Check out RequestFuture if you’re interested.
If you’re dealing with high-resolution compressed images, Volley is the only solution here that works well.
Volley can be used with Okhttp (New version of Okhttp supports NIO for better performance )
Volley plays nice with the Activity life cycle.
Problems With Volley:
Since Volley is new, few things are not supported yet, but it's fixed.
Multipart Requests (Solution: https://github.com/vinaysshenoy/enhanced-volley)
status code 201 is taken as an error, Status code from 200 to 207 are successful responses now.(Fixed: https://github.com/Vinayrraj/CustomVolley)
Update: in latest release of Google volley, the 2XX Status codes bug is fixed now!Thanks to Ficus Kirkpatrick!
it's less documented but many of the people are supporting volley in github, java like documentation can be found here. On android developer website, you may find guide for Transmitting Network Data Using Volley. And volley source code can be found at Google Git
To solve/change Redirect Policy of Volley Framework use Volley with OkHTTP (CommonsWare mentioned above)
Also you can read this Comparing Volley's image loading with Picasso
Retrofit:
It's released by Square, This offers very easy to use REST API's (Update: Voila! with NIO support)
Pros of Retrofit:
Compared to Volley, Retrofit's REST API code is brief and provides excellent API documentation and has good support in communities! It is very easy to add into the projects.
We can use it with any serialization library, with error handling.
Update: - There are plenty of very good changes in Retrofit 2.0.0-beta2
Cons of Retrofit for version 1.6:
Memory related error handling functionality is not good (in older versions of Retrofit/OkHttp) not sure if it's improved with the Okio with Java NIO support.
Minimum threading assistance can result call back hell if we use this in an improper way.
(All above Cons have been solved in the new version of Retrofit 2.0 beta)
========================================================================
Update:
Android Async vs Volley vs Retrofit performance benchmarks (milliseconds, lower value is better):
(FYI above Retrofit Benchmarks info will improve with java NIO support because the new version of OKhttp is dependent on NIO Okio library)
In all three tests with varying repeats (1 – 25 times), Volley was anywhere from 50% to 75% faster. Retrofit clocked in at an impressive 50% to 90% faster than the AsyncTasks, hitting the same endpoint the same number of times. On the Dashboard test suite, this translated into loading/parsing the data several seconds faster. That is a massive real-world difference. In order to make the tests fair, the times for AsyncTasks/Volley included the JSON parsing as Retrofit does it for you automatically.
RetroFit Wins in benchmark test!
In the end, we decided to go with Retrofit for our application. Not only is it ridiculously fast, but it meshes quite well with our existing architecture. We were able to make a parent Callback Interface that automatically performs error handling, caching, and pagination with little to no effort for our APIs. In order to merge in Retrofit, we had to rename our variables to make our models GSON compliant, write a few simple interfaces, delete functions from the old API, and modify our fragments to not use AsyncTasks. Now that we have a few fragments completely converted, it’s pretty painless. There were some growing pains and issues that we had to overcome, but overall it went smoothly. In the beginning, we ran into a few technical issues/bugs, but Square has a fantastic Google+ community that was able to help us through it.
When to use Volley?!
We can use Volley when we need to load images as well as consuming REST APIs!, network call queuing system is needed for many n/w request at the same time! also Volley has better memory related error handling than Retrofit!
OkHttp can be used with Volley, Retrofit uses OkHttp by default! It has SPDY support, connection pooling, disk caching, transparent compression! Recently, it has got some support of java NIO with Okio library.
Source, credit: volley-vs-retrofit by Mr. Josh Ruesch
Note: About streaming it depends on what type of streaming you want like RTSP/RTCP.
It is simple: if recv()
returns 0 bytes; you will not receive any more data on this connection. Ever. You still might be able to send.
It means that your non-blocking socket have to raise an exception (it might be system-dependent) if no data is available but the connection is still alive (the other end may send).
One of most upleasing functional forEach
's limitations is lack of checked exceptions support.
One possible workaround is to replace terminal forEach
with plain old foreach loop:
Stream<String> stream = Stream.of("", "1", "2", "3").filter(s -> !s.isEmpty());
Iterable<String> iterable = stream::iterator;
for (String s : iterable) {
fileWriter.append(s);
}
Here is list of most popular questions with other workarounds on checked exception handling within lambdas and streams:
Java 8 Lambda function that throws exception?
Java 8: Lambda-Streams, Filter by Method with Exception
How can I throw CHECKED exceptions from inside Java 8 streams?
Java 8: Mandatory checked exceptions handling in lambda expressions. Why mandatory, not optional?
In my weird scenario, I had a different column that didn't always return a value in the 'render' function. return null
solved my issue.
Use this method Collections.sort(List,Comparator) . Implement a Comparator and pass it to Collections.sort().
class RecipeCompare implements Comparator<Recipe> {
@Override
public int compare(Recipe o1, Recipe o2) {
// write comparison logic here like below , it's just a sample
return o1.getID().compareTo(o2.getID());
}
}
Then use the Comparator
as
Collections.sort(recipes,new RecipeCompare());
npm ws was the answer for me. I found it less intrusive and more straight forward. With it was also trivial to mix websockets with rest services. Shared simple code on this post.
var WebSocketServer = require("ws").Server;
var http = require("http");
var express = require("express");
var port = process.env.PORT || 5000;
var app = express();
app.use(express.static(__dirname+ "/../"));
app.get('/someGetRequest', function(req, res, next) {
console.log('receiving get request');
});
app.post('/somePostRequest', function(req, res, next) {
console.log('receiving post request');
});
app.listen(80); //port 80 need to run as root
console.log("app listening on %d ", 80);
var server = http.createServer(app);
server.listen(port);
console.log("http server listening on %d", port);
var userId;
var wss = new WebSocketServer({server: server});
wss.on("connection", function (ws) {
console.info("websocket connection open");
var timestamp = new Date().getTime();
userId = timestamp;
ws.send(JSON.stringify({msgType:"onOpenConnection", msg:{connectionId:timestamp}}));
ws.on("message", function (data, flags) {
console.log("websocket received a message");
var clientMsg = data;
ws.send(JSON.stringify({msg:{connectionId:userId}}));
});
ws.on("close", function () {
console.log("websocket connection close");
});
});
console.log("websocket server created");
If you have Excel 2007 or later use COUNTIFS
with an "S" on the end, i.e.
=COUNTIFS(B2:B292,">10",B2:B292,"<10000")
You may need to change commas , to semi-colons ;
In earlier versions of excel use SUMPRODUCT
like this
=SUMPRODUCT((B2:B292>10)*(B2:B292<10000))
Note: if you want to include exactly 10 change > to >= - similarly with 10000, change < to <=
Try it:
if (Objects.equals(gender, "Male")) {
salutation ="Mr.";
} else if (Objects.equals(gender, "Female")) {
salutation ="Ms.";
}
I see a couple of issues.
First:
ser.read() is only going to return 1 byte at a time.
If you specify a count
ser.read(5)
it will read 5 bytes (less if timeout occurrs before 5 bytes arrive.)
If you know that your input is always properly terminated with EOL characters, better way is to use
ser.readline()
That will continue to read characters until an EOL is received.
Second:
Even if you get ser.read() or ser.readline() to return multiple bytes, since you are iterating over the return value, you will still be handling it one byte at a time.
Get rid of the
for line in ser.read():
and just say:
line = ser.readline()
If you want to discard the array at the same time as summing, you could do (say, stack
is the array):
var stack = [1,2,3],
sum = 0;
while(stack.length > 0) { sum += stack.pop() };
Just did the test and it works with toEqual
please find my test:
describe('toEqual', function() {
it('passes if arrays are equal', function() {
var arr = [1, 2, 3];
expect(arr).toEqual([1, 2, 3]);
});
});
Just for information:
toBe() versus toEqual(): toEqual() checks equivalence. toBe(), on the other hand, makes sure that they're the exact same object.
You can create the ordered dict from old dict in one line:
from collections import OrderedDict
ordered_dict = OrderedDict(sorted(ship.items())
The default sorting key is by dictionary key, so the new ordered_dict
is sorted by old dict's keys.
Instead of using the ifelse as in the above example, one can also prefilter the data prior to labeling based on some threshold values, this saves a lot of work for the plotting device:
xlimit <- 36
ylimit <- 24
ggplot(myData)+geom_point(aes(myX,myY))+
geom_label(data=myData[myData$myX > xlimit & myData$myY> ylimit,], aes(myX,myY,myLabel))
Why all people want to use '==' instead of simple '=' ? It is bad habit! It used only in [[ ]] expression. And in (( )) too. But you may use just = too! It work well in any case. If you use numbers, not strings use not parcing to strings and then compare like strings but compare numbers. like that
let -i i=5 # garantee that i is nubmber
test $i -eq 5 && echo "$i is equal 5" || echo "$i not equal 5"
It's match better and quicker. I'm expert in C/C++, Java, JavaScript. But if I use bash i never use '==' instead '='. Why you do so?
You could add a calculated column that includes only the date without the time. Between the two options, I'd go with the BETWEEN
operator because it's 'cleaner' to me and should make better use of indexes. Comparing execution plans would seem to indicate that BETWEEN
would be faster; however, in actual testing they performed the same.
It is working form me. Here I am geeting the table created datetime and adding 10 minutes on the datetime. later depending on the current time, Expiry Operations are done.
from datetime import datetime, time, timedelta
import pytz
Added 10 minutes on database datetime
table_datetime = '2019-06-13 07:49:02.832969' (example)
# Added 10 minutes on database datetime
# table_datetime = '2019-06-13 07:49:02.832969' (example)
table_expire_datetime = table_datetime + timedelta(minutes=10 )
# Current datetime
current_datetime = datetime.now()
# replace the timezone in both time
expired_on = table_expire_datetime.replace(tzinfo=utc)
checked_on = current_datetime.replace(tzinfo=utc)
if expired_on < checked_on:
print("Time Crossed)
else:
print("Time not crossed ")
It worked for me.
The API doc for IllegalArgumentException
:
Thrown to indicate that a method has been passed an illegal or inappropriate argument.
From looking at how it is used in the JDK libraries, I would say:
It seems like a defensive measure to complain about obviously bad input before the input can get into the works and cause something to fail halfway through with a nonsensical error message.
It's used for cases where it would be too annoying to throw a checked exception (although it makes an appearance in the java.lang.reflect code, where concern about ridiculous levels of checked-exception-throwing is not otherwise apparent).
I would use IllegalArgumentException
to do last ditch defensive argument checking for common utilities (trying to stay consistent with the JDK usage). Or where the expectation is that a bad argument is a programmer error, similar to an NullPointerException
. I wouldn't use it to implement validation in business code. I certainly wouldn't use it for the email example.
There is a way simpler way. You put the href in a paragraph just created for that href. For example:
HREF name
By default .equals() uses == identity function to compare which obviously doesn't work as the instances test1 and test2 are not the same. == only works with primitive data types like int or string. So you need to override it to make it work by comparing all the member variables of the Test class
If you are stuck with a legacy database where someone already placed JPA annotations on but did NOT define the relationships and you are now trying to define them for use in your code, then you might NOT be able to delete the customerId @Column
since other code may directly reference it already. In that case, define the relationships as follows:
@ManyToOne(optional=false)
@JoinColumn(name="productId",referencedColumnName="id_product", insertable=false, updatable=false)
private Product product;
@ManyToOne(optional=false)
@JoinColumn(name="customerId",referencedColumnName="id_customer", insertable=false, updatable=false)
private Customer customer;
This allows you to access the relationships. However, to add/update to the relationships you will have to manipulate the foreign keys directly via their defined @Column
values. It's not an ideal situation, but if you are handed this sort of situation, at least you can define the relationships so that you can use JPQL successfully.
jQuery is a DOM manipulation library.
AngularJS is an MV* framework.
In fact, AngularJS is one of the few JavaScript MV* frameworks (many JavaScript MVC tools still fall under the category library).
Being a framework, it hosts your code and takes ownership of decisions about what to call and when!
AngularJS itself includes a jQuery-lite edition within it. So for some basic DOM selection/manipulation, you really don't have to include the jQuery library (it saves many bytes to run on the network.)
AngularJS has the concept of "Directives" for DOM manipulation and designing reusable UI components, so you should use it whenever you feel the need of doing DOM manipulation related stuff (directives are only place where you should write jQuery code while using AngularJS).
AngularJS involves some learning curve (more than jQuery :-).
-->For any developer coming from jQuery background, my first advice would be to "learn JavaScript as a first class language before jumping onto a rich framework like AngularJS!" I learned the above fact the hard way.
Good luck.
Just put quotes around the Environment variable (as you have done) :
if "%DevEnvDir%" == "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\"
but it's the way you put opening bracket without a space that is confusing it.
Works for me...
C:\if "%gtk_basepath%" == "C:\Program Files\GtkSharp\2.12\" (echo yes)
yes
You could use IIF
statement like in the next example:
SELECT
IIF(test_expression, value_if_true, value_if_false) AS FIELD_NAME
FROM
TABLE_NAME
You can use
moment().isSameOrBefore(Moment|String|Number|Date|Array);
moment().isSameOrAfter(Moment|String|Number|Date|Array);
or
moment().isBetween(moment-like, moment-like);
See here : http://momentjs.com/docs/#/query/
public static void compareArrays(int[] array1, int[] array2) {
boolean b = true;
if (array1 != null && array2 != null){
if (array1.length != array2.length)
b = false;
else
for (int i = 0; i < array2.length; i++) {
if (array2[i] != array1[i]) {
b = false;
}
}
}else{
b = false;
}
System.out.println(b);
}
I saw someone use this example as part of a job application test. My feedback to him was that it lacks an escape from the outer loop when the array is mostly sorted.
consider what would happen in this case:
int[] arr = {1,2,3,4,5,6,7,8};
here's something that makes more sense:
int[] arr = {1,2,3,4,5,6,7,8};
int temp = 0;
int loopCount=0;
bool doBreak=true;
for (int write = 0; write < arr.Length; write++)
{
doBreak=true;
for (int sort = 0; sort < arr.Length - 1; sort++)
{
if (arr[sort] > arr[sort + 1])
{
temp = arr[sort + 1];
arr[sort + 1] = arr[sort];
arr[sort] = temp;
doBreak=false;
}
loopCount++;
}
if(doBreak){ break; /*early escape*/ }
}
Console.WriteLine(loopCount);
for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + " ");
Compare date only instead of date + time (NOW) with:
CURDATE()
Easier solution;
#/bin/bash
if (( ${1:-2} >= 2 )); then
echo "First parameter must be 0 or 1"
fi
# rest of script...
Output
$ ./test
First parameter must be 0 or 1
$ ./test 0
$ ./test 1
$ ./test 4
First parameter must be 0 or 1
$ ./test 2
First parameter must be 0 or 1
Explanation
(( ))
- Evaluates the expression using integers.${1:-2}
- Uses parameter expansion to set a value of 2
if undefined.>= 2
- True if the integer is greater than or equal to two 2
.Here is my solution for this :
mkdir temp
mkdir results
cp /usr/share/dict/american-english ~/temp/american-english-dictionary
cp /usr/share/dict/british-english ~/temp/british-english-dictionary
cat ~/temp/american-english-dictionary | wc -l > ~/results/count-american-english-dictionary
cat ~/temp/british-english-dictionary | wc -l > ~/results/count-british-english-dictionary
grep -Fxf ~/temp/american-english-dictionary ~/temp/british-english-dictionary > ~/results/common-english
grep -Fxvf ~/results/common-english ~/temp/american-english-dictionary > ~/results/unique-american-english
grep -Fxvf ~/results/common-english ~/temp/british-english-dictionary > ~/results/unique-british-english
In date '?'
, the '?'
is a literal string with value ?
, not a parameter placeholder, so your query does not have any parameters. The date
is a shorthand cast from (literal) string to date. You need to replace date '?'
with ?
to actually have a parameter.
Also if you know it is a date, then use setDate(..)
and not setString(..)
to set the parameter.
Try numpy.array_split
.
From the documentation:
>>> x = np.arange(8.0)
>>> np.array_split(x, 3)
[array([ 0., 1., 2.]), array([ 3., 4., 5.]), array([ 6., 7.])]
Identical to numpy.split
, but won't raise an exception if the groups aren't equal length.
If number of chunks > len(array) you get blank arrays nested inside, to address that - if your split array is saved in a
, then you can remove empty arrays by:
[x for x in a if x.size > 0]
Just save that back in a
if you wish.
You can use the query
function, so if your data were in col A where the first row was the column title...
=query(A2:A,"select A, count(A) where A != '' group by A order by count(A) desc label A 'City'", 0)
yields
City count
London 2
Paris 2
Berlin 1
Rome 1
Link to working Google Sheet.
https://docs.google.com/spreadsheets/d/1N5xw8-YP2GEPYOaRkX8iRA6DoeRXI86OkfuYxwXUCbc/edit#gid=0
PEP 8 defines that it is better to use the is
operator when comparing singletons.
The name of the array indicates the starting address. Starting address of both namet2
and nameIt2
are different. So the equal to (==
) operator checks whether the addresses are the same or not. For comparing two strings, a better way is to use strcmp()
, or we can compare character by character using a loop.
You can try with this:
WITH CTE_A As (SELECT COUNT(*) as articleNumber,A.UserID as UserID FROM Articles A
Inner Join Users U
on A.userId = U.userId
Group By A.userId , U.userId ),
B as (Select us.registrationDate,
CASE
WHEN CTE_A.articleNumber < 2 THEN 'Ama'
WHEN CTE_A.articleNumber < 5 THEN 'SemiAma'
WHEN CTE_A.articleNumber < 7 THEN 'Good'
WHEN CTE_A.articleNumber < 9 THEN 'Better'
WHEN CTE_A.articleNumber < 12 THEN 'Best'
ELSE 'Outstanding'
END as Ranking,
us.hobbies, etc...
FROM USERS Us Inner Join CTE_A
on CTE_A.UserID=us.UserID)
Select * from B
There is a bad Java bug that will cause this: https://bugs.java.com/view_bug.do?bug_id=JDK-8189789
Okay, I am now connecting without the semaphore timeout problem.
If anyone reading ever encounters the same thing, I hope that this procedure works for you; but no promises; hey, it's windows.
In my case this was Windows 7
I got a little hint from This page on eHow; not sure if that might help anyone or not.
So anyway, this was the simple twenty three step procedure that worked for me
Click on start button
Choose Control Panel
From Control Panel, choose Device Manger
From Device Manager, choose Universal Serial Bus Controllers
From Universal Serial Bus Controllers, click the little sideways triangle
I cannot predict what you'll see on your computer, but on mine I get a long drop-down list
Begin the investigation to figure out which one of these members of this list is the culprit...
On each member of the drop-down list, right-click on the name
A list will open, choose Properties
Guesswork time: using the various tabs near the top of the resulting window which opens, make a guess if this is the USB adapter driver which is choking your stuff with semaphore timeouts
Once you have made the proper guess, then close the USB Root Hub Properties window (but leave the Device Manager window open).
Physically disonnect anything and everything from that USB hub.
Unplug it.
Return your mouse pointer to that USB Root Hub in the list which you identified earlier.
Right click again
Choose Uninstall
Let Windows do its thing
Wait a little while
Power Down the whole computer if you have the time; some say this is required. I think I got away without it.
Plug the USB hub back into a USB connector on the PC
If the list in the device manager blinks and does a few flash-bulbs, it's okay.
Plug the BlueTooth connector back into the USB hub
Let windows do its thing some more
Within two minutes, I had a working COM port again, no semaphore timeouts.
Hope it works for anyone else who may be having a similar problem.
Just to enhance @adivis12 answer, you don't need to do the if
statement. Put it like this:
fig, ax = plt.subplots()
for BAR in dict_of_dfs.keys():
dict_of_dfs[BAR].plot(ax=ax)
Comparison of strings is very easy in Ruby:
v1 = "string1"
v2 = "string2"
puts v1 == v2 # prints false
puts "hello"=="there" # prints false
v1 = "string2"
puts v1 == v2 # prints true
Make sure your var2 is not an array (which seems to be like)
They are pretty similar, with Lodash is taking over...
They both are a utility library which takes the world of utility in JavaScript...
It seems Lodash is getting updated more regularly now, so more used in the latest projects...
Also Lodash seems is lighter by a couple of KBs...
Both have a good API and documentation, but I think the Lodash one is better...
Here is a screenshot for each of the documentation items for getting the first value of an array...
Underscore.js:
Lodash:
As things may get updated time to time, just check their website also...
I have had same problem with my scripts. But when I did some modifications it worked for me. I did like this :-
export k=$(date "+%k");
if [ $k -ge 16 ]
then exit 0;
else
echo "good job for nothing";
fi;
that way I resolved my problem. Hope that will help for you too.
There are several ways rsync compares files -- the authoritative source is the rsync algorithm description: https://www.andrew.cmu.edu/course/15-749/READINGS/required/cas/tridgell96.pdf. The wikipedia article on rsync is also very good.
For local files, rsync compares metadata and if it looks like it doesn't need to copy the file because size and timestamp match between source and destination it doesn't look further. If they don't match, it cp's the file. However, what if the metadata do match but files aren't actually the same? Then rsync probably didn't do what you intended.
Files that are the same size may still have changed. One simple example is a text file where you correct a typo -- like changing "teh" to "the". The file size is the same, but the corrected file will have a newer timestamp. --size-only
says "don't look at the time; if size matches assume files match", which would be the wrong choice in this case.
On the other hand, suppose you accidentally did a big cp -r A B
yesterday, but you forgot to preserve the time stamps, and now you want to do the operation in reverse rsync B A
. All those files you cp'ed have yesterday's time stamp, even though they weren't really modified yesterday, and rsync will by default end up copying all those files, and updating the timestamp to yesterday too. --size-only
may be your friend in this case (modulo the example above).
--ignore-times
says to compare the files regardless of whether the files have the same modify time. Consider the typo example above, but then not only did you correct the typo but you used touch
to make the corrected file have the same modify time as the original file -- let's just say you're sneaky that way. Well --ignore-times
will do a diff of the files even though the size and time match.
You can try VSCommands extension from Visual Studio Gallery. Latest release allows you to select two file and compare them:
a = 2;
vs
a(2);
function a(nb) {
lot;
of = cross;
browser();
return handling(nb);
}
In your opinion, what do you think is going to be the fastest?
e can also select rows based on values of a column that are not in a list or any iterable. We will create boolean variable just like before, but now we will negate the boolean variable by placing ~ in the front.
For example
list = [1, 0]
df[df.col1.isin(list)]
Try this. This method will determine if (two) date spans are overlapping, regardless of the ordering of the method's input arguments. This can also be used with more than two date spans, by individually checking each date span combination (ex. with 3 date spans, run span1
against span2
, span2
against span3
, and span1
against span3
):
public static class HelperFunctions
{
public static bool AreSpansOverlapping(Tuple<DateTime,DateTime> span1, Tuple<DateTime,DateTime> span2, bool includeEndPoints)
{
if (span1 == null || span2 == null)
{
return false;
}
else if ((new DateTime[] { span1.Item1, span1.Item2, span2.Item1, span2.Item2 }).Any(v => v == DateTime.MinValue))
{
return false;
}
else
{
if (span1.Item1 > span1.Item2)
{
span1 = new Tuple<DateTime, DateTime>(span1.Item2, span1.Item1);
}
if (span2.Item1 > span2.Item2)
{
span2 = new Tuple<DateTime, DateTime>(span2.Item2, span2.Item1);
}
if (includeEndPoints)
{
return
((
(span1.Item1 <= span2.Item1 && span1.Item2 >= span2.Item1)
|| (span1.Item1 <= span2.Item2 && span1.Item2 >= span2.Item2)
) || (
(span2.Item1 <= span1.Item1 && span2.Item2 >= span1.Item1)
|| (span2.Item1 <= span1.Item2 && span2.Item2 >= span1.Item2)
));
}
else
{
return
((
(span1.Item1 < span2.Item1 && span1.Item2 > span2.Item1)
|| (span1.Item1 < span2.Item2 && span1.Item2 > span2.Item2)
) || (
(span2.Item1 < span1.Item1 && span2.Item2 > span1.Item1)
|| (span2.Item1 < span1.Item2 && span2.Item2 > span1.Item2)
) || (
span1.Item1 == span2.Item1 && span1.Item2 == span2.Item2
));
}
}
}
}
Test:
static void Main(string[] args)
{
Random r = new Random();
DateTime d1;
DateTime d2;
DateTime d3;
DateTime d4;
for (int i = 0; i < 100; i++)
{
d1 = new DateTime(2012,1, r.Next(1,31));
d2 = new DateTime(2012,1, r.Next(1,31));
d3 = new DateTime(2012,1, r.Next(1,31));
d4 = new DateTime(2012,1, r.Next(1,31));
Console.WriteLine("span1 = " + d1.ToShortDateString() + " to " + d2.ToShortDateString());
Console.WriteLine("span2 = " + d3.ToShortDateString() + " to " + d4.ToShortDateString());
Console.Write("\t");
Console.WriteLine(HelperFunctions.AreSpansOverlapping(
new Tuple<DateTime, DateTime>(d1, d2),
new Tuple<DateTime, DateTime>(d3, d4),
true //or use False, to ignore span's endpoints
).ToString());
Console.WriteLine();
}
Console.WriteLine("COMPLETE");
System.Console.ReadKey();
}
If your requirements are to have no duplicates, you should be using a HashSet.
HashSet.Add will return false when the item already exists (if that even matters to you).
You can use the constructor that @pstrjds links to below (or here) to define the equality operator or you'll need to implement the equality methods in RemoteDevice
(GetHashCode
& Equals
).
the best explanation i've found is this:
What is the difference betwen INTEGER and NUMBER? When should we use NUMBER and when should we use INTEGER? I just wanted to update my comments here...
NUMBER always stores as we entered. Scale is -84 to 127. But INTEGER rounds to whole number. The scale for INTEGER is 0. INTEGER is equivalent to NUMBER(38,0). It means, INTEGER is constrained number. The decimal place will be rounded. But NUMBER is not constrained.
INTEGER is always slower then NUMBER. Since integer is a number with added constraint. It takes additional CPU cycles to enforce the constraint. I never watched any difference, but there might be a difference when we load several millions of records on the INTEGER column. If we need to ensure that the input is whole numbers, then INTEGER is best option to go. Otherwise, we can stick with NUMBER data type.
Here is the link
Doesn't the Directory.GetFiles(String, String)
overload already do that? You would just do Directory.GetFiles(dir, "*.jpg", SearchOption.AllDirectories)
If you want to put them in a list, then just replace the "*.jpg"
with a variable that iterates over a list and aggregate the results into an overall result set. Much clearer than individually specifying them. =)
Something like...
foreach(String fileExtension in extensionList){
foreach(String file in Directory.GetFiles(dir, fileExtension, SearchOption.AllDirectories)){
allFiles.Add(file);
}
}
(If your directories are large, using EnumerateFiles
instead of GetFiles
can potentially be more efficient)
I think it's worth putting a few timings up here for some perspective.
All timings done on OS-X 10.5.8 with python2.7
John Clement's answer:
python -m timeit -s 'my_list = range(1000)[::-1]; from operator import itemgetter' 'min(enumerate(my_list),key=itemgetter(1))'
1000 loops, best of 3: 239 usec per loop
David Wolever's answer:
python -m timeit -s 'my_list = range(1000)[::-1]' 'min((val, idx) for (idx, val) in enumerate(my_list))
1000 loops, best of 3: 345 usec per loop
OP's answer:
python -m timeit -s 'my_list = range(1000)[::-1]' 'my_list.index(min(my_list))'
10000 loops, best of 3: 96.8 usec per loop
Note that I'm purposefully putting the smallest item last in the list to make .index
as slow as it could possibly be. It would be interesting to see at what N the iterate once answers would become competitive with the iterate twice answer we have here.
Of course, speed isn't everything and most of the time, it's not even worth worrying about ... choose the one that is easiest to read unless this is a performance bottleneck in your code (and then profile on your typical real-world data -- preferably on your target machines).
You should use labels attribute inside plot function and the value of this attribute should be the vector containing the values that you want for each point to have.
Not only there is no need to declare it as false
first, I would add few other improvements:
use boolean
instead of Boolean
(which can also be null
for no reason)
assign during declaration:
boolean isMatch = email1.equals(email2);
...and use final
keyword if you can:
final boolean isMatch = email1.equals(email2);
Last but not least:
if (isMatch == true)
can be expressed as:
if (isMatch)
which renders the isMatch
flag not that useful, inlining it might not hurt readability. I suggest looking for some better courses/tutorials out there...
You're not comparing the contents of the arrays, you're comparing the addresses of the arrays. Since they're two separate arrays, they have different addresses.
Avoid this problem by using higher-level containers, such as std::vector
, std::deque
, or std::array
.
No need to use Linq like this here, because there already exists an extension method to do this for you.
Enumerable.Except<TSource>
http://msdn.microsoft.com/en-us/library/bb336390.aspx
You just need to create your own comparer to compare as needed.
I had the same problem where there's no files under Generated Java files, BuildConfig and R.java were missing. The automatic build option is not generating.
In Eclipse under Project, uncheck Build Automatically. Then under Project select Build Project. You may need to fix the projec
to_date
format worked for me. Please consider the date formats:
MON-
, MM
, .
, -
.
t.start_date >= to_date('14.11.2016 04:01:39', 'DD.MM.YYYY HH24:MI:SS')
t.start_date <=to_date('14.11.2016 04:10:07', 'DD.MM.YYYY HH24:MI:SS')
You can do a column transformation by using apply
Define a clean function to remove the dollar and commas and convert your data to float.
def clean(x):
x = x.replace("$", "").replace(",", "").replace(" ", "")
return float(x)
Next, call it on your column like this.
data['Revenue'] = data['Revenue'].apply(clean)
You can also change the value of this database parameter for your session by using the ALTER SESSION command and use it as you wanted
ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MM-YYYY';
SELECT TO_DATE('05-12-2015') FROM dual;
05/12/2015
First of all you should use double "==" instead of "=" to compare two values. Using "=" You assigning value to variable in this case "somevar"
class MyClass():
def __init__(self, a, b):
self.value1 = a
self.value2 = b
def __call__(self):
return [self.value1, self.value2]
Testing:
>>> x = MyClass('foo','bar')
>>> x()
['foo', 'bar']
I don't know how good or bad this is, but you can try something like this:
try:
obj = Model.objects.get(id=some_id)
except Model.DoesNotExist:
obj = Model.objects.create()
obj.__dict__.update(your_fields_dict)
obj.save()
You could eagerly create the a thread-safe Singleton instance, depending on your application needs, this is succinct code, though I would prefer @andasa's lazy version.
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton() { }
public static Singleton Instance()
{
return instance;
}
}
If you know you're on bash, and still get this error, make sure you write the if with spaces.
[[1==1]] # This outputs error
[[ 1==1 ]] # OK
See the MSDN getch docs. Specifically:
The _getch and_getwch functions read a single character from the console without echoing the character. None of these functions can be used to read CTRL+C. When reading a function key or an arrow key, each function must be called twice; the first call returns 0 or 0xE0, and the second call returns the actual key code.
The Python function returns a character. you can use ord()
to get an integer value you can test, for example keycode = ord(msvcrt.getch())
.
So if you read an 0x00 or 0xE0, read it a second time to get the key code for an arrow or function key. From experimentation, 0x00 precedes F1-F10 (0x3B-0x44) and 0xE0 precedes arrow keys and Ins/Del/Home/End/PageUp/PageDown.
... and getting back to easy ... for simple scripts you can use:
import sys
needs = (3, 9) # or whatever
pvi = sys.version_info.major, sys.version_info.minor
later in your code
try:
assert pvi >= needs
except:
print("will fail!")
# etc.
The accepted answers really limit what you can do with your code. For example, you would not be able to search an array of Object Ids
by using the equals method. Instead, it would make more sense to always cast to string and compare the keys.
Here's an example answer in case if you need to use indexOf()
to check within an array of references for a specific id. assume query
is a query you are executing, assume someModel
is a mongo model for the id you are looking for, and finally assume results.idList
is the field you are looking for your object id in.
query.exec(function(err,results){
var array = results.idList.map(function(v){ return v.toString(); });
var exists = array.indexOf(someModel._id.toString()) >= 0;
console.log(exists);
});
I used this code:
ws.Range("A:A").FormulaR1C1 = "=DATEVALUE(RC[1])"
column A will be mm/dd/yyyy
RC[1] is column B, the TEXT string, eg, 01/30/12, THIS IS NOT DATE TYPE
Sam's solution should be sufficient. I've used combination of both histogram difference and template matching because not one method was working for me 100% of the times. I've given less importance to histogram method though. Here's how I've implemented in simple python script.
import cv2
class CompareImage(object):
def __init__(self, image_1_path, image_2_path):
self.minimum_commutative_image_diff = 1
self.image_1_path = image_1_path
self.image_2_path = image_2_path
def compare_image(self):
image_1 = cv2.imread(self.image_1_path, 0)
image_2 = cv2.imread(self.image_2_path, 0)
commutative_image_diff = self.get_image_difference(image_1, image_2)
if commutative_image_diff < self.minimum_commutative_image_diff:
print "Matched"
return commutative_image_diff
return 10000 //random failure value
@staticmethod
def get_image_difference(image_1, image_2):
first_image_hist = cv2.calcHist([image_1], [0], None, [256], [0, 256])
second_image_hist = cv2.calcHist([image_2], [0], None, [256], [0, 256])
img_hist_diff = cv2.compareHist(first_image_hist, second_image_hist, cv2.HISTCMP_BHATTACHARYYA)
img_template_probability_match = cv2.matchTemplate(first_image_hist, second_image_hist, cv2.TM_CCOEFF_NORMED)[0][0]
img_template_diff = 1 - img_template_probability_match
# taking only 10% of histogram diff, since it's less accurate than template method
commutative_image_diff = (img_hist_diff / 10) + img_template_diff
return commutative_image_diff
if __name__ == '__main__':
compare_image = CompareImage('image1/path', 'image2/path')
image_difference = compare_image.compare_image()
print image_difference
Worth noting that when you inspect a string using the interactive python shell or a Jupyter notebook, the \n
and other backslashed strings like \t
are rendered literally:
>>> gotcha = 'Here is some random message...'
>>> gotcha += '\nAdditional content:\n\t{}'.format('Yet even more great stuff!')
>>> gotcha
'Here is some random message...\nAdditional content:\n\tYet even more great stuff!'
The newlines, tabs, and other special non-printed characters are rendered as whitespace only when printed, or written to a file:
>>> print('{}'.format(gotcha))
Here is some random message...
Additional content:
Yet even more great stuff!
I ran into a similar problem where I was trying to sort a n x 2 2D array
named contests
which is a 2D array of simple integers. This was working for most of the times but threw a runtime error for one input:-
Arrays.sort(contests, (row1, row2) -> {
if (row1[0] < row2[0]) {
return 1;
} else return -1;
});
Error:-
Exception in thread "main" java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.base/java.util.TimSort.mergeHi(TimSort.java:903)
at java.base/java.util.TimSort.mergeAt(TimSort.java:520)
at java.base/java.util.TimSort.mergeForceCollapse(TimSort.java:461)
at java.base/java.util.TimSort.sort(TimSort.java:254)
at java.base/java.util.Arrays.sort(Arrays.java:1441)
at com.hackerrank.Solution.luckBalance(Solution.java:15)
at com.hackerrank.Solution.main(Solution.java:49)
Looking at the answers above I tried adding a condition for equals
and I don't know why but it worked. Hopefully we must explicitly specify what should be returned for all cases (greater than, equals and less than):
Arrays.sort(contests, (row1, row2) -> {
if (row1[0] < row2[0]) {
return 1;
}
if(row1[0] == row2[0]) return 0;
return -1;
});
Here's a more valid way which also check if your textbox is filled with only blanks.
// When spaces are not allowed
if (string.IsNullOrWhiteSpace(txtBox1.Text) || string.IsNullOrWhiteSpace(txtBox2.Text))
//...give error...
// When spaces are allowed
if (string.IsNullOrEmpty(txtBox1.Text) || string.IsNullOrEmpty(txtBox2.Text))
//...give error...
The edited answer of @Habib.OSU is also fine, this is just another approach.
For those of you who need to convert hexadecimal representation of a signed byte from two-character String into byte (which in Java is always signed), there is an example. Parsing a hexadecimal string never gives negative number, which is faulty, because 0xFF is -1 from some point of view (two's complement coding). The principle is to parse the incoming String as int, which is larger than byte, and then wrap around negative numbers. I'm showing only bytes, so that example is short enough.
String inputTwoCharHex="FE"; //whatever your microcontroller data is
int i=Integer.parseInt(inputTwoCharHex,16);
//negative numbers is i now look like 128...255
// shortly i>=128
if (i>=Integer.parseInt("80",16)){
//need to wrap-around negative numbers
//we know that FF is 255 which is -1
//and FE is 254 which is -2 and so on
i=-1-Integer.parseInt("FF",16)+i;
//shortly i=-256+i;
}
byte b=(byte)i;
//b is now surely between -128 and +127
This can be edited to process longer numbers. Just add more FF's or 00's respectively. For parsing 8 hex-character signed integers, you need to use Long.parseLong, because FFFF-FFFF, which is integer -1, wouldn't fit into Integer when represented as a positive number (gives 4294967295). So you need Long to store it. After conversion to negative number and casting back to Integer, it will fit. There is no 8 character hex string, that wouldn't fit integer in the end.
You might also consider adding "
.
For example for %i in (*.wav) do opusenc "%~ni.wav" "%~ni.opus"
is very good idea.
I also received this error and tried everything I could find online and it wouldn't go away. In the end, I just downgraded MVC from 5.2.3 to 4.0.40804. I don't like this solution because eventually I'll need to use MVC 5, but it works for now. Hope this helps others.
Answer below the dotted line below is the original that's now outdated.
Here is the latest information ( Thank you @deadfish ):
add &hl=<language>
like &hl=pl
or &hl=en
example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl
All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en
......................................................................
To change the actual local market:
Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html
To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720
Sometimes it happened to me that the method described in the accepted answer didn't work, especially if the separator is a carriage return.
In those cases I solved in this way:
string='first line
second line
third line'
oldIFS="$IFS"
IFS='
'
IFS=${IFS:0:1} # this is useful to format your code with tabs
lines=( $string )
IFS="$oldIFS"
for line in "${lines[@]}"
do
echo "--> $line"
done
Let's measure the performance by using the following piece of code.
import numpy as np
import time
exec_time0 = []
exec_time1 = []
exec_time2 = []
sizeOfArray = 5000
numOfIterations = 200
for i in xrange(numOfIterations):
A = np.random.randint(0,255,(sizeOfArray,sizeOfArray))
B = np.random.randint(0,255,(sizeOfArray,sizeOfArray))
a = time.clock()
res = (A==B).all()
b = time.clock()
exec_time0.append( b - a )
a = time.clock()
res = np.array_equal(A,B)
b = time.clock()
exec_time1.append( b - a )
a = time.clock()
res = np.array_equiv(A,B)
b = time.clock()
exec_time2.append( b - a )
print 'Method: (A==B).all(), ', np.mean(exec_time0)
print 'Method: np.array_equal(A,B),', np.mean(exec_time1)
print 'Method: np.array_equiv(A,B),', np.mean(exec_time2)
Output
Method: (A==B).all(), 0.03031857
Method: np.array_equal(A,B), 0.030025185
Method: np.array_equiv(A,B), 0.030141515
According to the results above, the numpy methods seem to be faster than the combination of the == operator and the all() method and by comparing the numpy methods the fastest one seems to be the numpy.array_equal method.
The SOAP WS supports both remote procedure call (i.e. RPC) and message oriented middle-ware (MOM) integration styles. The Restful Web Service supports only RPC integration style.
The SOAP WS is transport protocol neutral. Supports multiple protocols like HTTP(S), Messaging, TCP, UDP SMTP, etc. The REST is transport protocol specific. Supports only HTTP or HTTPS protocols.
The SOAP WS permits only XML data format.You define operations, which tunnels through the POST. The focus is on accessing the named operations and exposing the application logic as a service. The REST permits multiple data formats like XML, JSON data, text, HTML, etc. Any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE Web operations. The focus is on accessing the named resources and exposing the data as a service. REST has AJAX support. It can use the XMLHttpRequest object. Good for stateless CRUD (Create, Read, Update, and Delete) operations. GET - represent() POST - acceptRepresention() PUT - storeRepresention() DELETE - removeRepresention()
SOAP based reads cannot be cached. REST based reads can be cached. Performs and scales better. SOAP WS supports both SSL security and WS-security, which adds some enterprise security features like maintaining security right up to the point where it is needed, maintaining identities through intermediaries and not just point to point SSL only, securing different parts of the message with different security algorithms, etc. The REST supports only point-to-point SSL security. The SSL encrypts the whole message, whether all of it is sensitive or not. The SOAP has comprehensive support for both ACID based transaction management for short-lived transactions and compensation based transaction management for long-running transactions. It also supports two-phase commit across distributed resources. The REST supports transactions, but it is neither ACID compliant nor can provide two phase commit across distributed transactional resources as it is limited by its HTTP protocol.
The SOAP has success or retry logic built in and provides end-to-end reliability even through SOAP intermediaries. REST does not have a standard messaging system, and expects clients invoking the service to deal with communication failures by retrying.
source http://java-success.blogspot.in/2012/02/java-web-services-interview-questions.html
As offer_date
is an number, and is of lower accuracy than your real dates, this may work...
- Convert your real date to a string of format YYYYMM
- Conver that value to an INT
- Compare the result you your offer_date
SELECT
*
FROM
offers
WHERE
offer_date = (SELECT CAST(to_char(create_date, 'YYYYMM') AS INT) FROM customers where id = '12345678')
AND offer_rate > 0
Also, by doing all the manipulation on the create_date
you only do the processing on one value.
Additionally, had you manipulated the offer_date
you would not be able to utilise any index on that field, and so force SCANs instead of SEEKs.
Try something like this:
$txt = "user id date";
$myfile = file_put_contents('logs.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);
So, I created an interface
public interface OnBackPressedListener {
void onBackPressed();
}
And implemented it by all fragments that need to handle back button. In main activity I overrided onBackPressed()
method:
@Override
public void onBackPressed() {
final Fragment currentFragment = mNavHostFragment.getChildFragmentManager().getFragments().get(0);
final NavController controller = Navigation.findNavController(this, R.id.nav_host_fragment);
if (currentFragment instanceof OnBackPressedListener)
((OnBackPressedListener) currentFragment).onBackPressed();
else if (!controller.popBackStack())
finish();
}
So, If the top fragment of my Navigation host implements OnBackPressedListener
interface, I call its onBackPressed()
method, elsewhere I simply pop back stack and close application if the back stack is empty.
You can do this without modifying the html. http://jsfiddle.net/8JwhZ/1085/
<div class="title">
<span>Cumulative performance</span>
<span>20/02/2011</span>
</div>
.title span:nth-of-type(1) { float:right }
.title span:nth-of-type(2) { float:left }
nobody seems to have recommended noHistory="true" in manifest.xml to prevent certain activity to appear after you press back button which by default calling method finish()
Typically, you pass the goroutine a (possibly separate) signal channel. That signal channel is used to push a value into when you want the goroutine to stop. The goroutine polls that channel regularly. As soon as it detects a signal, it quits.
quit := make(chan bool)
go func() {
for {
select {
case <- quit:
return
default:
// Do other stuff
}
}
}()
// Do stuff
// Quit goroutine
quit <- true
In single shot ;)
To get the Date
String date = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
To get the Time
String time = new SimpleDateFormat("hh:mm", Locale.getDefault()).format(new Date());
To get the date and time
String dateTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefaut()).format(new Date());
Happy coding :)
If you want only the line number do this:
grep -n Pattern file.ext | gawk '{print $1}' FS=":"
Example:
$ grep -n 9780545460262 EXT20130410.txt | gawk '{print $1}' FS=":"
48793
52285
54023
There are a few different options on how to do this. The most basic is to use varargin
, and then use nargin
, size
etc. to determine whether the optional arguments have been passed to the function.
% Function that takes two arguments, X & Y, followed by a variable
% number of additional arguments
function varlist(X,Y,varargin)
fprintf('Total number of inputs = %d\n',nargin);
nVarargs = length(varargin);
fprintf('Inputs in varargin(%d):\n',nVarargs)
for k = 1:nVarargs
fprintf(' %d\n', varargin{k})
end
A little more elegant looking solution is to use the inputParser
class to define all the arguments expected by your function, both required and optional. inputParser
also lets you perform type checking on all arguments.
For those who have the following error:
Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement
You can simply run this command to see which folder can load files from:
SHOW VARIABLES LIKE "secure_file_priv";
After that, you have to copy the files in that folder and run the query with LOAD DATA LOCAL INFILE
instead of LOAD DATA INFILE
.
The basic purpose of ValidateAntiForgeryToken attribute is to prevent cross-site request forgery attacks.
A cross-site request forgery is an attack in which a harmful script element, malicious command, or code is sent from the browser of a trusted user. For more information on this please visit http://www.asp.net/mvc/overview/security/xsrfcsrf-prevention-in-aspnet-mvc-and-web-pages.
It is simple to use, you need to decorate method with ValidateAntiForgeryToken attribute as below:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateProduct(Product product)
{
if (ModelState.IsValid)
{
//your logic
}
return View(ModelName);
}
It is derived from System.Web.Mvc namespace.
And in your view, add this code to add the token so it is used to validate the form upon submission.
@Html.AntiForgeryToken()
In swift 5, this is how you can capture motion and check
override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
if motion == .motionShake
{
print("shaking")
}
}
*
*
Linkers and Loaders from LinuxJournal explains this concept with clarity. It also explains how the classic name a.out came. (assembler output)
A quick summary,
c program --> [compiler] --> objectFile --> [linker] --> executable file (say, a.out)
we got the executable, now give this file to your friend or to your customer who is in need of this software :)
when they run this software, say by typing it in command line ./a.out
execute in command line ./a.out --> [Loader] --> [execve] --> program is loaded in memory
Once the program is loaded into the memory, control is transferred to this program by making the PC (program counter) pointing to the first instruction of a.out
The SimpleHelpers.FileEncoding Nuget package wraps a C# port of the Mozilla Universal Charset Detector into a dead-simple API:
var encoding = FileEncoding.DetectFileEncoding(txtFile);
For completeness; working with the data loaded into memory;
dim hf As integer: hf = freefile
dim lines() as string, i as long
open "c:\bla\bla.bla" for input as #hf
lines = Split(input$(LOF(hf), #hf), vbnewline)
close #hf
for i = 0 to ubound(lines)
debug.? "Line"; i; "="; lines(i)
next
The font sizes in your question are an example of what ratio each header should be in comparison to each other, rather than what size they should be themselves (in pixels).
So in response to your question "Is there a 'best practice' for these for mobile phones? - say iphone screen size?", yes there probably is - but you might find what someone says is "best practice" does not work for your layout.
However, to help get you on the right track, this article about building responsive layouts provides a good example of how to calculate the base font-size
in pixels in relation to device screen sizes.
The suggested font-sizes for screen resolutions suggested from that article are as follows:
@media (min-width: 858px) {
html {
font-size: 12px;
}
}
@media (min-width: 780px) {
html {
font-size: 11px;
}
}
@media (min-width: 702px) {
html {
font-size: 10px;
}
}
@media (min-width: 724px) {
html {
font-size: 9px;
}
}
@media (max-width: 623px) {
html {
font-size: 8px;
}
}
You can use from root directory:
RewriteEngine On
RewriteRule ^(?:system)\b.* /403.html
Or:
RewriteRule ^(?:system)\b.* /403.php # with header('HTTP/1.0 403 Forbidden');
Auto-alignment? Lawful good?
If you mean formatting, then Ctrl+Shift+F.
Note that the onload event doesn't seem to fire if the iframe is loaded when offscreen. This frequently occurs when using "Open in New Window" /w tabs.
Simple. Just instantiate your entity, set it to an object and pass it to your view in your controller.
Entity
VehicleInfoEntities db = new VehicleInfoEntities();
Stored Procedure
dbo.prcGetMakes()
or
you can add any parameters in your stored procedure inside the brackets ()
dbo.prcGetMakes("BMW")
Controller
public class HomeController : Controller
{
VehicleInfoEntities db = new VehicleInfoEntities();
public ActionResult Index()
{
var makes = db.prcGetMakes(null);
return View(makes);
}
}
I had exactly the same problem. Just one more working modification of the solution given by Denis (the type must be specified):
SELECT ARRAY(
SELECT column_name::text
FROM information_schema.columns
WHERE table_name='aean'
)
MYSQL 8 does, in a way:
MYSQL 8 supports JSON tables, so you could load your results into a JSON variable and select from that variable using the JSON_TABLE() command.
For 8085: Stack pointer is a special purpose 16-bit register in the Microprocessor, which holds the address of the top of the stack.
The stack pointer register in a computer is made available for general purpose use by programs executing at lower privilege levels than interrupt handlers. A set of instructions in such programs, excluding stack operations, stores data other than the stack pointer, such as operands, and the like, in the stack pointer register. When switching execution to an interrupt handler on an interrupt, return address data for the currently executing program is pushed onto a stack at the interrupt handler's privilege level. Thus, storing other data in the stack pointer register does not result in stack corruption. Also, these instructions can store data in a scratch portion of a stack segment beyond the current stack pointer.
Read this one for more info.
Use df.to_dict('records')
-- gives the output without having to transpose externally.
In [2]: df.to_dict('records')
Out[2]:
[{'customer': 1L, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'},
{'customer': 2L, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'},
{'customer': 3L, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}]
There is a, perhaps subtle, but important misconception in a number these answers. I thought I'd add my answer to clear it up.
What is
HEAD
?
HEAD
is a symbolic reference pointing to wherever you are in your commit history. It follows you wherever you go, whatever you do, like a shadow. If you make a commit, HEAD
will move. If you checkout something, HEAD
will move. Whatever you do, if you have moved somewhere new in your commit history, HEAD
has moved along with you. To address one common misconception: you cannot detach yourself from HEAD
. That is not what a detached HEAD state is. If you ever find yourself thinking: "oh no, i'm in detached HEAD state! I've lost my HEAD!" Remember, it's your HEAD. HEAD is you. You haven't detached from the HEAD, you and your HEAD have detached from something else.
HEAD
can point to a commit, yes, but typically it does not. Let me say that again. Typically HEAD
does not point to a commit. It points to a branch reference. It is attached to that branch, and when you do certain things (e.g., commit
or reset
), the attached branch will move along with HEAD
. You can see what it is pointing to by looking under the hood.
cat .git/HEAD
Normally you'll get something like this:
ref: refs/heads/master
Sometimes you'll get something like this:
a3c485d9688e3c6bc14b06ca1529f0e78edd3f86
That's what happens when HEAD
points directly to a commit. This is called a detached HEAD, because HEAD
is pointing to something other than a branch reference. If you make a commit in this state, master
, no longer being attached to HEAD
, will no longer move along with you. It does not matter where that commit is. You could be on the same commit as your master branch, but if HEAD
is pointing to the commit rather than the branch, it is detached and a new commit will not be associated with a branch reference.
You can look at this graphically if you try the following exercise. From a git repository, run this. You'll get something slightly different, but they key bits will be there. When it is time to checkout the commit directly, just use whatever abbreviated hash you get from the first output (here it is a3c485d
).
git checkout master
git log --pretty=format:"%h: %d" -1
# a3c485d: (HEAD -> master)
git checkout a3c485d -q # (-q is for dramatic effect)
git log --pretty=format:"%h: %d" -1
# a3c485d: (HEAD, master)
OK, so there is a small difference in the output here. Checking out the commit directly (instead of the branch) gives us a comma instead of an arrow. What do you think, are we in a detached HEAD state? HEAD is still referring to a specific revision that is associated with a branch name. We're still on the master branch, aren't we?
Now try:
git status
# HEAD detached at a3c485d
Nope. We're in 'detached HEAD' state.
You can see the same representation of (HEAD -> branch)
vs. (HEAD, branch)
with git log -1
.
HEAD
is you. It points to whatever you checked out, wherever you are. Typically that is not a commit, it is a branch. If HEAD
does point to a commit (or tag), even if it's the same commit (or tag) that a branch also points to, you (and HEAD
) have been detached from that branch. Since you don't have a branch attached to you, the branch won't follow along with you as you make new commits. HEAD
, however, will.
One of the best examples of Hadoop-like MapReduce implementation.
Keep in mind though that they are limited to key-value based implementations of the MapReduce idea (so they are limiting in applicability).
Read the data:
foo <- read.table(text="1 349
1 393
1 392
4 459
3 49
3 32
2 94")
And sort:
foo[order(foo$V1),]
This relies on the fact that order
keeps ties in their original order. See ?order
.
I'm sure there are other ways to accomplish this, but one solution would be to use join
through the Query Builder.
If you have tables set up something like this:
users
id
...
friends
id
user_id
friend_id
...
votes, comments and status_updates (3 tables)
id
user_id
....
In your User model:
class User extends Eloquent {
public function friends()
{
return $this->hasMany('Friend');
}
}
In your Friend model:
class Friend extends Eloquent {
public function user()
{
return $this->belongsTo('User');
}
}
Then, to gather all the votes for the friends of the user with the id of 1, you could run this query:
$user = User::find(1);
$friends_votes = $user->friends()
->with('user') // bring along details of the friend
->join('votes', 'votes.user_id', '=', 'friends.friend_id')
->get(['votes.*']); // exclude extra details from friends table
Run the same join
for the comments
and status_updates
tables. If you would like votes, comments, and status_updates to be in one chronological list, you can merge the resulting three collections into one and then sort the merged collection.
Edit
To get votes, comments, and status updates in one query, you could build up each query and then union the results. Unfortunately, this doesn't seem to work if we use the Eloquent hasMany
relationship (see comments for this question for a discussion of that problem) so we have to modify to queries to use where
instead:
$friends_votes =
DB::table('friends')->where('friends.user_id','1')
->join('votes', 'votes.user_id', '=', 'friends.friend_id');
$friends_comments =
DB::table('friends')->where('friends.user_id','1')
->join('comments', 'comments.user_id', '=', 'friends.friend_id');
$friends_status_updates =
DB::table('status_updates')->where('status_updates.user_id','1')
->join('friends', 'status_updates.user_id', '=', 'friends.friend_id');
$friends_events =
$friends_votes
->union($friends_comments)
->union($friends_status_updates)
->get();
At this point, though, our query is getting a bit hairy, so a polymorphic relationship with and an extra table (like DefiniteIntegral suggests below) might be a better idea.
Slightly modified version in C# that yields needed permutations in an array of ANY type.
// USAGE: create an array of any type, and call Permutations()
var vals = new[] {"a", "bb", "ccc"};
foreach (var v in Permutations(vals))
Console.WriteLine(string.Join(",", v)); // Print values separated by comma
public static IEnumerable<T[]> Permutations<T>(T[] values, int fromInd = 0)
{
if (fromInd + 1 == values.Length)
yield return values;
else
{
foreach (var v in Permutations(values, fromInd + 1))
yield return v;
for (var i = fromInd + 1; i < values.Length; i++)
{
SwapValues(values, fromInd, i);
foreach (var v in Permutations(values, fromInd + 1))
yield return v;
SwapValues(values, fromInd, i);
}
}
}
private static void SwapValues<T>(T[] values, int pos1, int pos2)
{
if (pos1 != pos2)
{
T tmp = values[pos1];
values[pos1] = values[pos2];
values[pos2] = tmp;
}
}
To elaborate on this response, Apache IO Utils might save you some time. Consider the following example that will recursively search for a file of a given name:
File file = FileUtils.listFiles(new File("the/desired/root/path"),
new NameFileFilter("filename.ext"),
FileFilterUtils.trueFileFilter()
).iterator().next();
See:
Another option:
x === 2 ? doSomething() : void 0;
One way to handle this is to put the information as an attribute on the primary one. I must stress, I really think this is the appropriate thing to do only when the two pieces of information are related such that one has information about the other.
For example, I sometimes stash the name of "crucial variables" or variables that have been significantly modified by storing a list of variable names as an attribute on the data frame:
attr(my.DF, 'Modified.Variables') <- DVs.For.Analysis$Names.of.Modified.Vars
return(my.DF)
This allows me to store a list of variable names with the data frame itself.
swift 4
I just add this line in viewDidLoad and work fine with me.
view.removeConstraints(view.constraints)
I would bind two different getters/setters pair to one variable:
class Coordinates{
int red;
@JsonProperty("red")
public byte getRed() {
return red;
}
public void setRed(byte red) {
this.red = red;
}
@JsonProperty("r")
public byte getR() {
return red;
}
public void setR(byte red) {
this.red = red;
}
}
To check your MySQL version on your mac, navigate to the directory where you installed it (default is usr/local/mysql/bin) and issue this command:
./mysql --version
Alternatively, to avoid needing to navigate to that specific dir to run the command, add its location to your path ($PATH). There's more than one way to add a dir to your $PATH (with explanations on stackoverflow and other places on how to do so), such as adding it to your ./bash_profile.
After adding the mysql bin dir to your $PATH, verify it's there by executing:
echo $PATH
Thereafter you can check your mysql version from anywhere by running (note no "./"):
mysql --version
As per Java doc:
A static method is a method that is associated with the class in which it is defined rather than with any object. Every instance of the class shares its static methods
In Java 8, along with default methods static methods are also allowed in an interface. This makes it easier for us to organize helper methods in our libraries. We can keep static methods specific to an interface in the same interface rather than in a separate class.
A nice example of this is:
list.sort(ordering);
instead of
Collections.sort(list, ordering);
Another example of using static methods is also given in doc itself:
public interface TimeClient {
// ...
static public ZoneId getZoneId (String zoneString) {
try {
return ZoneId.of(zoneString);
} catch (DateTimeException e) {
System.err.println("Invalid time zone: " + zoneString +
"; using default time zone instead.");
return ZoneId.systemDefault();
}
}
default public ZonedDateTime getZonedDateTime(String zoneString) {
return ZonedDateTime.of(getLocalDateTime(), getZoneId(zoneString));
}
}
use onPause()
method to do what you want to do on home button.
The first day of the previous month is always 1, to get the last day of the previous month, use 0 with DateSerial:
''Today is 20/03/2013 in dd/mm/yyyy
DateSerial(Year(Date),Month(Date),0) = 28/02/2013
DateSerial(Year(Date),1,0) = 31/12/2012
You can get the first day from the above like so:
LastDay = DateSerial(Year(Date),Month(Date),0)
FirstDay = LastDay-Day(LastDay)+1
See also: How to caculate last business day of month in VBScript
My understanding is that this question is better answered over in this post.
But briefly, the answer to the OP with this method is simply:
s1 = pd.merge(df1, df2, how='inner', on=['user_id'])
Which gives s1 with 5 columns: user_id and the other two columns from each of df1 and df2.
Generalizing @nisetama's solution using GNU date (trusty Ubuntu 14.04 LTS):
start=`date`
# <processing code>
stop=`date`
duration=`date -ud@$(($(date -ud"$stop" +%s)-$(date -ud"$start" +%s))) +%T`
echo $start
echo $stop
echo $duration
yielding:
Wed Feb 7 12:31:16 CST 2018
Wed Feb 7 12:32:25 CST 2018
00:01:09
I encountered this error because I converted my data to an np.array
. I fixed the problem by converting my data to an np.matrix
instead and taking the transpose.
ValueError:
regr.fit(np.array(x_list), np.array(y_list))
Correct:
regr.fit(np.transpose(np.matrix(x_list)), np.transpose(np.matrix(y_list)))
Try MySQL Workbench. It packs in very nice data modeling tools. Check out their screenshots for EER diagrams (Enhanced Entity Relationships, which are a notch up ER diagrams).
This isn't CakePHP specific, but you can modify the options so that the foreign keys and join tables follow the conventions that CakePHP uses. This would simplify your data modeling process once you've put the rules in place.
Unrecognized option: - Error: Could not create the Java Virtual Machine. Error: A fatal exception has occurred. Program will exit.
I was getting this Error due to incorrect syntax using in the terminal. I was using java - version. But its actually is java -version. there is no space between - and version. you can also cross check by using java -help.
i hope this will help.
In general you can use pandas rename function here. Given your dataframe you could change to a new name like this. If you had more columns you could also rename those in the dictionary. The 0 is the current name of your column
import pandas as pd
import numpy as np
e = np.random.normal(size=100)
e_dataframe = pd.DataFrame(e)
e_dataframe.rename(index=str, columns={0:'new_column_name'})
To highlight a block of code in Notepad++, please do the following steps
Style token
and select any of the five choices available ( styles from Using 1st style
to using 5th style
). Each is of different colors.If you want yellow color choose using 3rd style
.If you want to create your own style you can use Style Configurator
under Settings
menu.
Here simple interceptor example, I set mouse on wait when ajax starts and set it to auto when ajax ends.
$httpProvider.interceptors.push(function($document) {
return {
'request': function(config) {
// here ajax start
// here we can for example add some class or show somethin
$document.find("body").css("cursor","wait");
return config;
},
'response': function(response) {
// here ajax ends
//here we should remove classes added on request start
$document.find("body").css("cursor","auto");
return response;
}
};
});
Code has to be added in application config app.config
. I showed how to change mouse on loading state but in there it is possible to show/hide any loader content, or add, remove some css classes which are showing the loader.
Interceptor will run on every ajax call, so no need to create special boolean variables ( $scope.loading=true/false etc. ) on every http call.
Interceptor is using builded in angular jqLite https://docs.angularjs.org/api/ng/function/angular.element so no Jquery needed.
I also encountered this mongoose error CastError: Cast to ObjectId failed for value \"583fe2c488cf652d4c6b45d1\" at path \"_id\" for model User
So I run npm list command to verify the mongodb and mongoose version in my local.
Heres the report:
......
......
+-- [email protected]
+-- [email protected]
.....
It seems there's an issue on this mongodb version so what I did is I uninstall and try to use different version such as 2.2.16
$ npm uninstall mongodb
, it will delete the mongodb from your node_modules directory. After that install the lower version of mongodb.
$ npm install [email protected]
Finally, I restart the app and the CastError is gone!!
To decode:
byte[] image = Base64.getDecoder().decode(base64string);
To encode:
String text = Base64.getEncoder().encodeToString(imageData);
a combination of answers gave me a very fast running time. using the shift method to create new column of next row values, then using the row_iterator function as @alisdt did, but here i changed it from iterrows to itertuples which is 100 times faster.
my script is for iterating dataframe of duplications in different length and add one second for each duplication so they all be unique.
# create new column with shifted values from the departure time column
df['next_column_value'] = df['column_value'].shift(1)
# create row iterator that can 'save' the next row without running for loop
row_iterator = df.itertuples()
# jump to the next row using the row iterator
last = next(row_iterator)
# because pandas does not support items alteration i need to save it as an object
t = last[your_column_num]
# run and update the time duplications with one more second each
for row in row_iterator:
if row.column_value == row.next_column_value:
t = t + add_sec
df_result.at[row.Index, 'column_name'] = t
else:
# here i resetting the 'last' and 't' values
last = row
t = last[your_column_num]
Hope it will help.
As Christian's answer with assign()
shows, there is a way to assign in the global environment. A simpler, shorter (but not better ... stick with assign) way is to use the <<-
operator, ie
a <<- "new"
inside the function.
Use FromResult Method
public async Task<string> GetString()
{
System.Threading.Thread.Sleep(5000);
return await Task.FromResult("Hello");
}
sudo gem install --no-user-install <gem-name>
will install your gem globally, i.e. it will be available to all user's contexts.
you should to delete your the Override onOptionsItemSelected and replate your onCreateOptionsMenu with this code
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_action_bar_finish_order_stop, menu);
menu.getItem(0).setOnMenuItemClickListener(new FinishOrderStopListener(this, getApplication(), selectedChild));
return true;
}
Let me state it clearly that you can use the string overload to include nested levels regardless of the multiplicities of the corresponding relationships, if you don't mind using string literals:
query.Include("Collection.Property")
Note: This assumes that you will declare constants for row and column indexes named COLUMN_HEADING_ROW
, FIRST_COL
, and LAST_COL
, and that _xlSheet
is the name of the ExcelSheet
(using Microsoft.Interop.Excel
)
First, define the range:
var columnHeadingsRange = _xlSheet.Range[
_xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
_xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];
Then, set the background color of that range:
columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;
Finally, set the font color:
columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;
And here's the code combined:
var columnHeadingsRange = _xlSheet.Range[
_xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
_xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];
columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;
columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;
How do i make an:
if str(variable) == [contains text]:
condition?
Perhaps the most direct way is:
if str(variable) != '':
# ...
Note that the if not ...
solutions test the opposite condition.
If you just want to print user name on the pages, maybe you'll like this solution. It's free from object castings and works without Spring Security too:
@RequestMapping(value = "/index.html", method = RequestMethod.GET)
public ModelAndView indexView(HttpServletRequest request) {
ModelAndView mv = new ModelAndView("index");
String userName = "not logged in"; // Any default user name
Principal principal = request.getUserPrincipal();
if (principal != null) {
userName = principal.getName();
}
mv.addObject("username", userName);
// By adding a little code (same way) you can check if user has any
// roles you need, for example:
boolean fAdmin = request.isUserInRole("ROLE_ADMIN");
mv.addObject("isAdmin", fAdmin);
return mv;
}
Note "HttpServletRequest request" parameter added.
Works fine because Spring injects it's own objects (wrappers) for HttpServletRequest, Principal etc., so you can use standard java methods to retrieve user information.
I tried your code, you didn't assign/bind a value to your formControlName.
In HTML file:
<form [formGroup]="form">
<label>
<input type="radio" value="Male" formControlName="gender">
<span>male</span>
</label>
<label>
<input type="radio" value="Female" formControlName="gender">
<span>female</span>
</label>
</form>
In the TS file:
form: FormGroup;
constructor(fb: FormBuilder) {
this.name = 'Angular2'
this.form = fb.group({
gender: ['', Validators.required]
});
}
Make sure you use Reactive form properly: [formGroup]="form"
and you don't need the name attribute.
In my sample. words male
and female
in span tags are the values display along the radio button and Male
and Female
values are bind to formControlName
To make it shorter:
<form [formGroup]="form">
<input type="radio" value='Male' formControlName="gender" >Male
<input type="radio" value='Female' formControlName="gender">Female
</form>
Hope it helps:)
What error message are you getting?
I'd guess your actual error is because your php variable isn't wrapped in quotes. Try this
$update_query = "UPDATE db.tablename SET insert_time=now() WHERE username='" .$somename . "'";
Make sure that, server output is on otherwise output will not be display;
sql> set serveroutput on;
declare
n number(10):=1;
begin
while n<=10
loop
dbms_output.put_line(n);
n:=n+1;
end loop;
end;
/
Outout: 1 2 3 4 5 6 7 8 9 10
Answer E is correct answer. If E is not there, you will soon run out of memory (or) No correct answer.
Object should be unreachable to be eligible for GC. JVM will do multiple scans and moving objects from one generation to another generation to determine the eligibility of GC and frees the memory when the objects are not reachable.
Does it mean that I'm blocking reading any input from the Server/Client for this socket for 2000 millisecond and after this time the socket is ready to read data?
No, it means that if no data arrives within 2000ms a SocketTimeoutException
will be thrown.
What does it mean timeout expire?
It means the 2000ms (in your case) elapses without any data arriving.
What is the option which must be enabled prior to blocking operation?
There isn't one that 'must be' enabled. If you mean 'may be enabled', this is one of them.
Infinite Timeout menas that the socket does't read anymore?
What a strange suggestion. It means that if no data ever arrives you will block in the read forever.
for the entire line
^(\w+)\s+(\w+)\s+(\d+(?:\/\d+){2})\s+(\w+)$
subprocess.Popen
takes a cwd
argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'
), or use r'd:\test\local'
so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t
part will be translated to a tab.
So, your new line should look like:
subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')
To use your Python script path as cwd, import os
and define cwd using this:
os.path.dirname(os.path.realpath(__file__))
From MySQL docs: Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC:
In standard SQL, the syntax
DECIMAL(M)
is equivalent toDECIMAL(M,0)
So, you are converting to a number with 2 integer digits and 0 decimal digits. Try this instead:
CAST((COUNT(*) * 1.5) AS DECIMAL(12,2))
Simple way:
directory_name = "name"
Dir.mkdir(directory_name) unless File.exists?(directory_name)
If I understand correctly you want to exclude files from the vscode fuzzy finder. If that is the case, I am guessing the above answers are for older versions of vscode. What worked for me is adding:
"files.exclude": {
"**/directory-you-want-to-exclude": true,
"**/.git": true,
"**/.svn": true,
"**/.hg": true,
"**/CVS": true,
"**/.DS_Store": true
}
to my settings.json
. This file can be opened through File
>Preferences
>Settings
I think you should have a directory per container with a Dockerfile (no extension) in it. For example:
/db/Dockerfile
/web/Dockerfile
/api/Dockerfile
When you build just use the directory name, Docker will find the Dockerfile. e.g:
docker build -f ./db .
window.open is a method; you can open new window, and can customize it. window.location.href is just a property of the current window.
The simple answer for this problem is to change the DOCK property of the Label. It is "NONE" by default.
Check out the MSDN article Asynchronous Programming with Async and Await if you can afford to play with new stuff. It was added to .NET 4.5.
Example code snippet from the link (which is itself from this MSDN sample code project):
// Three things to note in the signature:
// - The method has an async modifier.
// - The return type is Task or Task<T>. (See "Return Types" section.)
// Here, it is Task<int> because the return statement returns an integer.
// - The method name ends in "Async."
async Task<int> AccessTheWebAsync()
{
// You need to add a reference to System.Net.Http to declare client.
HttpClient client = new HttpClient();
// GetStringAsync returns a Task<string>. That means that when you await the
// task you'll get a string (urlContents).
Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");
// You can do work here that doesn't rely on the string from GetStringAsync.
DoIndependentWork();
// The await operator suspends AccessTheWebAsync.
// - AccessTheWebAsync can't continue until getStringTask is complete.
// - Meanwhile, control returns to the caller of AccessTheWebAsync.
// - Control resumes here when getStringTask is complete.
// - The await operator then retrieves the string result from getStringTask.
string urlContents = await getStringTask;
// The return statement specifies an integer result.
// Any methods that are awaiting AccessTheWebAsync retrieve the length value.
return urlContents.Length;
}
Quoting:
If
AccessTheWebAsync
doesn't have any work that it can do between calling GetStringAsync and awaiting its completion, you can simplify your code by calling and awaiting in the following single statement.
string urlContents = await client.GetStringAsync();
More details are in the link.
You can create .war file back from your existing folder.
Using this command
cd /to/your/folder/location
jar -cvf my_web_app.war *
import java.util.*; public class Mult {
public static int[][] C;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter Row of Matrix A");
int Rowa = s.nextInt();
System.out.println("Enter Column of Matrix A");
int Cola = s.nextInt();
System.out.println("Enter Row of Matrix B");
int Rowb = s.nextInt();
System.out.println("Enter Column of Matrix B");
int Colb = s.nextInt();
int[][] A = new int[Rowa][Cola];
int[][] B = new int[Rowb][Colb];
C= new int[Rowa][Colb];
//int[][] C = new int;
System.out.println("Enter Values of Matrix A");
for(int i =0 ; i< A.length ; i++) {
for(int j = 0 ; j<A.length;j++) {
A[i][j] = s.nextInt();
}
}
System.out.println("Enter Values of Matrix B");
for(int i =0 ; i< B.length ; i++) {
for(int j = 0 ; j<B.length;j++) {
B[i][j] = s.nextInt();
}
}
if(Cola==Rowb) {
for(int i = 0;i < A.length;i++){
for(int j = 0;j < A.length;j++){
C[i][j]=0;
for(int k = 0;k < B.length;k++){
C[i][j] += A[i][k] * B[k][j];
}
}
}
}
else {
System.out.println("Cannot multiply");
}
// Printing matrix A
/*
for(int i =0 ; i< A.length ; i++) {
for(int j = 0 ; j<A.length;j++) {
System.out.print(A[i][j]+ "\t");
}
System.out.println();
}
*/
for(int i =0 ; i< A.length ; i++) {
for(int j = 0 ; j<A.length;j++) {
System.out.print(C[i][j]+ "\t");
}
System.out.println();
}
}
}
If you were resizing before uploading I just found out this http://www.plupload.com/
It does all the magic for you in any imaginable method.
Unfortunately HTML5 resize only is supported with Mozilla browser, but you can redirect other browsers to Flash and Silverlight.
I just tried it and it worked with my android!
I was using http://swfupload.org/ in flash, it does the job very well, but the resize size is very small. (cannot remember the limit) and does not go back to html4 when flash is not available.
You can use Object.values():
The
Object.values()
method returns an array of a given object's own enumerable property values, in the same order as that provided by afor...in
loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
and then use the indexOf() method:
The
indexOf()
method returns the first index at which a given element can be found in the array, or -1 if it is not present.
For example:
Object.values(obj).indexOf("test`") >= 0
A more verbose example is below:
var obj = {_x000D_
"a": "test1",_x000D_
"b": "test2"_x000D_
}_x000D_
_x000D_
_x000D_
console.log(Object.values(obj).indexOf("test1")); // 0_x000D_
console.log(Object.values(obj).indexOf("test2")); // 1_x000D_
_x000D_
console.log(Object.values(obj).indexOf("test1") >= 0); // true_x000D_
console.log(Object.values(obj).indexOf("test2") >= 0); // true _x000D_
_x000D_
console.log(Object.values(obj).indexOf("test10")); // -1_x000D_
console.log(Object.values(obj).indexOf("test10") >= 0); // false
_x000D_
A good practice would be based on readability, e.g.:
string str ("Test string");
for (int index = 0, auto it = str.begin(); it < str.end(); ++it)
cout << index++ << *it;
Or:
string str ("Test string");
for (int index = 0, auto it = str.begin(); it < str.end(); ++it, ++index)
cout << index << *it;
Or your original:
string str ("Test string");
int index = 0;
for (auto it = str.begin() ; it < str.end(); ++it, ++index)
cout << index << *it;
Etc. Whatever is easiest and cleanest to you.
It's not clear there is any one best practice as you'll need a counter variable somewhere. The question seems to be whether where you define it and how it is incremented works well for you.
Try setting the path of maven first through command prompt.
setpath.bat
Open the cmd
from the base window of the batch file.
The rest maven commands can be used once path is set through cmd
.
jsonb
in Postgres 9.4+You can use the same query as below, just with jsonb_array_elements()
.
But rather use the jsonb
"contains" operator @>
in combination with a matching GIN index on the expression data->'objects'
:
CREATE INDEX reports_data_gin_idx ON reports
USING gin ((data->'objects') jsonb_path_ops);
SELECT * FROM reports WHERE data->'objects' @> '[{"src":"foo.png"}]';
Since the key objects
holds a JSON array, we need to match the structure in the search term and wrap the array element into square brackets, too. Drop the array brackets when searching a plain record.
More explanation and options:
json
in Postgres 9.3+Unnest the JSON array with the function json_array_elements()
in a lateral join in the FROM
clause and test for its elements:
SELECT data::text, obj
FROM reports r, json_array_elements(r.data#>'{objects}') obj
WHERE obj->>'src' = 'foo.png';
The CTE (WITH
query) just substitutes for a table reports
.
Or, equivalent for just a single level of nesting:
SELECT *
FROM reports r, json_array_elements(r.data->'objects') obj
WHERE obj->>'src' = 'foo.png';
->>
, ->
and #>
operators are explained in the manual.
Both queries use an implicit JOIN LATERAL
.
Closely related:
These snippets all perform exactly the same thing:
element.on('click', function () { ... });
element.bind('click', function () { ... });
element.click(function () { ... });
However, they are very different from these, which all perform the same thing:
element.on('click', 'selector', function () { ... });
element.delegate('click', 'selector', function () { ... });
$('selector').live('click', function () { ... });
The second set of event handlers use event delegation and will work for dynamically added elements. Event handlers that use delegation are also much more performant. The first set will not work for dynamically added elements, and are much worse for performance.
jQuery's on()
function does not introduce any new functionality that did not already exist, it is just an attempt to standardize event handling in jQuery (you no longer have to decide between live, bind, or delegate).
If the rest of your system is OK with DateTimeOffset instead of DateTime, there's a really convenient feature:
long unixSeconds = DateTimeOffset.Now.ToUnixTimeSeconds();
ZXing is an open source project that can detect and parse a number of different barcodes. It can also generate QR-codes. (Only QR-codes, though).
There are a number of variants for different languages: ActionScript, Android (java), C++, C#, IPhone (Obj C), Java ME, Java SE, JRuby, JSP. Support for generating QR-codes comes with some of those: ActionScript, Android, C# and the Java variants.
Here is an example:
MySqlConnection con = new MySqlConnection(
"Server=ServerName;Database=DataBaseName;UID=username;Password=password");
MySqlCommand cmd = new MySqlCommand(
" INSERT Into Test (lat, long) VALUES ('"+OSGconv.deciLat+"','"+
OSGconv.deciLon+"')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Normally, that is not an error per se; it is a warning that the first file it found that matches the -lPI-Http
argument to the compiler/linker is not valid. The error occurs when no other library can be found with the right content.
So, you need to look to see whether /dvlpmnt/libPI-Http.a
is a library of 32-bit object files or of 64-bit object files - it will likely be 64-bit if you are compiling with the -m32
option. Then you need to establish whether there is an alternative libPI-Http.a
or libPI-Http.so
file somewhere else that is 32-bit. If so, ensure that the directory that contains it is listed in a -L/some/where
argument to the linker. If not, then you will need to obtain or build a 32-bit version of the library from somewhere.
To establish what is in that library, you may need to do:
mkdir junk
cd junk
ar x /dvlpmnt/libPI-Http.a
file *.o
cd ..
rm -fr junk
The 'file
' step tells you what type of object files are in the archive. The rest just makes sure you don't make a mess that can't be easily cleaned up.
I hide the warnings in the pink boxes by running the following code in a cell:
from IPython.display import HTML
HTML('''<script>
code_show_err=false;
function code_toggle_err() {
if (code_show_err){
$('div.output_stderr').hide();
} else {
$('div.output_stderr').show();
}
code_show_err = !code_show_err
}
$( document ).ready(code_toggle_err);
</script>
To toggle on/off output_stderr, click <a href="javascript:code_toggle_err()">here</a>.''')
First use
git pull https://github.com/username/repository master
and then try
git push -u origin master
The variable a is pointing at the object "Dog". It's best to think of the variable in Python as a tag. You can move the tag to different objects which is what you did when you changed a = "dog"
to a = "dog eats treats"
.
However, immutability refers to the object, not the tag.
If you tried a[1] = 'z'
to make "dog"
into "dzg"
, you would get the error:
TypeError: 'str' object does not support item assignment"
because strings don't support item assignment, thus they are immutable.
I found this solution to work on every device despite API level (even for < 11)
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
ComponentName cn = intent.getComponent();
Intent mainIntent = IntentCompat.makeRestartActivityTask(cn);
startActivity(mainIntent);
You can easily install update version if you use Anaconda by closing Spyder and then running the following command in a system terminal (Anaconda Prompt on Windows, xterm on Linux or Terminal.app on macOS):
conda install spyder= Your desire version
(For example, Version is 3.1)
conda install spyder=3.1
Or you can use pip with this command in a system terminal (cmd.exe on Windows, xterm on Linux or Terminal.app on macOS):
pip install --pre -U spyder
Note: Do not use this command if you are using Anaconda because it could break your installation.
I agree with thomaux that the initialization type checking error is a TypeScript bug. However, I still wanted to find a way to declare and initialize a Dictionary in a single statement with correct type checking. This implementation is longer, however it adds additional functionality such as a containsKey(key: string)
and remove(key: string)
method. I suspect that this could be simplified once generics are available in the 0.9 release.
First we declare the base Dictionary class and Interface. The interface is required for the indexer because classes cannot implement them.
interface IDictionary {
add(key: string, value: any): void;
remove(key: string): void;
containsKey(key: string): bool;
keys(): string[];
values(): any[];
}
class Dictionary {
_keys: string[] = new string[];
_values: any[] = new any[];
constructor(init: { key: string; value: any; }[]) {
for (var x = 0; x < init.length; x++) {
this[init[x].key] = init[x].value;
this._keys.push(init[x].key);
this._values.push(init[x].value);
}
}
add(key: string, value: any) {
this[key] = value;
this._keys.push(key);
this._values.push(value);
}
remove(key: string) {
var index = this._keys.indexOf(key, 0);
this._keys.splice(index, 1);
this._values.splice(index, 1);
delete this[key];
}
keys(): string[] {
return this._keys;
}
values(): any[] {
return this._values;
}
containsKey(key: string) {
if (typeof this[key] === "undefined") {
return false;
}
return true;
}
toLookup(): IDictionary {
return this;
}
}
Now we declare the Person specific type and Dictionary/Dictionary interface. In the PersonDictionary note how we override values()
and toLookup()
to return the correct types.
interface IPerson {
firstName: string;
lastName: string;
}
interface IPersonDictionary extends IDictionary {
[index: string]: IPerson;
values(): IPerson[];
}
class PersonDictionary extends Dictionary {
constructor(init: { key: string; value: IPerson; }[]) {
super(init);
}
values(): IPerson[]{
return this._values;
}
toLookup(): IPersonDictionary {
return this;
}
}
And here is a simple initialization and usage example:
var persons = new PersonDictionary([
{ key: "p1", value: { firstName: "F1", lastName: "L2" } },
{ key: "p2", value: { firstName: "F2", lastName: "L2" } },
{ key: "p3", value: { firstName: "F3", lastName: "L3" } }
]).toLookup();
alert(persons["p1"].firstName + " " + persons["p1"].lastName);
// alert: F1 L2
persons.remove("p2");
if (!persons.containsKey("p2")) {
alert("Key no longer exists");
// alert: Key no longer exists
}
alert(persons.keys().join(", "));
// alert: p1, p3
For Facebook share with an image without an API and using a #
to deep link into a sub page, the trick was to share the image as picture=
The variable mainUrl
would be http://yoururl.com/
var d1 = $('.targ .t1').text();
var d2 = $('.targ .t2').text();
var d3 = $('.targ .t3').text();
var d4 = $('.targ .t4').text();
var descript_ = d1 + ' ' + d2 + ' ' + d3 + ' ' + d4;
var descript = encodeURIComponent(descript_);
var imgUrl_ = 'path/to/mypic_'+id+'.jpg';
var imgUrl = mainUrl + encodeURIComponent(imgUrl_);
var shareLink = mainUrl + encodeURIComponent('mypage.html#' + id);
var fbShareLink = shareLink + '&picture=' + imgUrl + '&description=' + descript;
var twShareLink = 'text=' + descript + '&url=' + shareLink;
// facebook
$(".my-btn .facebook").off("tap click").on("tap click",function(){
var fbpopup = window.open("https://www.facebook.com/sharer/sharer.php?u=" + fbShareLink, "pop", "width=600, height=400, scrollbars=no");
return false;
});
// twitter
$(".my-btn .twitter").off("tap click").on("tap click",function(){
var twpopup = window.open("http://twitter.com/intent/tweet?" + twShareLink , "pop", "width=600, height=400, scrollbars=no");
return false;
});
I had the same problem in writing the Kafka producer program using java. This error is coming due to the wrong slf4j library. use below slf4j-simple maven dependency that will fix your problem.
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.6.1</version>
<scope>test</scope>
</dependency>
wget -r ftp://url
Work perfectly for Redhat and Ubuntu
It makes more sense to join the item with the orders than with the people !
SELECT
people.pe_name,
COUNT(distinct orders.ord_id) AS num_orders,
COUNT(items.item_id) AS num_items
FROM
people
INNER JOIN orders ON orders.pe_id = people.pe_id
INNER JOIN items ON items.ord_id = orders.ord_id
GROUP BY
people.pe_id;
Joining the items with the people provokes a lot of doublons. For example, the cake items in order 3 will be linked with the order 2 via the join between the people, and you don't want this to happen !!
So :
1- You need a good understanding of your schema. Items are link to orders, and not to people.
2- You need to count distinct orders for one person, else you will count as many items as orders.
maybe this help :
declare
@statement AS NVARCHAR(MAX)
,@text1 varchar(50)='hello'
,@text2 varchar(50)='world'
set @statement = '
select '''+@text1+''' + '' beautifull '' + ''' + @text2 + '''
'
exec sp_executesql @statement;
this is same as below :
select @text1 + ' beautifull ' + @text2
This is what I used to use a csv file into an array. Couldn't get the above answers to work, but this worked for me.
$(document).ready(function() {
"use strict";
$.ajax({
type: "GET",
url: "../files/icd10List.csv",
dataType: "text",
success: function(data) {processData(data);}
});
});
function processData(icd10Codes) {
"use strict";
var input = $.csv.toArrays(icd10Codes);
$("#test").append(input);
}
Used the jQuery-CSV Plug-in linked above.
Core Background implements the desired iOS 7 effect.
https://github.com/justinmfischer/core-background
Disclaimer: I am the author of this project
I was looking for a really simple way to get PHP to send a socket.io message to clients.
This doesn't require any additional PHP libraries - it just uses sockets.
Instead of trying to connect to the websocket interface like so many other solutions, just connect to the node.js server and use .on('data')
to receive the message.
Then, socket.io
can forward it along to clients.
Detect a connection from your PHP server in Node.js like this:
//You might have something like this - just included to show object setup
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.on("connection", function(s) {
//If connection is from our server (localhost)
if(s.remoteAddress == "::ffff:127.0.0.1") {
s.on('data', function(buf) {
var js = JSON.parse(buf);
io.emit(js.msg,js.data); //Send the msg to socket.io clients
});
}
});
Here's the incredibly simple php code - I wrapped it in a function - you may come up with something better.
Note that 8080
is the port to my Node.js server - you may want to change.
function sio_message($message, $data) {
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$result = socket_connect($socket, '127.0.0.1', 8080);
if(!$result) {
die('cannot connect '.socket_strerror(socket_last_error()).PHP_EOL);
}
$bytes = socket_write($socket, json_encode(Array("msg" => $message, "data" => $data)));
socket_close($socket);
}
You can use it like this:
sio_message("chat message","Hello from PHP!");
You can also send arrays which are converted to json and passed along to clients.
sio_message("DataUpdate",Array("Data1" => "something", "Data2" => "something else"));
This is a useful way to "trust" that your clients are getting legitimate messages from the server.
You can also have PHP pass along database updates without having hundreds of clients query the database.
I wish I'd found this sooner - hope this helps!
You can find what you need on infochimps.org.
They have a list of 350,000 simple (ie non-compound) words available for free download.
Word List - 350,000+ Simple English Words
Regarding other languages, you might want to poke around on Wiktionary. Here is a link to all the database backups - the information isnt organized so likely but if they have a language, you can download the data in SQL format.
With the pandas
library, this is as easy as using two commands!
pandas.read_json()
To convert a JSON string to a pandas object (either a series or dataframe). Then, assuming the results were stored as df
:
df.to_csv()
Which can either return a string or write directly to a csv-file.
Based on the verbosity of previous answers, we should all thank pandas for the shortcut.
Keep the files in the same directory and use package main
in all files.
myproj/
your-program/
main.go
lib.go
Then run:
~/myproj/your-program$ go build && ./your-program
This is not possible from HTML on. The closest what you can get is the accept-charset
attribute of the <form>
. Only MSIE browser adheres that, but even then it is doing it wrong (e.g. CP1252 is actually been used when it says that it has sent ISO-8859-1). Other browsers are fully ignoring it and they are using the charset as specified in the Content-Type
header of the response. Setting the character encoding right is basically fully the responsiblity of the server side. The client side should just send it back in the same charset as the server has sent the response in.
To the point, you should really configure the character encoding stuff entirely from the server side on. To overcome the inability to edit URIEncoding
attribute, someone here on SO wrote a (complex) filter: Detect the URI encoding automatically in Tomcat. You may find it useful as well (note: I haven't tested it).
Update:
Noted should be that the meta tag as given in your question is ignored when the content is been transferred over HTTP. Instead, the HTTP response Content-Type
header will be used to determine the content type and character encoding. You can determine the HTTP header with for example Firebug, in the Net panel.
Use this, and you will find all informations at http://www.w3schools.com/html/html5_geolocation.asp
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
I think what you are looking for, if you are looking for something in a dictionary, is the setdefault
method:
(Pdb) we=dict()
(Pdb) we.setdefault('e',14)
14
(Pdb) we['e']
14
(Pdb) we['r']="p"
(Pdb) we.setdefault('r','jeff')
'p'
(Pdb) we['r']
'p'
(Pdb) we[e]
*** NameError: name 'e' is not defined
(Pdb) we['e']
14
(Pdb) we['q2']
*** KeyError: 'q2' (Pdb)
The important thing to note in my example is that the setdefault
method changes the dictionary if and only if the key that the setdefault
method refers to is not present.
But this is obviously performing a 'string' comparison
No. The string will be automatically cast into a DATETIME value.
See 11.2. Type Conversion in Expression Evaluation.
When an operator is used with operands of different types, type conversion occurs to make the operands compatible. Some conversions occur implicitly. For example, MySQL automatically converts numbers to strings as necessary, and vice versa.
if you want to change the only icon of radio button then you can only add android:button="@drawable/ic_launcher"
to your radio button and for making sensitive on click then you have to use the selector
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/image_what_you_want_on_select_state" android:state_checked="true"/>
<item android:drawable="@drawable/image_what_you_want_on_un_select_state" android:state_checked="false"/>
</selector>
and set to your radio android:background="@drawable/name_of_selector"
This answer relevant for Vue.js version 2
<th
class="initial "
v-on:click="myFilter"
v-bind:class="{ active: isActive }"
>
<span class="wkday">M</span>
</th>
The rest of the answer by Douglas is still applicable (setting up the new Vue instance with isActive: false
, etc).
Relevant docs: https://vuejs.org/v2/guide/class-and-style.html#Object-Syntax and https://vuejs.org/v2/guide/events.html#Method-Event-Handlers
If you are using linux and faced such problem during creating link, try to change jar file path of original jmeter file.
+ java -server -XX:+HeapDumpOnOutOfMemoryError -Xms512m -Xmx512m -XX:NewSize=128m -XX:MaxNewSize=128m -XX:MaxTenuringThreshold=2 -XX:PermSize=64m -XX:MaxPermSize=128m -XX:+CMSClassUnloadingEnabled -jar ./ApacheJMeter.jar -help
Change to:
java $ARGS $JVM_ARGS -jar "/opt/apache-jmeter-2.11/bin/ApacheJMeter.jar" "$@"
Beware of your environment!
For example, this doesn’t seem to work in ECMAscript
y ^= x ^= y ^= x;
But this does
x ^= y ^= x; y ^= x;
My advise? Assume as little as possible.
You should be able to transfer the Application to another Username. You would need all your old user information to transfer it. The application would remove it's self from old account to new account. Also you could put a limit on how many times you where allowed to transfer it. If you transfer it to the application could expire after a year and force to buy update.
PHP_EOL is a predefined constant in PHP since PHP 4.3.10 and PHP 5.0.2. See the manual posting:
Using this will save you extra coding on cross platform developments.
IE.
$data = 'some data'.PHP_EOL;
$fp = fopen('somefile', 'a');
fwrite($fp, $data);
If you looped through this twice you would see in 'somefile':
some data
some data
borderColor on any view(or UIView Subclass) could also be set using storyboard with a little bit of coding and this approach could be really handy if you're setting border color on multiple UI Objects.
Below are the steps how to achieve it,
P.S: Remember, Categories can't have stored properties. 'borderUIColor' is used as a calculated property, just as a reference to achieve what we're focusing on.
Please have a look at the below code sample;
Objective C:
Interface File:
#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>
@interface CALayer (BorderProperties)
// This assigns a CGColor to borderColor.
@property (nonatomic, assign) UIColor* borderUIColor;
@end
Implementation File:
#import "CALayer+BorderProperties.h"
@implementation CALayer (BorderProperties)
- (void)setBorderUIColor:(UIColor *)color {
self.borderColor = color.CGColor;
}
- (UIColor *)borderUIColor {
return [UIColor colorWithCGColor:self.borderColor];
}
@end
Swift 2.0:
extension CALayer {
var borderUIColor: UIColor {
set {
self.borderColor = newValue.CGColor
}
get {
return UIColor(CGColor: self.borderColor!)
}
}
}
And finally go to your storyboard/XIB, follow the remaining steps;
You've to set layer.borderWidth property value to at least 1 to see the border color.
Build and Run. Happy Coding. :)
What if you are using this to determine the current selector to find its children
so this holds: <ol>
then there is <li>
s under how to write a selector
var count = $(this+"> li").length;
wont work..
Couldnt get the TEXT() formula to work
Easiest solution was to copy paste into Notepad and back into Excel with the column set to Text before pasting back
Or you can do the same with a formula like this
=DAY(A2)&"/"&MONTH(A2)&"/"&YEAR(A2)& " "&HOUR(B2)&":"&MINUTE(B2)&":"&SECOND(B2)
The sed way,
sed -e ':a; N; $!ba; s/\n/,/g'
# :a # label called 'a'
# N # append next line into Pattern Space (see info sed)
# $!ba # if it's the last line ($) do not (!) jump to (b) label :a (a) - break loop
# s/\n/,/g # any substitution you want
Note:
This is linear in complexity, substituting only once after all lines are appended into sed's Pattern Space.
@AnandRajaseka's answer, and some other similar answers, such as here, are O(n²), because sed has to do substitute every time a new line is appended into the Pattern Space.
To compare,
seq 1 100000 | sed ':a; N; $!ba; s/\n/,/g' | head -c 80
# linear, in less than 0.1s
seq 1 100000 | sed ':a; /$/N; s/\n/,/; ta' | head -c 80
# quadratic, hung
In addition to grants, you can try creating synonyms. It will avoid the need for specifying the table owner schema every time.
From the connecting schema:
CREATE SYNONYM pi_int FOR pct.pi_int;
Then you can query pi_int
as:
SELECT * FROM pi_int;
Here's a complete solution for Swagger with Spring Security. We probably want to only enable Swagger in our development and QA environment and disable it in the production environment. So, I am using a property (prop.swagger.enabled
) as a flag to bypass spring security authentication for swagger-ui only in development/qa environment.
@Configuration
@EnableSwagger2
public class SwaggerConfiguration extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {
@Value("${prop.swagger.enabled:false}")
private boolean enableSwagger;
@Bean
public Docket SwaggerConfig() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(enableSwagger)
.select()
.apis(RequestHandlerSelectors.basePackage("com.your.controller"))
.paths(PathSelectors.any())
.build();
}
@Override
public void configure(WebSecurity web) throws Exception {
if (enableSwagger)
web.ignoring().antMatchers("/v2/api-docs",
"/configuration/ui",
"/swagger-resources/**",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (enableSwagger) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
}
As I discussed here ,
if you want to pass custom JSON object to MVC action then you can use this solution, it works like a charm.
public string GetData() {
// InputStream contains the JSON object you've sent
String jsonString = new StreamReader(this.Request.InputStream).ReadToEnd();
// Deserialize it to a dictionary
var dic =
Newtonsoft.Json.JsonConvert.DeserializeObject < Dictionary < String,
dynamic >> (jsonString);
string result = "";
result += dic["firstname"] + dic["lastname"];
// You can even cast your object to their original type because of 'dynamic' keyword
result += ", Age: " + (int) dic["age"];
if ((bool) dic["married"])
result += ", Married";
return result;
}
The real benefit of this solution is that you don't require to define a new class for each combination of arguments and beside that, you can cast your objects to their original types easily.
You can use a helper method like this to facilitate your job:
public static Dictionary < string, dynamic > GetDic(HttpRequestBase request) {
String jsonString = new StreamReader(request.InputStream).ReadToEnd();
return Newtonsoft.Json.JsonConvert.DeserializeObject < Dictionary < string, dynamic >> (jsonString);
}
I tried many ways but this works.
Sample code is availalbe in DBCC SHRINKFILE
USE DBName;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE DBName
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (DBName_log, 1); --File name SELECT * FROM sys.database_files; query to get the file name
GO
-- Reset the database recovery model.
ALTER DATABASE DBName
SET RECOVERY FULL;
GO
No need to convert it in a string by using json.dumps()
r = {'is_claimed': 'True', 'rating': 3.5}
file.write(r['is_claimed'])
file.write(str(r['rating']))
You can get the values directly from the dict object.
::-webkit-input-placeholder {
font-size: 14px;
color: #d0cdfa;
text-transform: uppercase;
text-transform: uppercase;
text-align: center;
font-weight: bold;
}
:-moz-placeholder {
font-size:14px;
color: #d0cdfa;
text-transform: uppercase;
text-align: center;
font-weight: bold;
}
::-moz-placeholder {
font-size: 14px;
color: #d0cdfa;
text-transform: uppercase;
text-align: center;
font-weight: bold;
}
:-ms-input-placeholder {
font-size: 14px;
color: #d0cdfa;
text-transform: uppercase;
text-align: center;
font-weight: bold;
}
In straight-up computer programming, there is no such thing as "printing bold text". Let's back up a bit and understand that your text is a string of bytes and bytes are just bundles of bits. To the computer, here's your "hello" text, in binary.
0110100001100101011011000110110001101111
Each one or zero is a bit. Every eight bits is a byte. Every byte is, in a string like that in Python 2.x, one letter/number/punctuation item (called a character). So for example:
01101000 01100101 01101100 01101100 01101111
h e l l o
The computer translates those bits into letters, but in a traditional string (called an ASCII string), there is nothing to indicate bold text. In a Unicode string, which works a little differently, the computer can support international language characters, like Chinese ones, but again, there's nothing to say that some text is bold and some text is not. There's also no explicit font, text size, etc.
In the case of printing HTML, you're still outputting a string. But the computer program reading that string (a web browser) is programmed to interpret text like this is <b>bold</b>
as "this is bold" when it converts your string of letters into pixels on the screen. If all text were WYSIWYG, the need for HTML itself would be mitigated -- you would just select text in your editor and bold it instead of typing out the HTML.
Other programs use different systems -- a lot of answers explained a completely different system for printing bold text on terminals. I'm glad you found out how to do what you want to do, but at some point, you'll want to understand how strings and memory work.
I know that this post is quite old, but for reference I fixed this issue by updating the version of datepicker
It is worth trying that too to avoid hours of debugging.
The most readable way is
x = 10 if a > b else 11
but you can use and
and or
, too:
x = a > b and 10 or 11
The "Zen of Python" says that "readability counts", though, so go for the first way.
Also, the and-or trick will fail if you put a variable instead of 10
and it evaluates to False
.
However, if more than the assignment depends on this condition, it will be more readable to write it as you have:
if A[i] > B[j]:
x = A[i]
i += 1
else:
x = A[j]
j += 1
unless you put i
and j
in a container. But if you show us why you need it, it may well turn out that you don't.
I hope this helps!
The difference between .dylib and .so on mac os x is how they are compiled. For .so files you use -shared and for .dylib you use -dynamiclib. Both .so and .dylib are interchangeable as dynamic library files and either have a type as DYLIB or BUNDLE. Heres the readout for different files showing this.
libtriangle.dylib:
Mach header
magic cputype cpusubtype caps filetype ncmds sizeofcmds flags
MH_MAGIC_64 X86_64 ALL 0x00 DYLIB 17 1368 NOUNDEFS DYLDLINK TWOLEVEL NO_REEXPORTED_DYLIBS
libtriangle.so:
Mach header
magic cputype cpusubtype caps filetype ncmds sizeofcmds flags
MH_MAGIC_64 X86_64 ALL 0x00 DYLIB 17 1256 NOUNDEFS DYLDLINK TWOLEVEL NO_REEXPORTED_DYLIBS
triangle.so:
Mach header
magic cputype cpusubtype caps filetype ncmds sizeofcmds flags
MH_MAGIC_64 X86_64 ALL 0x00 BUNDLE 16 1696 NOUNDEFS DYLDLINK TWOLEVEL
The reason the two are equivalent on Mac OS X is for backwards compatibility with other UNIX OS programs that compile to the .so file type.
Compilation notes: whether you compile a .so file or a .dylib file you need to insert the correct path into the dynamic library during the linking step. You do this by adding -install_name and the file path to the linking command. If you dont do this you will run into the problem seen in this post: Mac Dynamic Library Craziness (May be Fortran Only).
You could also consider going parallel, especially if you don't care about the sequence and more about getting something done for each item:
SomeIEnumerable<T>.AsParallel().ForAll( Action<T> / Delegate / Lambda )
For example:
var numbers = new[] { 1, 2, 3, 4, 5 };
numbers.AsParallel().ForAll( Console.WriteLine );
HTH.
See: http://www.postgresql.org/docs/9.1/static/arrays.html
If your non-native driver still does not allow you to pass arrays, then you can:
pass a string representation of an array (which your stored procedure can then parse into an array -- see string_to_array
)
CREATE FUNCTION my_method(TEXT) RETURNS VOID AS $$
DECLARE
ids INT[];
BEGIN
ids = string_to_array($1,',');
...
END $$ LANGUAGE plpgsql;
then
SELECT my_method(:1)
with :1 = '1,2,3,4'
rely on Postgres itself to cast from a string to an array
CREATE FUNCTION my_method(INT[]) RETURNS VOID AS $$
...
END $$ LANGUAGE plpgsql;
then
SELECT my_method('{1,2,3,4}')
choose not to use bind variables and issue an explicit command string with all parameters spelled out instead (make sure to validate or escape all parameters coming from outside to avoid SQL injection attacks.)
CREATE FUNCTION my_method(INT[]) RETURNS VOID AS $$
...
END $$ LANGUAGE plpgsql;
then
SELECT my_method(ARRAY [1,2,3,4])
Element
inherits from Node
, in the same way that Dog
inherits from Animal
.
An Element
object "is-a" Node
object, in the same way that a Dog
object "is-a" Animal
object.
Node
is for implementing a tree structure, so its methods are for firstChild
, lastChild
, childNodes
, etc. It is more of a class for a generic tree structure.
And then, some Node
objects are also Element
objects. Element
inherits from Node
. Element
objects actually represents the objects as specified in the HTML file by the tags such as <div id="content"></div>
. The Element
class define properties and methods such as attributes
, id
, innerHTML
, clientWidth
, blur()
, and focus()
.
Some Node
objects are text nodes and they are not Element
objects. Each Node
object has a nodeType
property that indicates what type of node it is, for HTML documents:
1: Element node
3: Text node
8: Comment node
9: the top level node, which is document
We can see some examples in the console:
> document instanceof Node
true
> document instanceof Element
false
> document.firstChild
<html>...</html>
> document.firstChild instanceof Node
true
> document.firstChild instanceof Element
true
> document.firstChild.firstChild.nextElementSibling
<body>...</body>
> document.firstChild.firstChild.nextElementSibling === document.body
true
> document.firstChild.firstChild.nextSibling
#text
> document.firstChild.firstChild.nextSibling instanceof Node
true
> document.firstChild.firstChild.nextSibling instanceof Element
false
> Element.prototype.__proto__ === Node.prototype
true
The last line above shows that Element
inherits from Node
. (that line won't work in IE due to __proto__
. Will need to use Chrome, Firefox, or Safari).
By the way, the document
object is the top of the node tree, and document
is a Document
object, and Document
inherits from Node
as well:
> Document.prototype.__proto__ === Node.prototype
true
Here are some docs for the Node and Element classes:
https://developer.mozilla.org/en-US/docs/DOM/Node
https://developer.mozilla.org/en-US/docs/DOM/Element
It's nice that Go has a Duration
type -- having explicitly defined units can prevent real-world problems.
And because of Go's strict type rules, you can't multiply a Duration by an integer -- you must use a cast in order to multiply common types.
/*
MultiplyDuration Hide semantically invalid duration math behind a function
*/
func MultiplyDuration(factor int64, d time.Duration) time.Duration {
return time.Duration(factor) * d // method 1 -- multiply in 'Duration'
// return time.Duration(factor * int64(d)) // method 2 -- multiply in 'int64'
}
The official documentation demonstrates using method #1:
To convert an integer number of units to a Duration, multiply:
seconds := 10
fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
But, of course, multiplying a duration by a duration should not produce a duration -- that's nonsensical on the face of it. Case in point, 5 milliseconds times 5 milliseconds produces 6h56m40s
. Attempting to square 5 seconds results in an overflow (and won't even compile if done with constants).
By the way, the int64
representation of Duration
in nanoseconds "limits the largest representable duration to approximately 290 years", and this indicates that Duration
, like int64
, is treated as a signed value: (1<<(64-1))/(1e9*60*60*24*365.25) ~= 292
, and that's exactly how it is implemented:
// A Duration represents the elapsed time between two instants
// as an int64 nanosecond count. The representation limits the
// largest representable duration to approximately 290 years.
type Duration int64
So, because we know that the underlying representation of Duration
is an int64
, performing the cast between int64
and Duration
is a sensible NO-OP -- required only to satisfy language rules about mixing types, and it has no effect on the subsequent multiplication operation.
If you don't like the the casting for reasons of purity, bury it in a function call as I have shown above.
String str = "to";
str.replace("to", "xyz");
Just try it :)
In react native, I had the error not show maps and close app, run adb logcat and show error within console:
java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion
fix it by adding within androidManifest.xml
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />
Mostly stylistic these days. When C was young, there was no such thing as a const variable. So if you used a variable instead of a #define
, you had no guarantee that somebody somewhere wouldn't change the value of it, causing havoc throughout your program.
In the old days, FORTRAN passed even constants to subroutines by reference, and it was possible (and headache inducing) to change the value of a constant like '2' to be something different. One time, this happened in a program I was working on, and the only hint we had that something was wrong was we'd get an ABEND (abnormal end) when the program hit the STOP 999
that was supposed to end it normally.
A more up to date solution, for encoding:
// This is the same for all of the below, and
// you probably won't need it except for debugging
// in most cases.
function bytesToHex(bytes) {
return Array.from(
bytes,
byte => byte.toString(16).padStart(2, "0")
).join("");
}
// You almost certainly want UTF-8, which is
// now natively supported:
function stringToUTF8Bytes(string) {
return new TextEncoder().encode(string);
}
// But you might want UTF-16 for some reason.
// .charCodeAt(index) will return the underlying
// UTF-16 code-units (not code-points!), so you
// just need to format them in whichever endian order you want.
function stringToUTF16Bytes(string, littleEndian) {
const bytes = new Uint8Array(string.length * 2);
// Using DataView is the only way to get a specific
// endianness.
const view = new DataView(bytes.buffer);
for (let i = 0; i != string.length; i++) {
view.setUint16(i, string.charCodeAt(i), littleEndian);
}
return bytes;
}
// And you might want UTF-32 in even weirder cases.
// Fortunately, iterating a string gives the code
// points, which are identical to the UTF-32 encoding,
// though you still have the endianess issue.
function stringToUTF32Bytes(string, littleEndian) {
const codepoints = Array.from(string, c => c.codePointAt(0));
const bytes = new Uint8Array(codepoints.length * 4);
// Using DataView is the only way to get a specific
// endianness.
const view = new DataView(bytes.buffer);
for (let i = 0; i != codepoints.length; i++) {
view.setUint32(i, codepoints[i], littleEndian);
}
return bytes;
}
Examples:
bytesToHex(stringToUTF8Bytes("hello ?? "))
// "68656c6c6f20e6bca2e5ad9720f09f918d"
bytesToHex(stringToUTF16Bytes("hello ?? ", false))
// "00680065006c006c006f00206f225b570020d83ddc4d"
bytesToHex(stringToUTF16Bytes("hello ?? ", true))
// "680065006c006c006f002000226f575b20003dd84ddc"
bytesToHex(stringToUTF32Bytes("hello ?? ", false))
// "00000068000000650000006c0000006c0000006f0000002000006f2200005b57000000200001f44d"
bytesToHex(stringToUTF32Bytes("hello ?? ", true))
// "68000000650000006c0000006c0000006f00000020000000226f0000575b0000200000004df40100"
For decoding, it's generally a lot simpler, you just need:
function hexToBytes(hex) {
const bytes = new Uint8Array(hex.length / 2);
for (let i = 0; i !== bytes.length; i++) {
bytes[i] = parseInt(hex.substr(i * 2, 2), 16);
}
return bytes;
}
then use the encoding parameter of TextDecoder
:
// UTF-8 is default
new TextDecoder().decode(hexToBytes("68656c6c6f20e6bca2e5ad9720f09f918d"));
// but you can also use:
new TextDecoder("UTF-16LE").decode(hexToBytes("680065006c006c006f002000226f575b20003dd84ddc"))
new TextDecoder("UTF-16BE").decode(hexToBytes("00680065006c006c006f00206f225b570020d83ddc4d"));
// "hello ?? "
Here's the list of allowed encoding names: https://www.w3.org/TR/encoding/#names-and-labels
You might notice UTF-32 is not on that list, which is a pain, so:
function bytesToStringUTF32(bytes, littleEndian) {
const view = new DataView(bytes.buffer);
const codepoints = new Uint32Array(view.byteLength / 4);
for (let i = 0; i !== codepoints.length; i++) {
codepoints[i] = view.getUint32(i * 4, littleEndian);
}
return String.fromCodePoint(...codepoints);
}
Then:
bytesToStringUTF32(hexToBytes("00000068000000650000006c0000006c0000006f0000002000006f2200005b57000000200001f44d"), false)
bytesToStringUTF32(hexToBytes("68000000650000006c0000006c0000006f00000020000000226f0000575b0000200000004df40100"), true)
// "hello ?? "
I add custom commands to a environment evoked in a CMD after starting services... I haven't done it with postgres, but with Oracle:
#set up var with noop command
RUN export POST_START_CMDS=":"
RUN mkdir /scripts
ADD script.sql /scripts
CMD service oracle-xe start; $POST_START_CMDS; tail -f /var/log/dmesg
and start with
docker run -d ... -e POST_START_CMDS="su - oracle -c 'sqlplus @/scripts/script' " <image>
.
Something like that should be what you need
private void button1_Click(object sender, RoutedEventArgs e)
{
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
// Set filter for file extension and default file extension
dlg.DefaultExt = ".png";
dlg.Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif";
// Display OpenFileDialog by calling ShowDialog method
Nullable<bool> result = dlg.ShowDialog();
// Get the selected file name and display in a TextBox
if (result == true)
{
// Open document
string filename = dlg.FileName;
textBox1.Text = filename;
}
}
My Expected code :
$('#my-select').val('').change();
working perfectly thank to @PanPipes for the usefull one.
Try
sSource = sSource.replaceAll("\\\\", "");
Edit : Ok even in stackoverflow there is backslash escape... You need to have four backslashes in your replaceAll first String argument...
The reason of this is because backslash is considered as an escape character for special characters (like \n for instance).
Moreover replaceAll first arg is a regular expression that also use backslash as escape sequence.
So for the regular expression you need to pass 2 backslash. To pass those two backslashes by a java String to the replaceAll, you also need to escape both backslashes.
That drives you to have four backslashes for your expression! That's the beauty of regex in java ;)
If you want to avoid tuples, another way is by calling the first
, one
or all
methods:
query = db.engine.execute("SELECT * FROM blogs "
"WHERE id = 1 ")
assert query.first().name == "Welcome to my blog"
tldr: there is simply no way to do that; if you are trying to do that, you get LocalDateTime wrong.
The reason is that LocalDateTime does not record Time Zone after instances are created. You cannot convert a date time without time zone to another date time based on a specific time zone.
As a matter of fact, LocalDateTime.now() should never be called in production code unless your purpose is getting random results. When you construct a LocalDateTime instance like that, this instance contains date time ONLY based on current server's time zone, which means this piece of code will generate different result if it is running a server with a different time zone config.
LocalDateTime can simplify date calculating. If you want a real universally usable data time, use ZonedDateTime or OffsetDateTime: https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html.
Inline style only for clarity here. Use a real CSS stylesheet.
<!-- First, your background image is a DIV with a background
image style applied, not a IMG tag. -->
<div style="background-image:url(YourBackgroundImage);">
<!-- Second, create a placeholder div to assist in positioning
the other images. This is relative to the background div. -->
<div style="position: relative; left: 0; top: 0;">
<!-- Now you can place your IMG tags, and position them relative
to the container we just made -->
<img src="YourForegroundImage" style="position: relative; top: 0; left: 0;"/>
</div>
</div>
As the message error says, you need to Increase the length of your column to fit the length of the data you are trying to insert (0000-00-00)
EDIT 1:
Following your comment, I run a test table:
mysql> create table testDate(id int(2) not null auto_increment, pdd date default null, primary key(id));
Query OK, 0 rows affected (0.20 sec)
Insertion:
mysql> insert into testDate values(1,'0000-00-00');
Query OK, 1 row affected (0.06 sec)
EDIT 2:
So, aparently you want to insert a NULL value to pdd
field as your comment states ?
You can do that in 2 ways like this:
Method 1:
mysql> insert into testDate values(2,'');
Query OK, 1 row affected, 1 warning (0.06 sec)
Method 2:
mysql> insert into testDate values(3,NULL);
Query OK, 1 row affected (0.07 sec)
EDIT 3:
You failed to change the default value of pdd
field. Here is the syntax how to do it (in my case, I set it to NULL in the start, now I will change it to NOT NULL)
mysql> alter table testDate modify pdd date not null;
Query OK, 3 rows affected, 1 warning (0.60 sec)
Records: 3 Duplicates: 0 Warnings: 1
For this format (assuming datepart has the format dd-mm-yyyy) in plain javascript use dateString2Date
.
[Edit] Added an ES6 utility method to parse a date string using a format string parameter (format
) to inform the method about the position of date/month/year in the input string.
var result = document.querySelector('#result');_x000D_
_x000D_
result.textContent = _x000D_
`*Fixed\ndateString2Date('01-01-2016 00:03:44'):\n => ${_x000D_
dateString2Date('01-01-2016 00:03:44')}`;_x000D_
_x000D_
result.textContent += _x000D_
`\n\n*With formatting\ntryParseDateFromString('01-01-2016 00:03:44', 'dmy'):\n => ${_x000D_
tryParseDateFromString('01-01-2016 00:03:44', "dmy").toUTCString()}`;_x000D_
_x000D_
result.textContent += _x000D_
`\n\nWith formatting\ntryParseDateFromString('03/01/2016', 'mdy'):\n => ${_x000D_
tryParseDateFromString('03/01/1943', "mdy").toUTCString()}`;_x000D_
_x000D_
// fixed format dd-mm-yyyy_x000D_
function dateString2Date(dateString) {_x000D_
var dt = dateString.split(/\-|\s/);_x000D_
return new Date(dt.slice(0,3).reverse().join('-') + ' ' + dt[3]);_x000D_
}_x000D_
_x000D_
// multiple formats (e.g. yyyy/mm/dd or mm-dd-yyyy etc.)_x000D_
function tryParseDateFromString(dateStringCandidateValue, format = "ymd") {_x000D_
if (!dateStringCandidateValue) { return null; }_x000D_
let mapFormat = format_x000D_
.split("")_x000D_
.reduce(function (a, b, i) { a[b] = i; return a;}, {});_x000D_
const dateStr2Array = dateStringCandidateValue.split(/[ :\-\/]/g);_x000D_
const datePart = dateStr2Array.slice(0, 3);_x000D_
let datePartFormatted = [_x000D_
+datePart[mapFormat.y],_x000D_
+datePart[mapFormat.m]-1,_x000D_
+datePart[mapFormat.d] ];_x000D_
if (dateStr2Array.length > 3) {_x000D_
dateStr2Array.slice(3).forEach(t => datePartFormatted.push(+t));_x000D_
}_x000D_
// test date validity according to given [format]_x000D_
const dateTrial = new Date(Date.UTC.apply(null, datePartFormatted));_x000D_
return dateTrial && dateTrial.getFullYear() === datePartFormatted[0] &&_x000D_
dateTrial.getMonth() === datePartFormatted[1] &&_x000D_
dateTrial.getDate() === datePartFormatted[2]_x000D_
? dateTrial :_x000D_
null;_x000D_
}
_x000D_
<pre id="result"></pre>
_x000D_
As of now (October 2017) Google has implemented a specific property to handle the zooming/scrolling, called gestureHandling
. Its purpose is to handle mobile devices operation, but it modifies the behaviour for desktop browsers as well. Here it is from official documentation:
function initMap() { var locationRio = {lat: -22.915, lng: -43.197}; var map = new google.maps.Map(document.getElementById('map'), { zoom: 13, center: locationRio, gestureHandling: 'none' });
The available values for gestureHandling are:
'greedy'
: The map always pans (up or down, left or right) when the user swipes (drags on) the screen. In other words, both a one-finger swipe and a two-finger swipe cause the map to pan.'cooperative'
: The user must swipe with one finger to scroll the page and two fingers to pan the map. If the user swipes the map with one finger, an overlay appears on the map, with a prompt telling the user to use two fingers to move the map. On desktop applications, users can zoom or pan the map by scrolling while pressing a modifier key (the ctrl or ? key).'none'
: This option disables panning and pinching on the map for mobile devices, and dragging of the map on desktop devices.'auto'
(default): Depending on whether the page is scrollable, the Google Maps JavaScript API sets the gestureHandling property to either'cooperative'
or'greedy'
In short, you can easily force the setting to "always zoomable" ('greedy'
), "never zoomable" ('none'
), or "user must press CRTL/? to enable zoom" ('cooperative'
).
In doubt change your editor to make tabs and spaces visible. It is also a very good idea to have the editor resolve all tabs to 4 spaces.
In case on windows 7 gacutil.exe (to put assembly in GAC) and sn.exe(To ensure uniqueness of assembly) resides at C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin
Then go to the path of gacutil as shown below execute the below command after replacing path of your assembly
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin>gacutil /i "replace with path of your assembly to be put into GAC"
Try this: .aspx page
<td>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True"OnTextChanged="TextBox1_TextChanged"></asp:TextBox>
<asp:AutoCompleteExtender ServiceMethod="GetCompletionList" MinimumPrefixLength="1"
CompletionInterval="10" EnableCaching="false" CompletionSetCount="1" TargetControlID="TextBox1"
ID="AutoCompleteExtender1" runat="server" FirstRowSelected="false">
</asp:AutoCompleteExtender>
Now To auto populate from database :
public static List<string> GetCompletionList(string prefixText, int count)
{
return AutoFillProducts(prefixText);
}
private static List<string> AutoFillProducts(string prefixText)
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
using (SqlCommand com = new SqlCommand())
{
com.CommandText = "select ProductName from ProdcutMaster where " + "ProductName like @Search + '%'";
com.Parameters.AddWithValue("@Search", prefixText);
com.Connection = con;
con.Open();
List<string> countryNames = new List<string>();
using (SqlDataReader sdr = com.ExecuteReader())
{
while (sdr.Read())
{
countryNames.Add(sdr["ProductName"].ToString());
}
}
con.Close();
return countryNames;
}
}
}
Now:create a stored Procedure that fetches the Product details depending on the selected product from the Auto Complete Text Box.
Create Procedure GetProductDet
(
@ProductName varchar(50)
)
as
begin
Select BrandName,warranty,Price from ProdcutMaster where ProductName=@ProductName
End
Create a function name to get product details ::
private void GetProductMasterDet(string ProductName)
{
connection();
com = new SqlCommand("GetProductDet", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@ProductName", ProductName);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds=new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
con.Close();
//Binding TextBox From dataTable
txtbrandName.Text =dt.Rows[0]["BrandName"].ToString();
txtwarranty.Text = dt.Rows[0]["warranty"].ToString();
txtPrice.Text = dt.Rows[0]["Price"].ToString();
}
Auto post back should be true
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>
Now, Just call this function
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
//calling method and Passing Values
GetProductMasterDet(TextBox1.Text);
}
The absolutely best way is neither of the 2, but the 3rd. The first parameter to encode
defaults to 'utf-8'
ever since Python 3.0. Thus the best way is
b = mystring.encode()
This will also be faster, because the default argument results not in the string "utf-8"
in the C code, but NULL
, which is much faster to check!
Here be some timings:
In [1]: %timeit -r 10 'abc'.encode('utf-8')
The slowest run took 38.07 times longer than the fastest.
This could mean that an intermediate result is being cached.
10000000 loops, best of 10: 183 ns per loop
In [2]: %timeit -r 10 'abc'.encode()
The slowest run took 27.34 times longer than the fastest.
This could mean that an intermediate result is being cached.
10000000 loops, best of 10: 137 ns per loop
Despite the warning the times were very stable after repeated runs - the deviation was just ~2 per cent.
Using encode()
without an argument is not Python 2 compatible, as in Python 2 the default character encoding is ASCII.
>>> 'äöä'.encode()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
if ($inputs['type'] == 'attach') {
The code is valid, but it expects the function parameter $inputs
to be an array. The "Illegal string offset" warning when using $inputs['type']
means that the function is being passed a string instead of an array. (And then since a string offset is a number, 'type'
is not suitable.)
So in theory the problem lies elsewhere, with the caller of the code not providing a correct parameter.
However, this warning message is new to PHP 5.4. Old versions didn't warn if this happened. They would silently convert 'type'
to 0
, then try to get character 0 (the first character) of the string. So if this code was supposed to work, that's because abusing a string like this didn't cause any complaints on PHP 5.3 and below. (A lot of old PHP code has experienced this problem after upgrading.)
You might want to debug why the function is being given a string by examining the calling code, and find out what value it has by doing a var_dump($inputs);
in the function. But if you just want to shut the warning up to make it behave like PHP 5.3, change the line to:
if (is_array($inputs) && $inputs['type'] == 'attach') {
Yes it is, none of the Visual Stdio editions have C mentioned, but it is included with the C++ compiler (you therefore need to look under C++). The main difference between using C and C++ is the naming system (i.e. using .c and not .cpp).
You do have to be careful not to create a C++ project and rename it to C though, that does not work.
Much like you can use gcc
on Linux (or if you have MinGW installed) Visual Studio has a command to be used from command prompt (it must be the Visual Studio Developer Command Prompt though). As mentioned in the other answer you can use cl
to compile your c file (make sure it is named .c)
Example:
cl myfile.c
Or to check all the accepted commands:
C:\Program Files (x86)\Microsoft Visual Studio\2017\Community>cl
Microsoft (R) C/C++ Optimizing Compiler Version 19.16.27030.1 for x86
Copyright (C) Microsoft Corporation. All rights reserved.
usage: cl [ option... ] filename... [ /link linkoption... ]
C:\Program Files (x86)\Microsoft Visual Studio\2017\Community>
Without doubt one of the best features of Visual Studio is the convenient IDE.
Although it takes more configuring, you get bonuses such as basic debugging before compiling (for example if you forget a ;
)
To create a C project do the following:
Start a new project, go under C++ and select Empty Project
, enter the Name
of your project and the Location
you want it to install to, then click Ok
. Now wait for the project to be created.
Next under Solutions Explorer
right click Source Files
, select Add
then New Item
. You should see something like this:
Rename Source.cpp
to include a .c
extension (Source.c
for example). Select the location you want to keep it in, I would recommend always keeping it within the project folder itself (in this case C:\Users\Simon\Desktop\Learn\My First C Code
)
It should open up the .c
file, ready to be modified. Visual Studio can now be used as normal, happy coding!
Make as shown.
$(document).ready(function(){_x000D_
$('#myModal').modal('show');_x000D_
_x000D_
$('#myBtn').on('click', function(){_x000D_
$('#myModal').modal('show');_x000D_
});_x000D_
_x000D_
});_x000D_
<br/>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<title>Bootstrap Example</title>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
<h2>Activate Modal with JavaScript</h2>_x000D_
<!-- Trigger the modal with a button -->_x000D_
<button type="button" class="btn btn-info btn-lg" id="myBtn">Open Modal</button>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal fade" id="myModal" role="dialog">_x000D_
<div class="modal-dialog">_x000D_
_x000D_
<!-- Modal content-->_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal">×</button>_x000D_
<h4 class="modal-title">Modal Header</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<p>Some text in the modal.</p>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
For those who are looking to combine 2 color images into one, this is a slight mod on Andrey's answer which worked for me :
img1 = cv2.imread(imageFile1)
img2 = cv2.imread(imageFile2)
h1, w1 = img1.shape[:2]
h2, w2 = img2.shape[:2]
#create empty matrix
vis = np.zeros((max(h1, h2), w1+w2,3), np.uint8)
#combine 2 images
vis[:h1, :w1,:3] = img1
vis[:h2, w1:w1+w2,:3] = img2
You will get selected option's value and text from list/array by using filter.
editobj.FlagName=(EmployeeStatus|filter:{Value:editobj.Flag})[0].KeyName
<select name="statusSelect"
id="statusSelect"
class="form-control"
ng-model="editobj.Flag"
ng-options="option.Value as option.KeyName for option in EmployeeStatus"
ng-change="editobj.FlagName=(EmployeeStatus|filter:{Value:editobj.Flag})[0].KeyName">
</select>
I think the best method out there is to implement the SIGAR API by Hyperic. It works for most of the major operating systems ( darn near anything modern ) and is very easy to work with. The developer(s) are very responsive on their forum and mailing lists. I also like that it is GPL2 Apache licensed. They provide a ton of examples in Java too!
The correct format for url can be one of the following formats:
jdbc:oracle:thin:@<hostName>:<portNumber>:<sid>; (if you have sid)
jdbc:oracle:thin:@//<hostName>:<portNumber>/serviceName; (if you have oracle service name)
And don't put any space there. Try to use 1521 as port number. sid (database name) must be the same as the one which is in environment variables (if you are using windows).
This works in Python 3.x and 2.x:
# Fix Python 2.x.
try: input = raw_input
except NameError: pass
print("Hi " + input("Say something: "))
I found a better solution.
XML: (design.xml)
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent">
<FrameLayout android:layout_width="90px" android:layout_height="90px">
<RelativeLayout android:id="@+id/container" android:layout_width="fill_parent" android:layout_height="fill_parent">
</RelativeLayout>
</FrameLayout>
</FrameLayout>
Java Code:
public class Example extends Activity {
private RelativeLayout container;
private int currentX;
private int currentY;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.design);
container = (RelativeLayout)findViewById(R.id.container);
int top = 0;
int left = 0;
ImageView image1 = ...
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(left, top, 0, 0);
container.addView(image1, layoutParams);
ImageView image2 = ...
left+= 100;
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(left, top, 0, 0);
container.addView(image2, layoutParams);
ImageView image3 = ...
left= 0;
top+= 100;
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(left, top, 0, 0);
container.addView(image3, layoutParams);
ImageView image4 = ...
left+= 100;
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(left, top, 0, 0);
container.addView(image4, layoutParams);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
currentX = (int) event.getRawX();
currentY = (int) event.getRawY();
break;
}
case MotionEvent.ACTION_MOVE: {
int x2 = (int) event.getRawX();
int y2 = (int) event.getRawY();
container.scrollBy(currentX - x2 , currentY - y2);
currentX = x2;
currentY = y2;
break;
}
case MotionEvent.ACTION_UP: {
break;
}
}
return true;
}
}
That's works!!!
If you want to load other layout or control, the structure is the same.
you can use Package Manager to add it as package and it is the easiest way to do. You don't need anything else to work with mysql database.
Or you can run below command in Package Manager Console
PM> Install-Package MySql.Data
Renaming an Application- The Complete Guide
**A) for changing Just the application name
(App name which is displayed below icon)
in the Manifest.xml file, in <application tag,
android:label="YourAppName"
then do the same in All the <activity Tags
B) For changing EVERYTHING
(folder names, Package names, Refrences,app name, etc.)
*1) Renaming package names in gen folder and manifest.xml
Right Click on Your project
Android tools- Rename Application Package
*2) Renaming package names in src folder
Expand src folder, Click on package (Single click)
Press Alt+Shift+R
Check Update references and Rename subpackages
3) Renaming the app's main Folder (Optional)
click on the application's folder (Single click)
then Press Alt+Shift+R
4) Renaming application name- Refer "A)"**
The simplest solution (without depending on any third-party library or platform) is to create a URL instance pointing to the web page / link you want to download, and read the content using streams.
For example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class DownloadPage {
public static void main(String[] args) throws IOException {
// Make a URL to the web page
URL url = new URL("http://stackoverflow.com/questions/6159118/using-java-to-pull-data-from-a-webpage");
// Get the input stream through URL Connection
URLConnection con = url.openConnection();
InputStream is =con.getInputStream();
// Once you have the Input Stream, it's just plain old Java IO stuff.
// For this case, since you are interested in getting plain-text web page
// I'll use a reader and output the text content to System.out.
// For binary content, it's better to directly read the bytes from stream and write
// to the target file.
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
// read each line and write to System.out
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
Hope this helps.
IMO, you should have a look at the Observer Pattern, and this is how most of the listeners work
Forget using another plugin:
Here are 3 methods to close a jquery UI dialog when clicking outside popin:
If the dialog is modal/has background overlay: http://jsfiddle.net/jasonday/6FGqN/
jQuery(document).ready(function() {
jQuery("#dialog").dialog({
bgiframe: true,
autoOpen: false,
height: 100,
modal: true,
open: function(){
jQuery('.ui-widget-overlay').bind('click',function(){
jQuery('#dialog').dialog('close');
})
}
});
});
If dialog is non-modal Method 1: method 1: http://jsfiddle.net/jasonday/xpkFf/
// Close Pop-in If the user clicks anywhere else on the page
jQuery('body')
.bind(
'click',
function(e){
if(
jQuery('#dialog').dialog('isOpen')
&& !jQuery(e.target).is('.ui-dialog, a')
&& !jQuery(e.target).closest('.ui-dialog').length
){
jQuery('#dialog').dialog('close');
}
}
);
Non-Modal dialog Method 2: http://jsfiddle.net/jasonday/eccKr/
$(function() {
$( "#dialog" ).dialog({
autoOpen: false,
minHeight: 100,
width: 342,
draggable: true,
resizable: false,
modal: false,
closeText: 'Close',
open: function() {
closedialog = 1;
$(document).bind('click', overlayclickclose);
},
focus: function() {
closedialog = 0;
},
close: function() {
$(document).unbind('click');
}
});
$('#linkID').click(function() {
$('#dialog').dialog('open');
closedialog = 0;
});
var closedialog;
function overlayclickclose() {
if (closedialog) {
$('#dialog').dialog('close');
}
//set to one because click on dialog box sets to zero
closedialog = 1;
}
});
The comment by @s29 should be an answer:
One way to add a directory to the virtual environment is to install virtualenvwrapper (which is useful for many things) and then do
mkvirtualenv myenv
workon myenv
add2virtualenv . #for current directory
add2virtualenv ~/my/path
If you want to remove these path edit the file myenvhomedir/lib/python2.7/site-packages/_virtualenv_path_extensions.pth
Documentation on virtualenvwrapper can be found at http://virtualenvwrapper.readthedocs.org/en/latest/
Specific documentation on this feature can be found at http://virtualenvwrapper.readthedocs.org/en/latest/command_ref.html?highlight=add2virtualenv
it would be great if somebody told to put gif into any folder instead of assets folder
When you use the java
command to run a Java application from the command line, e.g.,
java some.AppName arg1 arg2 ...
the command loads the class that you nominated and then looks for the entry point method called main
. More specifically, it is looking for a method that is declared as follows:
package some;
public class AppName {
...
public static void main(final String[] args) {
// body of main method follows
...
}
}
The specific requirements for the entry point method are:
public
.static
2.void
.String[]
3. (The argument may be declared using varargs
syntax; e.g. String... args
. See this question for more information. The String[]
argument is used to pass the arguments from the command line, and is required even if your application takes no command-line arguments.)
If anyone of the above requirements is not satisfied, the java
command will fail with some variant of the message:
Error: Main method not found in class MyClass, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
Or, if you are running an extremely old version of Java:
java.lang.NoSuchMethodError: main
Exception in thread "main"
If you encounter this error, check that you have a main
method and that it satisfies all of the six requirements listed above.
1 - One really obscure variation of this is when one or more of the characters in "main" is NOT a LATIN-1 character … but a Unicode character that looks like the corresponding LATIN-1 character when displayed.
2 - Here is an explanation of why the method is required to be static.
3 - String
must correspond to java.lang.String
and not to a custom class named String
hiding it.
Add the CSS and JS in The Layout Folder.Access anywhere in the project
<!--// Stylesheets //-->
<?php
$themepath=Yii::app()->theme->baseUrl;
Yii::app()->clientScript->registerCoreScript("jquery");
?>
<link href="<?php echo $themepath."/css/custom.css"; ?>" rel="stylesheet" media="all" />
<!--// Javascript //-->
<?php Yii::app()->clientScript->registerCoreScript("jquery"); ?>
</script> -->
<script type="text/javascript" src="<?php echo $themepath; ?>/js/video.min.js"></script>
In my case, an Ubuntu system, in ports.conf I had
NameVirtualHost *:80
NameVirtualHost 192.168.1.79
Listen 80
And then, inside , I had
NameVirtualHost *:443
Listen 443
All I had to do was remove the line NameVirtualHost 192.168.1.79. Restarted apache and problem solved.
You can use javascript's indexOf function.
var str1 = "ABCDEFGHIJKLMNOP";_x000D_
var str2 = "DEFG";_x000D_
if(str1.indexOf(str2) != -1){_x000D_
console.log(str2 + " found");_x000D_
}
_x000D_
I can confirm Joseph's and Drew's answers to use RCTP TO: <address_to_check>
. I would like to add some little addenda on top of those answers.
Some mail providers implement a catch-all policy, meaning that *@mydomain.com
will return positive to the RCTP TO:
command. But this doesn't necessarily mean that the mailbox "exists", as in "belongs to a human". Nothing much can be done here, just be aware.
Greylisting: 1st connection from unknown IP is blocked. Solution: retry at least 2 times.
Blacklisting: if you send too many requests from the same IP, this IP is blocked. Solution: use IP rotation; Reacher uses Tor.
This is very provider-specific, but you sometimes can use well-crafted HTTP requests, and parse the responses of these requests to see if a username already signed up or not with this provider.
Here is the relevant function from an open-source library I wrote to check *@yahoo.com
addresses using HTTP requests: check-if-email-exists. I know my code is Rust and this thread is tagged PHP, but the same ideas apply.
This might be an edge case, but when the user has a full inbox, RCTP TO:
will return a 5.1.1 DSN
error message saying it's full. This means that the account actually exists!
I run Reacher, a real-time email verification API. My code is written in Rust, and is 100% open-source. Check it out if you want a more robust solution:
Github: https://github.com/amaurymartiny/check-if-email-exists
With a combination of various techniques to jump through hoops, I manage to verify around 80% of the emails my customers check.
Like already said, the -cp is just for telling the jvm in the command line which class to use for the main thread and where it can find the libraries (define classpath). In -jar it expects the class-path and main-class to be defined in the jar file manifest. So other is for defining things in command line while other finding them inside the jar manifest. There is no difference in performance. You can't use them at the same time, -jar will override the -cp.
Though even if you use -cp, it will still check the manifest file. So you can define some of the class-paths in the manifest and some in the command line. This is particularly useful when you have a dependency on some 3rd party jar, which you might not provide with your build or don't want to provide (expecting it to be found already in the system where it's to be installed for example). So you can use it to provide external jars. It's location may vary between systems or it may even have a different version on different system (but having the same interfaces). This way you can build the app with other version and add the actual 3rd party dependency to class-path on the command line when running it on different systems.
i think best approach is to make a common method and call in hover and click events.
I newer version of xampp you may use another method first open your httpd-xampp.conf file and find the string "phpmyadmin" using ctrl+F command (Windows). and then replace this code
Alias /phpmyadmin "D:/server/phpMyAdmin/"
<Directory "D:/server/phpMyAdmin">
AllowOverride AuthConfig
Require local
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>
with this
Alias /phpmyadmin "D:/server/phpMyAdmin/"
<Directory "D:/server/phpMyAdmin">
AllowOverride AuthConfig
Require all granted
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>
Don't Forget to Restart your Xampp.
You can use the status command in MySQL client.
mysql> status;
--------------
mysql Ver 14.14 Distrib 5.5.8, for Win32 (x86)
Connection id: 1
Current database: test
Current user: ODBC@localhost
SSL: Not in use
Using delimiter: ;
Server version: 5.5.8 MySQL Community Server (GPL)
Protocol version: 10
Connection: localhost via TCP/IP
Server characterset: latin1
Db characterset: latin1
Client characterset: gbk
Conn. characterset: gbk
TCP port: 3306
Uptime: 7 min 16 sec
Threads: 1 Questions: 21 Slow queries: 0 Opens: 33 Flush tables: 1 Open tables: 26 Queries per second avg: 0.48
--------------
mysql>
I got it working by selecting the original layout I had in the W / H selection. Storyboard is working as expected and the error is gone.
Be also sure that you are developing for iOS 8.0. Check that from the project's general settings.
instead of print $image;
you should go for print "<img src=<?$image;?>>"
and note that $image should contain the path of your image.
So, If you are only storing the name of your image in database then instead of that you have to store the full path of your image in the database like /root/user/Documents/image.jpeg.
Make sure (django 1.5 and beyond) that you put the url name in quotes, and if your url takes parameters they should be outside of the quotes (I spent hours figuring out this mistake!).
{% url 'namespace:view_name' arg1=value1 arg2=value2 as the_url %}
<a href="{{ the_url }}"> link_name </a>
I sort of fixed it by using the following code:
$("#editor").live('input paste',function(e){
if(e.target.id == 'editor') {
$('<textarea></textarea>').attr('id', 'paste').appendTo('#editMode');
$("#paste").focus();
setTimeout($(this).paste, 250);
}
});
Now I just need to store the caret location and append to that position then I'm all set... I think :)
If you want the column as string values, then:
SELECT id, name, CASE WHEN hide = 0 THEN 'false' ELSE 'true' END AS hide
FROM anonymous_table
If the DBMS supports BOOLEAN, you can use instead:
SELECT id, name, CASE WHEN hide = 0 THEN false ELSE true END AS hide
FROM anonymous_table
That's the same except that the quotes around the names false
and true
were removed.
Use this snip : var IE = (navigator.userAgent.indexOf("Edge") > -1 || navigator.userAgent.indexOf("Trident/7.0") > -1) ? true : false;
The answer by @chepner will copy all the sub-directories irrespective of the fact if it contains the file or not. If you need to exclude the sub-directories that dont contain the file and still retain the directory structure, use
rsync -zarv --prune-empty-dirs --include "*/" --include="*.sh" --exclude="*" "$from" "$to"
LayoutInflater creates View objects based on layouts defined in XML. There are several different ways to use LayoutInflater, including creating custom Views, inflating Fragment views into Activity views, creating Dialogs, or simply inflating a layout file View into an Activity.
There are a lot of misconceptions about how the inflation process works. I think this comes from poor of the documentation for the inflate() method. If you want to learn about the inflate() method in detail, I wrote a blog post about it here:
https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/
This worked for me. It looks like a button and behaves like a link. You can bookmark it for example.
<a href="mypage.aspx?param1=1" style="text-decoration:none;">
<asp:Button PostBackUrl="mypage.aspx?param1=1" Text="my button-like link" runat="server" />
</a>
This may work:
SELECT Count(tag) AS 'Tag Count'
FROM Table
GROUP BY tag
and
SELECT Count(tag) AS 'Negative Tag Count'
FROM Table
WHERE entryID > 0
GROUP BY tag
First, you should disable selinux
, edit file /etc/sysconfig/selinux
so it looks like this:
SELINUX=disabled
SELINUXTYPE=targeted
Save file and restart system.
Then you can add the new rule to iptables
:
iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT
and restart iptables with /etc/init.d/iptables restart
If it doesn't work you should check other network settings.
As an addition to msangel answer I would like to add the following code block:
private static CompletableFuture<Boolean> redirectToLogger(final InputStream inputStream, final Consumer<String> logLineConsumer) {
return CompletableFuture.supplyAsync(() -> {
try (
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
) {
String line = null;
while((line = bufferedReader.readLine()) != null) {
logLineConsumer.accept(line);
}
return true;
} catch (IOException e) {
return false;
}
});
}
It allows to redirect the input stream (stdout, stderr) of the process to some other consumer. This might be System.out::println or anything else consuming strings.
Usage:
...
Process process = processBuilder.start()
CompletableFuture<Boolean> stdOutRes = redirectToLogger(process.getInputStream(), System.out::println);
CompletableFuture<Boolean> stdErrRes = redirectToLogger(process.getErrorStream(), System.out::println);
System.out.println(stdOutRes.get());
System.out.println(stdErrRes.get());
System.out.println(process.waitFor());
It is better to use .Value2() instead of .Value(). This is faster and gives the exact value in the cell. For certain type of data, truncation can be observed when .Value() is used.
instance.__class__.__name__
example:
>>> class A():
pass
>>> a = A()
>>> a.__class__.__name__
'A'
if you are using windows or linux operating system then type in command prompt / terminal
java -version
If java is correctly installed then you will get something like this
java version "1.7.0_25"
Java(TM) SE Runtime Environment (build 1.7.0_25-b15)
Java HotSpot(TM) Client VM (build 23.25-b01, mixed mode, sharing)
Side note: After installation of Java on a windows operating system, the PATH variable is changed to add java.exe so you need to re-open cmd.exe to reload the PATH variable.
Edit:
CD to the path first...
cd C:\ProgramData\Oracle\Java\javapath
java -version
Try this:
SELECT SUM(transaction_amount) FROM TransactionMaster WHERE Card_No ='123' AND CONVERT(VARCHAR(10),GETDATE(),111)
The GETDATE()
function returns the current date and time from the SQL Server.
With HTML5 you can do
<input type="number">
You can also use a regex pattern to limit the input text.
<input type="text" pattern="^[0-9]*$" />
Use position:fixed
, as previously stated, IE6 doesn't recognize position:fixed
, but with some css magic you can get IE6 to behave:
html, body {
height: 100%;
overflow:auto;
}
body #fixedElement {
position:fixed !important;
position: absolute; /*ie6 */
bottom: 0;
}
The !important
flag makes it so you don't have to use a conditional comment for IE. This will have #fixedElement
use position:fixed
in all browsers but IE, and in IE
, position:absolute
will take effect with bottom:0
. This will simulate position:fixed
for IE6
DataFrame.compare
With pandas 1.1, you could essentially replicate Ted Petrou's output with a single function call. Example taken from the docs:
pd.__version__
# '1.1.0'
df1.compare(df2)
score isEnrolled Comment
self other self other self other
1 1.11 1.21 NaN NaN NaN NaN
2 NaN NaN 1.0 0.0 NaN On vacation
Here, "self" refers to the LHS dataFrame, while "other" is the RHS DataFrame. By default, equal values are replaced with NaNs so you can focus on just the diffs. If you want to show values that are equal as well, use
df1.compare(df2, keep_equal=True, keep_shape=True)
score isEnrolled Comment
self other self other self other
1 1.11 1.21 False False Graduated Graduated
2 4.12 4.12 True False NaN On vacation
You can also change the axis of comparison using align_axis
:
df1.compare(df2, align_axis='index')
score isEnrolled Comment
1 self 1.11 NaN NaN
other 1.21 NaN NaN
2 self NaN 1.0 NaN
other NaN 0.0 On vacation
This compares values row-wise, instead of column-wise.
As far as I can tell there is no upper limit in 2008.
In SQL Server 2005 the code in your question fails on the assignment to the @GGMMsg
variable with
Attempting to grow LOB beyond maximum allowed size of 2,147,483,647 bytes.
the code below fails with
REPLICATE: The length of the result exceeds the length limit (2GB) of the target large type.
However it appears these limitations have quietly been lifted. On 2008
DECLARE @y VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),92681);
SET @y = REPLICATE(@y,92681);
SELECT LEN(@y)
Returns
8589767761
I ran this on my 32 bit desktop machine so this 8GB string is way in excess of addressable memory
Running
select internal_objects_alloc_page_count
from sys.dm_db_task_space_usage
WHERE session_id = @@spid
Returned
internal_objects_alloc_page_co
------------------------------
2144456
so I presume this all just gets stored in LOB
pages in tempdb
with no validation on length. The page count growth was all associated with the SET @y = REPLICATE(@y,92681);
statement. The initial variable assignment to @y
and the LEN
calculation did not increase this.
The reason for mentioning this is because the page count is hugely more than I was expecting. Assuming an 8KB page then this works out at 16.36 GB which is obviously more or less double what would seem to be necessary. I speculate that this is likely due to the inefficiency of the string concatenation operation needing to copy the entire huge string and append a chunk on to the end rather than being able to add to the end of the existing string. Unfortunately at the moment the .WRITE
method isn't supported for varchar(max) variables.
Addition
I've also tested the behaviour with concatenating nvarchar(max) + nvarchar(max)
and nvarchar(max) + varchar(max)
. Both of these allow the 2GB limit to be exceeded. Trying to then store the results of this in a table then fails however with the error message Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes.
again. The script for that is below (may take a long time to run).
DECLARE @y1 VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),2147483647);
SET @y1 = @y1 + @y1;
SELECT LEN(@y1), DATALENGTH(@y1) /*4294967294, 4294967292*/
DECLARE @y2 NVARCHAR(MAX) = REPLICATE(CAST('X' AS NVARCHAR(MAX)),1073741823);
SET @y2 = @y2 + @y2;
SELECT LEN(@y2), DATALENGTH(@y2) /*2147483646, 4294967292*/
DECLARE @y3 NVARCHAR(MAX) = @y2 + @y1
SELECT LEN(@y3), DATALENGTH(@y3) /*6442450940, 12884901880*/
/*This attempt fails*/
SELECT @y1 y1, @y2 y2, @y3 y3
INTO Test
Here is a simple example, it will help you to get object key name.
var obj ={parts:{costPart:1000, salesPart: 2000}};
console.log(Object.keys(obj));
the output would be parts.
If you want to look at the actual GNU implementation of those functions in C, check out the latest trunk of glibc. See the GNU C Library.
Use the #
syntax for comments
From: https://docs.docker.com/engine/reference/builder/#format
# My comment here
RUN echo 'we are running some cool things'
Use preventDefault()
to stop the event of submit button and in ajax call success submit the form using submit()
:
$('#btnSave').click(function (e) {
e.preventDefault(); // <------------------ stop default behaviour of button
var element = this;
$.ajax({
url: "/Home/SaveDetailedInfo",
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "Success") {
alert("Done");
$(element).closest("form").submit(); //<------------ submit form
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error has occured!!!");
}
});
});
I would suggest in taking a look into JWE using special algorithms which is not present in jwt.io to decrypt
Reference link: https://www.npmjs.com/package/node-webtokens
jwt.generate('PBES2-HS512+A256KW', 'A256GCM', payload, pwd, (error, token) => {
jwt.parse(token).verify(pwd, (error, parsedToken) => {
// other statements
});
});
This answer may be too late or you might have already found out the way, but still, I felt it would be helpful for you and others as well.
A simple example which I have created: https://github.com/hansiemithun/jwe-example
Simply rename the folder. git is a "content-tracker", so the SHA1 hashes are the same and git knows, that you rename it. The only thing that changes is the tree-object.
rm <directory>
git add .
git commit
If you are working on Root Directory then you can use this approach
res.sendFile(__dirname + '/FOLDER_IN_ROOT_DIRECTORY/index.html');
but if you are using Routes which is inside a folder lets say /Routes/someRoute.js
then you will need to do something like this
const path = require("path");
...
route.get("/some_route", (req, res) => {
res.sendFile(path.resolve('FOLDER_IN_ROOT_DIRECTORY/index.html')
});
While a = 'foo' if True else 'bar'
is the more modern way of doing the ternary if statement (python 2.5+), a 1-to-1 equivalent of your version might be:
a = (b == True and "123" or "456" )
... which in python should be shortened to:
a = b is True and "123" or "456"
... or if you simply want to test the truthfulness of b's value in general...
a = b and "123" or "456"
? :
can literally be swapped out for and or