You can easily make your own 'AlertView' and use it everywhere.
alertView("You really want this?");
Implement it once:
private void alertView( String message ) {
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle( "Hello" )
.setIcon(R.drawable.ic_launcher)
.setMessage(message)
// .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialoginterface, int i) {
// dialoginterface.cancel();
// }})
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i) {
}
}).show();
}
I have just discovered a plugin on JSFiddle. Two possible alternatives : 1 single input OR 3 inputs, but looks like a single one... (use Tab key to go to the next input)
[link]http://jsfiddle.net/davidelrizzo/c8ASE/ It seems interesting !
As defined in JLS for-each loop can have two forms:
If the type of Expression is a subtype of Iterable
then translation is as:
List<String> someList = new ArrayList<String>();
someList.add("Apple");
someList.add("Ball");
for (String item : someList) {
System.out.println(item);
}
// IS TRANSLATED TO:
for(Iterator<String> stringIterator = someList.iterator(); stringIterator.hasNext(); ) {
String item = stringIterator.next();
System.out.println(item);
}
If the Expression necessarily has an array type T[]
then:
String[] someArray = new String[2];
someArray[0] = "Apple";
someArray[1] = "Ball";
for(String item2 : someArray) {
System.out.println(item2);
}
// IS TRANSLATED TO:
for (int i = 0; i < someArray.length; i++) {
String item2 = someArray[i];
System.out.println(item2);
}
Java 8 has introduced streams which perform generally better. We can use them as:
someList.stream().forEach(System.out::println);
Arrays.stream(someArray).forEach(System.out::println);
Add the --fields
parameter as comma separated field names enclosed in double inverted quotes:
--fields "<FIELD 1>,<FIELD 2>..."
This is complete example:
mongoexport --host Cluster0-shard-0/shard1URL.mongodb.net:27017,shard2URL.mongodb.net:27017,shard3URL.mongodb.net:27017 --ssl --username <USERNAME> --password <PASSWORD> --authenticationDatabase admin --db <DB NAME> --collection <COLLECTION NAME> --type <OUTPUT FILE TYPE> --out <OUTPUT FILE NAME> --fields "<FIELD 1>,<FIELD 2>..."
class Foo: is called old style class and class X(object): is called new style class.
Check this What is the difference between old style and new style classes in Python? . New style is recommended. Read about "unifying types and classes"
You can omit the -jar
option and start the jar file like this:
java -cp MyJar.jar;C:\externalJars\* mainpackage.MyMainClass
For me, the problem was that when I copied the solution to a new folder and opened it, it was missing the Nuget folder as shown below. I copied this folder over and everything worked. Note: This same folder was in our source control but not in this solutions project, it was up one directory.
Thanks for the pointers guys - the Value vs Value2 argument got me a different set of search results which helped me realise what the answer is. Incidentally, the Value property is a parametrized property, which must be accessed through an accessor in C#. These are called get_Value and set_Value, and take an optional enum value. If anyone's interested, this explains it nicely.
It's possible to make the assignment via the Value2 property however, which is preferable as the interop documentation recommends against the use use of the get_Value and set_Value methods, for reasons beyond my understanding.
The key seems to be the dimension of the array of objects. For the call to work the array must be declared as two-dimensional, even if you're only assigning one-dimensional data.
I declared my data array as an object[NumberofRows,1]
and the assignment call worked.
I thought I would expand on these answers for OSX and Linux folks (not that they need it):
I prefer to use mvnDebug too. But after OSX maverick destroyed my Java dev environment, I am starting from scratch and stubbled upon this post, and thought I would add to it.
$ mvnDebug vertx:runMod
-bash: mvnDebug: command not found
DOH! I have not set it up on this box after the new SSD drive and/or the reset of everything Java when I installed Maverick.
I use a package manager for OSX and Linux so I have no idea where mvn really lives. (I know for brief periods of time.. thanks brew.. I like that I don't know this.)
Let's see:
$ which mvn
/usr/local/bin/mvn
There you are... you little b@stard.
Now where did you get installed to:
$ ls -l /usr/local/bin/mvn
lrwxr-xr-x 1 root wheel 39 Oct 31 13:00 /
/usr/local/bin/mvn -> /usr/local/Cellar/maven30/3.0.5/bin/mvn
Aha! So you got installed in /usr/local/Cellar/maven30/3.0.5/bin/mvn. You cheeky little build tool. No doubt by homebrew...
Do you have your little buddy mvnDebug with you?
$ ls /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug
/usr/local/Cellar/maven30/3.0.5/bin/mvnDebug
Good. Good. Very good. All going as planned.
Now move that little b@stard where I can remember him more easily.
$ ln -s /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug /usr/local/bin/mvnDebug
ln: /usr/local/bin/mvnDebug: Permission denied
Darn you computer... You will submit to my will. Do you know who I am? I am SUDO! BOW!
$ sudo ln -s /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug /usr/local/bin/mvnDebug
Now I can use it from Eclipse (but why would I do that when I have IntelliJ!!!!)
$ mvnDebug vertx:runMod
Preparing to Execute Maven in Debug Mode
Listening for transport dt_socket at address: 8000
Internally mvnDebug uses this:
MAVEN_DEBUG_OPTS="-Xdebug -Xnoagent -Djava.compiler=NONE \
-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000"
So you could modify it (I usually debug on port 9090).
This blog explains how to setup Eclipse remote debugging (shudder)
http://javarevisited.blogspot.com/2011/02/how-to-setup-remote-debugging-in.html
Ditto Netbeans
https://blogs.oracle.com/atishay/entry/use_netbeans_to_debug_a
Ditto IntelliJ http://www.jetbrains.com/idea/webhelp/run-debug-configuration-remote.html
Here is some good docs on the -Xdebug command in general.
http://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/jrdocs/refman/optionX.html
"-Xdebug enables debugging capabilities in the JVM which are used by the Java Virtual Machine Tools Interface (JVMTI). JVMTI is a low-level debugging interface used by debuggers and profiling tools. With it, you can inspect the state and control the execution of applications running in the JVM."
"The subset of JVMTI that is most typically used by profilers is always available. However, the functionality used by debuggers to be able to step through the code and set breakpoints has some overhead associated with it and is not always available. To enable this functionality you must use the -Xdebug option."
-Xrunjdwp:transport=dt_socket,server=y,suspend=n myApp
Check out the docs on -Xrunjdwp too. You can enable it only when a certain exception is thrown for example. You can start it up suspended or running. Anyway.. I digress.
By their very nature, references can only be set at the time they are created; i.e., the following two lines have very different effects:
int & A = B; // makes A an alias for B
A = C; // assigns value of C to B.
Futher, this is illegal:
int & D; // must be set to a int variable.
However, when you create a vector, there is no way to assign values to it's items at creation. You are essentially just making a whole bunch of the last example.
Yes right the static array is created at the compile time where as the dynamic array is created on the run time. Where as the difference as far is concerned with their memory locations the static are located on the stack and the dynamic are created on the heap. Everything which gets located on heap needs the memory management until and unless garbage collector as in the case of .net framework is present otherwise there is a risk of memory leak.
Boxing and Unboxing are specifically used to treat value-type objects as reference-type; moving their actual value to the managed heap and accessing their value by reference.
Without boxing and unboxing you could never pass value-types by reference; and that means you could not pass value-types as instances of Object.
I use this way (postgresql only): https://wiki.postgresql.org/wiki/First/last_%28aggregate%29
-- Create a function that always returns the first non-NULL item
CREATE OR REPLACE FUNCTION public.first_agg ( anyelement, anyelement )
RETURNS anyelement LANGUAGE sql IMMUTABLE STRICT AS $$
SELECT $1;
$$;
-- And then wrap an aggregate around it
CREATE AGGREGATE public.first (
sfunc = public.first_agg,
basetype = anyelement,
stype = anyelement
);
-- Create a function that always returns the last non-NULL item
CREATE OR REPLACE FUNCTION public.last_agg ( anyelement, anyelement )
RETURNS anyelement LANGUAGE sql IMMUTABLE STRICT AS $$
SELECT $2;
$$;
-- And then wrap an aggregate around it
CREATE AGGREGATE public.last (
sfunc = public.last_agg,
basetype = anyelement,
stype = anyelement
);
Then your example should work almost as is:
SELECT FIRST(id), customer, FIRST(total)
FROM purchases
GROUP BY customer
ORDER BY FIRST(total) DESC;
CAVEAT: It ignore's NULL rows
Now I use this way: http://pgxn.org/dist/first_last_agg/
To install on ubuntu 14.04:
apt-get install postgresql-server-dev-9.3 git build-essential -y
git clone git://github.com/wulczer/first_last_agg.git
cd first_last_app
make && sudo make install
psql -c 'create extension first_last_agg'
It's a postgres extension that gives you first and last functions; apparently faster than the above way.
If you use aggregate functions (like these), you can order the results, without the need to have the data already ordered:
http://www.postgresql.org/docs/current/static/sql-expressions.html#SYNTAX-AGGREGATES
So the equivalent example, with ordering would be something like:
SELECT first(id order by id), customer, first(total order by id)
FROM purchases
GROUP BY customer
ORDER BY first(total);
Of course you can order and filter as you deem fit within the aggregate; it's very powerful syntax.
select one.*, two.meal
from table1 as one
left join table2 as two
on (one.weddingtable = two.weddingtable and one.tableseat = two.tableseat)
/// Create the bottom sheet UI
Widget bottomSheetBuilder(){
return Container(
color: Color(0xFF737373), // This line set the transparent background
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(16.0),
topRight: Radius.circular( 16.0)
)
),
child: Center( child: Text("Hi everyone!"),)
),
);
}
Call this to show the BotoomSheet with corners:
/// Show the bottomSheet when called
Future _onMenuPressed() async {
showModalBottomSheet(
context: context,
builder: (widgetBuilder) => bottomSheetBuilder()
);
}
First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.
For example,
> z <- factor(letters[c(3, 2, 3, 4)])
# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d
# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"
here, z
has 4 elements.
The index is 2, 1, 2, 3
in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.
Then, as.numeric
converts simply the index part of factor into numeric.
as.character
handles the index and levels, and generates character vector expressed by its level.
?as.numeric
says that Factors are handled by the default method.
Try
let bytes = [65,108,105,99,101,39,115,32,65,100,118,101,110,116,117,114,101];_x000D_
_x000D_
let base64data = btoa(String.fromCharCode.apply(null, bytes));_x000D_
_x000D_
let a = document.createElement('a');_x000D_
a.href = 'data:;base64,' + base64data;_x000D_
a.download = 'binFile.txt'; _x000D_
a.click();
_x000D_
I convert here binary data to base64 (for bigger data conversion use this) - during downloading browser decode it automatically and save raw data in file. 2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop working (probably due to sandbox security restrictions) - but JSFiddle version works - here
mysqli_fetch_array()
returns NULL
if there is no row.
In procedural style:
if ( ! $row = mysqli_fetch_array( $result ) ) {
... no result ...
}
else {
... get the first result in $row ...
}
In Object oriented style:
if ( ! $row = $result->fetch_array() ) {
...
}
else {
... get the first result in $row ...
}
Just add a Label without text and with background color. Set the Coordinates of your choice and also height and width. You can do it manually or with Interface Builder.
Foreach-object operation statement:
$a,$b = 'hi.there' | foreach split .
$a,$b
hi
there
I just checked with www.browserscope.org and with IE9 and Chrome 24 you can have 6 concurrent connections to a single domain, and up to 17 to multiple ones.
Here's my Code to theme the alert dialog box:
<style name="alertDialog" parent="Theme.AppCompat.Dialog.Alert">
<item name="android:background">@color/light_button_text_color</item>
<item name="android:textColor">@android:color/black</item>
<item name="android:textColorPrimary">@android:color/black</item>
<item name="android:textColorSecondary">@android:color/black</item>
<item name="android:titleTextColor" tools:targetApi="m">@android:color/black</item>
</style>
Place this code in styles.xml. In your java apply this theme as:
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.alertDialog);
Create Spliterator
from Iterator
using Spliterators
class contains more than one function for creating spliterator, for example here am using spliteratorUnknownSize
which is getting iterator as parameter, then create Stream using StreamSupport
Spliterator<Model> spliterator = Spliterators.spliteratorUnknownSize(
iterator, Spliterator.NONNULL);
Stream<Model> stream = StreamSupport.stream(spliterator, false);
UPDATE: Ruby 1.9.3 Kernel#rand
also accepts ranges
rand(a..b)
http://www.rubyinside.com/ruby-1-9-3-introduction-and-changes-5428.html
Converting to array may be too expensive, and it's unnecessary.
(a..b).to_a.sample
Or
[*a..b].sample
Standard in Ruby 1.8.7+.
Note: was named #choice in 1.8.7 and renamed in later versions.
But anyway, generating array need resources, and solution you already wrote is the best, you can do.
I happened to try this so I could see the list of files first:
git status | grep "modified:" | awk '{print "git add " $2}' > file.sh
cat ./file.sh
execute:
chmod a+x file.sh
./file.sh
Edit: (see comments) This could be achieved in one step:
git status | grep "modified:" | awk '{print $2}' | xargs git add && git status
Try adding JSON.stringify(result)
to convert the JS Object into a JSON string.
From your code I can see you are logging the result in error
which is called if the AJAX request fails, so I'm not sure how you'd go about accessing the id/name/etc. then (you are checking for success inside the error condition!).
Note that if you use Chrome's console you should be able to browse through the object without having to stringify the JSON, which makes it easier to debug.
What you're asking about is called Variable Variables. All you need to do is store your string in a variable and access it like so:
$Class = 'MyCustomClass';
$Property = 'Name';
$List = array('Name');
$Object = new $Class();
// All of these will echo the same property
echo $Object->$Property; // Evaluates to $Object->Name
echo $Object->{$List[0]}; // Use if your variable is in an array
The problem is that floating elements are out-of-flow:
An element is called out of flow if it is floated, absolutely positioned, or is the root element.
Therefore, they don't impact surrounding elements as an in-flow element would.
This is explained in 9.5 Floats:
Since a float is not in the flow, non-positioned block boxes created before and after the float box flow vertically as if the float did not exist. However, the current and subsequent line boxes created next to the float are shortened as necessary to make room for the margin box of the float.
html {_x000D_
width: 550px;_x000D_
border: 1px solid;_x000D_
}_x000D_
body {_x000D_
font-family: sans-serif;_x000D_
color: rgba(0,0,0,.15);_x000D_
}_x000D_
body:after {_x000D_
content: '';_x000D_
display: block;_x000D_
clear: both;_x000D_
}_x000D_
div {_x000D_
position: relative;_x000D_
}_x000D_
div:after {_x000D_
font-size: 200%;_x000D_
position: absolute;_x000D_
left: 0;_x000D_
right: 0;_x000D_
top: 0;_x000D_
text-align: center;_x000D_
}_x000D_
.block-sibling {_x000D_
border: 3px solid green;_x000D_
}_x000D_
.block-sibling:after {_x000D_
content: 'Block sibling';_x000D_
color: green;_x000D_
}_x000D_
.float {_x000D_
float: left;_x000D_
border: 3px solid red;_x000D_
height: 90px;_x000D_
width: 150px;_x000D_
z-index: 1;_x000D_
}_x000D_
.float:after {_x000D_
content: 'Float';_x000D_
color: red;_x000D_
}
_x000D_
<div class="float"></div>_x000D_
<div class="block-sibling">_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non tortor._x000D_
</div>
_x000D_
This is also specified in 10.6 Calculating heights and margins. For "normal" blocks,
Only children in the normal flow are taken into account (i.e., floating boxes and absolutely positioned boxes are ignored […])
html {_x000D_
width: 550px;_x000D_
border: 1px solid;_x000D_
}_x000D_
body {_x000D_
font-family: sans-serif;_x000D_
color: rgba(0,0,0,.15);_x000D_
}_x000D_
body:after {_x000D_
content: '';_x000D_
display: block;_x000D_
clear: both;_x000D_
}_x000D_
div {_x000D_
position: relative;_x000D_
}_x000D_
div:after {_x000D_
font-size: 200%;_x000D_
position: absolute;_x000D_
left: 0;_x000D_
right: 0;_x000D_
top: 0;_x000D_
text-align: center;_x000D_
}_x000D_
.block-parent {_x000D_
border: 3px solid blue;_x000D_
}_x000D_
.block-parent:after {_x000D_
content: 'Block parent';_x000D_
color: blue;_x000D_
}_x000D_
.float {_x000D_
float: left;_x000D_
border: 3px solid red;_x000D_
height: 130px;_x000D_
width: 150px;_x000D_
}_x000D_
.float:after {_x000D_
content: 'Float';_x000D_
color: red;_x000D_
}
_x000D_
<div class="block-parent">_x000D_
<div class="float"></div>_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit._x000D_
</div>
_x000D_
A way to solve the problem is forcing some in-flow element to be placed below all floats. Then, the height of the parent will grow to wrap that element (and thus the floats too).
This can be achieved using the clear
property:
This property indicates which sides of an element's box(es) may not be adjacent to an earlier floating box.
html {_x000D_
width: 550px;_x000D_
border: 1px solid;_x000D_
}_x000D_
body {_x000D_
font-family: sans-serif;_x000D_
color: rgba(0,0,0,.15);_x000D_
}_x000D_
body:after {_x000D_
content: '';_x000D_
display: block;_x000D_
clear: both;_x000D_
}_x000D_
div {_x000D_
position: relative;_x000D_
}_x000D_
div:after {_x000D_
font-size: 200%;_x000D_
position: absolute;_x000D_
left: 0;_x000D_
right: 0;_x000D_
top: 0;_x000D_
text-align: center;_x000D_
}_x000D_
.block-parent {_x000D_
border: 3px solid blue;_x000D_
}_x000D_
.block-parent:after {_x000D_
content: 'Block parent';_x000D_
color: blue;_x000D_
}_x000D_
.float {_x000D_
float: left;_x000D_
border: 3px solid red;_x000D_
height: 84px;_x000D_
width: 150px;_x000D_
}_x000D_
.float:after {_x000D_
content: 'Float';_x000D_
color: red;_x000D_
}_x000D_
.clear {_x000D_
clear: both;_x000D_
text-align: center;_x000D_
height: 37px;_x000D_
border: 3px dashed pink;_x000D_
}_x000D_
.clear:after {_x000D_
position: static;_x000D_
content: 'Block sibling with clearance';_x000D_
color: pink;_x000D_
}
_x000D_
<div class="block-parent">_x000D_
<div class="float"></div>_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra._x000D_
<div class="clear"></div>_x000D_
</div>
_x000D_
So a solution is adding an empty element with clear: both
as the last sibling of the floats
<div style="clear: both"></div>
However, that is not semantic. So better generate a pseudo-element at the end of the parent:
.clearfix::after {
clear: both;
display: block;
}
There are multiple variants of this approach, e.g. using the deprecated single colon syntax :after
to support old browsers, or using other block-level displays like display: table
.
There is an exception to the problematic behavior defined at the beginning: if a block element establishes a Block Formatting Context (is a BFC root), then it will also wrap its floating contents.
According to 10.6.7 'Auto' heights for block formatting context roots,
If the element has any floating descendants whose bottom margin edge is below the element's bottom content edge, then the height is increased to include those edges.
html {_x000D_
width: 550px;_x000D_
border: 1px solid;_x000D_
}_x000D_
body {_x000D_
font-family: sans-serif;_x000D_
color: rgba(0,0,0,.15);_x000D_
}_x000D_
body:after {_x000D_
content: '';_x000D_
display: block;_x000D_
clear: both;_x000D_
}_x000D_
div {_x000D_
position: relative;_x000D_
}_x000D_
div:after {_x000D_
font-size: 200%;_x000D_
position: absolute;_x000D_
left: 0;_x000D_
right: 0;_x000D_
top: 0;_x000D_
text-align: center;_x000D_
}_x000D_
.block-parent {_x000D_
border: 3px solid blue;_x000D_
}_x000D_
.block-parent.bfc-root:after {_x000D_
content: 'BFC parent';_x000D_
color: blue;_x000D_
}_x000D_
.float {_x000D_
float: left;_x000D_
border: 3px solid red;_x000D_
height: 127px;_x000D_
width: 150px;_x000D_
}_x000D_
.float:after {_x000D_
content: 'Float';_x000D_
color: red;_x000D_
}_x000D_
.bfc-root {_x000D_
overflow: hidden;_x000D_
}
_x000D_
<div class="block-parent bfc-root">_x000D_
<div class="float"></div>_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit._x000D_
</div>
_x000D_
Additionally, as explained 9.5 Floats, BFC roots are also useful because of the following:
The border box of a table, a block-level replaced element, or an element in the normal flow that establishes a new block formatting context […] must not overlap the margin box of any floats in the same block formatting context as the element itself.
html {_x000D_
width: 550px;_x000D_
border: 1px solid;_x000D_
}_x000D_
body {_x000D_
font-family: sans-serif;_x000D_
color: rgba(0,0,0,.15);_x000D_
}_x000D_
body:after {_x000D_
content: '';_x000D_
display: block;_x000D_
clear: both;_x000D_
}_x000D_
div {_x000D_
position: relative;_x000D_
}_x000D_
div:after {_x000D_
font-size: 200%;_x000D_
position: absolute;_x000D_
left: 0;_x000D_
right: 0;_x000D_
top: 0;_x000D_
text-align: center;_x000D_
}_x000D_
.block-sibling {_x000D_
border: 3px solid green;_x000D_
}_x000D_
.block-sibling.bfc-root:after {_x000D_
content: 'BFC sibling';_x000D_
color: green;_x000D_
}_x000D_
.float {_x000D_
float: left;_x000D_
border: 3px solid red;_x000D_
height: 90px;_x000D_
width: 150px;_x000D_
z-index: 1;_x000D_
}_x000D_
.float:after {_x000D_
content: 'Float';_x000D_
color: red;_x000D_
}_x000D_
.bfc-root {_x000D_
overflow: hidden;_x000D_
}
_x000D_
<div class="float"></div>_x000D_
<div class="block-sibling bfc-root">_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur._x000D_
</div>
_x000D_
A block formatting context is established by
Block boxes with overflow
other than visible
, e.g. hidden
.bfc-root {
overflow: hidden;
/* display: block; */
}
Block containers that are not block boxes: when display
is set to inline-block
, table-cell
or table-caption
.
.bfc-root {
display: inline-block;
}
Floating elements: when float
is set to left
or right
.
.bfc-root {
float: left;
}
Absolutely positioned elements: when position
is set to absolute
or fixed
.
.bfc-root {
position: absolute;
}
Note those may have undesired collateral effects, like clipping overflowing content, calculating auto widths with the shrink-to-fit algorithm, or becoming out-of-flow. So the problem is that it's not possible to have an in-flow block-level element with visible overflow that establishes a BFC.
Display L3 addresses these issues:
Created the
flow
andflow-root
inner display types to better express flow layout display types and to create an explicit switch for making an element a BFC root. (This should eliminate the need for hacks like::after { clear: both; }
andoverflow: hidden
[…])
Sadly, there is no browser support yet. Eventually we may be able to use
.bfc-root {
display: flow-root;
}
Stealth Change in VS 2010 and .NET 4.0 and Later
No public installers with the RunInstallerAttribute.Yes attribute could be found
There is an alias change or compiler cleanup in .NET that may reveal this little tweak for your specific case.
If you have the following code …
RunInstaller(true) // old alias
You may need to update it to
RunInstallerAttribute(true) // new property spelling
It is like an alias changed under the covers at compile time or at runtime and you will get this error behavior. The above explicit change to RunInstallerAttribute(true) fixed it in all of our install scenarios on all machines.
After you add project or service installer then check for the “old” RunInstaller(true) and change it to the new RunInstallerAttribute(true)
psql: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket"/var/pgsql_socket/.s.PGSQL.5432"?
I kept on getting the above error and none of the above solutions worked for me. Finally the following solution solved my problem on Mac OS X
Install postgres using brew
brew install postgres
Install brew services
brew tap homebrew/services
To start postgres as a background service
brew services start postgresql
To stop postgres manually
brew services stop postgresql
We can also use brew services to restart Postgres
brew services restart postgresql
The easiest way to do this is to click on the Terminate button(red square) in the console:
Most Complete and Working (Tested) Code for Downloading Data For FireFox, Chrome and IE Code is Following. Assume that Data is in texarea field, that has id='textarea_area' and filename is name of file where data will be downloaded.
function download(filename) {
if (typeof filename==='undefined') filename = ""; // default
value = document.getElementById('textarea_area').value;
filetype="text/*";
extension=filename.substring(filename.lastIndexOf("."));
for (var i = 0; i < extToMIME.length; i++) {
if (extToMIME[i][0].localeCompare(extension)==0) {
filetype=extToMIME[i][1];
break;
}
}
var pom = document.createElement('a');
pom.setAttribute('href', 'data: '+filetype+';charset=utf-8,' + '\ufeff' + encodeURIComponent(value)); // Added BOM too
pom.setAttribute('download', filename);
if (document.createEvent) {
if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) { // IE
blobObject = new Blob(['\ufeff'+value]);
window.navigator.msSaveBlob(blobObject, filename);
} else { // FF, Chrome
var event = document.createEvent('MouseEvents');
event.initEvent('click', true, true);
pom.dispatchEvent(event);
}
} else if( document.createEventObject ) { // Have No Idea
var evObj = document.createEventObject();
pom.fireEvent( 'onclick' , evObj );
} else { // For Any Case
pom.click();
}
}
and then just call
<a href="javascript:download();">Download</a>
For Download Initiating.
Array for setting correct MIME type for download dialog CAN BE following:
// ----------------------- Extensions to MIME --------- //
// List of mime types
// combination of values from Windows 7 Registry and
// from C:\Windows\System32\inetsrv\config\applicationHost.config
// some added, including .7z and .dat
var extToMIME = [
[".323", "text/h323"],
[".3g2", "video/3gpp2"],
[".3gp", "video/3gpp"],
[".3gp2", "video/3gpp2"],
[".3gpp", "video/3gpp"],
[".7z", "application/x-7z-compressed"],
[".aa", "audio/audible"],
[".AAC", "audio/aac"],
[".aaf", "application/octet-stream"],
[".aax", "audio/vnd.audible.aax"],
[".ac3", "audio/ac3"],
[".aca", "application/octet-stream"],
[".accda", "application/msaccess.addin"],
[".accdb", "application/msaccess"],
[".accdc", "application/msaccess.cab"],
[".accde", "application/msaccess"],
[".accdr", "application/msaccess.runtime"],
[".accdt", "application/msaccess"],
[".accdw", "application/msaccess.webapplication"],
[".accft", "application/msaccess.ftemplate"],
[".acx", "application/internet-property-stream"],
[".AddIn", "text/xml"],
[".ade", "application/msaccess"],
[".adobebridge", "application/x-bridge-url"],
[".adp", "application/msaccess"],
[".ADT", "audio/vnd.dlna.adts"],
[".ADTS", "audio/aac"],
[".afm", "application/octet-stream"],
[".ai", "application/postscript"],
[".aif", "audio/x-aiff"],
[".aifc", "audio/aiff"],
[".aiff", "audio/aiff"],
[".air", "application/vnd.adobe.air-application-installer-package+zip"],
[".amc", "application/x-mpeg"],
[".application", "application/x-ms-application"],
[".art", "image/x-jg"],
[".asa", "application/xml"],
[".asax", "application/xml"],
[".ascx", "application/xml"],
[".asd", "application/octet-stream"],
[".asf", "video/x-ms-asf"],
[".ashx", "application/xml"],
[".asi", "application/octet-stream"],
[".asm", "text/plain"],
[".asmx", "application/xml"],
[".aspx", "application/xml"],
[".asr", "video/x-ms-asf"],
[".asx", "video/x-ms-asf"],
[".atom", "application/atom+xml"],
[".au", "audio/basic"],
[".avi", "video/x-msvideo"],
[".axs", "application/olescript"],
[".bas", "text/plain"],
[".bcpio", "application/x-bcpio"],
[".bin", "application/octet-stream"],
[".bmp", "image/bmp"],
[".c", "text/plain"],
[".cab", "application/octet-stream"],
[".caf", "audio/x-caf"],
[".calx", "application/vnd.ms-office.calx"],
[".cat", "application/vnd.ms-pki.seccat"],
[".cc", "text/plain"],
[".cd", "text/plain"],
[".cdda", "audio/aiff"],
[".cdf", "application/x-cdf"],
[".cer", "application/x-x509-ca-cert"],
[".chm", "application/octet-stream"],
[".class", "application/x-java-applet"],
[".clp", "application/x-msclip"],
[".cmx", "image/x-cmx"],
[".cnf", "text/plain"],
[".cod", "image/cis-cod"],
[".config", "application/xml"],
[".contact", "text/x-ms-contact"],
[".coverage", "application/xml"],
[".cpio", "application/x-cpio"],
[".cpp", "text/plain"],
[".crd", "application/x-mscardfile"],
[".crl", "application/pkix-crl"],
[".crt", "application/x-x509-ca-cert"],
[".cs", "text/plain"],
[".csdproj", "text/plain"],
[".csh", "application/x-csh"],
[".csproj", "text/plain"],
[".css", "text/css"],
[".csv", "text/csv"],
[".cur", "application/octet-stream"],
[".cxx", "text/plain"],
[".dat", "application/octet-stream"],
[".datasource", "application/xml"],
[".dbproj", "text/plain"],
[".dcr", "application/x-director"],
[".def", "text/plain"],
[".deploy", "application/octet-stream"],
[".der", "application/x-x509-ca-cert"],
[".dgml", "application/xml"],
[".dib", "image/bmp"],
[".dif", "video/x-dv"],
[".dir", "application/x-director"],
[".disco", "text/xml"],
[".dll", "application/x-msdownload"],
[".dll.config", "text/xml"],
[".dlm", "text/dlm"],
[".doc", "application/msword"],
[".docm", "application/vnd.ms-word.document.macroEnabled.12"],
[".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"],
[".dot", "application/msword"],
[".dotm", "application/vnd.ms-word.template.macroEnabled.12"],
[".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"],
[".dsp", "application/octet-stream"],
[".dsw", "text/plain"],
[".dtd", "text/xml"],
[".dtsConfig", "text/xml"],
[".dv", "video/x-dv"],
[".dvi", "application/x-dvi"],
[".dwf", "drawing/x-dwf"],
[".dwp", "application/octet-stream"],
[".dxr", "application/x-director"],
[".eml", "message/rfc822"],
[".emz", "application/octet-stream"],
[".eot", "application/octet-stream"],
[".eps", "application/postscript"],
[".etl", "application/etl"],
[".etx", "text/x-setext"],
[".evy", "application/envoy"],
[".exe", "application/octet-stream"],
[".exe.config", "text/xml"],
[".fdf", "application/vnd.fdf"],
[".fif", "application/fractals"],
[".filters", "Application/xml"],
[".fla", "application/octet-stream"],
[".flr", "x-world/x-vrml"],
[".flv", "video/x-flv"],
[".fsscript", "application/fsharp-script"],
[".fsx", "application/fsharp-script"],
[".generictest", "application/xml"],
[".gif", "image/gif"],
[".group", "text/x-ms-group"],
[".gsm", "audio/x-gsm"],
[".gtar", "application/x-gtar"],
[".gz", "application/x-gzip"],
[".h", "text/plain"],
[".hdf", "application/x-hdf"],
[".hdml", "text/x-hdml"],
[".hhc", "application/x-oleobject"],
[".hhk", "application/octet-stream"],
[".hhp", "application/octet-stream"],
[".hlp", "application/winhlp"],
[".hpp", "text/plain"],
[".hqx", "application/mac-binhex40"],
[".hta", "application/hta"],
[".htc", "text/x-component"],
[".htm", "text/html"],
[".html", "text/html"],
[".htt", "text/webviewhtml"],
[".hxa", "application/xml"],
[".hxc", "application/xml"],
[".hxd", "application/octet-stream"],
[".hxe", "application/xml"],
[".hxf", "application/xml"],
[".hxh", "application/octet-stream"],
[".hxi", "application/octet-stream"],
[".hxk", "application/xml"],
[".hxq", "application/octet-stream"],
[".hxr", "application/octet-stream"],
[".hxs", "application/octet-stream"],
[".hxt", "text/html"],
[".hxv", "application/xml"],
[".hxw", "application/octet-stream"],
[".hxx", "text/plain"],
[".i", "text/plain"],
[".ico", "image/x-icon"],
[".ics", "application/octet-stream"],
[".idl", "text/plain"],
[".ief", "image/ief"],
[".iii", "application/x-iphone"],
[".inc", "text/plain"],
[".inf", "application/octet-stream"],
[".inl", "text/plain"],
[".ins", "application/x-internet-signup"],
[".ipa", "application/x-itunes-ipa"],
[".ipg", "application/x-itunes-ipg"],
[".ipproj", "text/plain"],
[".ipsw", "application/x-itunes-ipsw"],
[".iqy", "text/x-ms-iqy"],
[".isp", "application/x-internet-signup"],
[".ite", "application/x-itunes-ite"],
[".itlp", "application/x-itunes-itlp"],
[".itms", "application/x-itunes-itms"],
[".itpc", "application/x-itunes-itpc"],
[".IVF", "video/x-ivf"],
[".jar", "application/java-archive"],
[".java", "application/octet-stream"],
[".jck", "application/liquidmotion"],
[".jcz", "application/liquidmotion"],
[".jfif", "image/pjpeg"],
[".jnlp", "application/x-java-jnlp-file"],
[".jpb", "application/octet-stream"],
[".jpe", "image/jpeg"],
[".jpeg", "image/jpeg"],
[".jpg", "image/jpeg"],
[".js", "application/x-javascript"],
[".json", "application/json"],
[".jsx", "text/jscript"],
[".jsxbin", "text/plain"],
[".latex", "application/x-latex"],
[".library-ms", "application/windows-library+xml"],
[".lit", "application/x-ms-reader"],
[".loadtest", "application/xml"],
[".lpk", "application/octet-stream"],
[".lsf", "video/x-la-asf"],
[".lst", "text/plain"],
[".lsx", "video/x-la-asf"],
[".lzh", "application/octet-stream"],
[".m13", "application/x-msmediaview"],
[".m14", "application/x-msmediaview"],
[".m1v", "video/mpeg"],
[".m2t", "video/vnd.dlna.mpeg-tts"],
[".m2ts", "video/vnd.dlna.mpeg-tts"],
[".m2v", "video/mpeg"],
[".m3u", "audio/x-mpegurl"],
[".m3u8", "audio/x-mpegurl"],
[".m4a", "audio/m4a"],
[".m4b", "audio/m4b"],
[".m4p", "audio/m4p"],
[".m4r", "audio/x-m4r"],
[".m4v", "video/x-m4v"],
[".mac", "image/x-macpaint"],
[".mak", "text/plain"],
[".man", "application/x-troff-man"],
[".manifest", "application/x-ms-manifest"],
[".map", "text/plain"],
[".master", "application/xml"],
[".mda", "application/msaccess"],
[".mdb", "application/x-msaccess"],
[".mde", "application/msaccess"],
[".mdp", "application/octet-stream"],
[".me", "application/x-troff-me"],
[".mfp", "application/x-shockwave-flash"],
[".mht", "message/rfc822"],
[".mhtml", "message/rfc822"],
[".mid", "audio/mid"],
[".midi", "audio/mid"],
[".mix", "application/octet-stream"],
[".mk", "text/plain"],
[".mmf", "application/x-smaf"],
[".mno", "text/xml"],
[".mny", "application/x-msmoney"],
[".mod", "video/mpeg"],
[".mov", "video/quicktime"],
[".movie", "video/x-sgi-movie"],
[".mp2", "video/mpeg"],
[".mp2v", "video/mpeg"],
[".mp3", "audio/mpeg"],
[".mp4", "video/mp4"],
[".mp4v", "video/mp4"],
[".mpa", "video/mpeg"],
[".mpe", "video/mpeg"],
[".mpeg", "video/mpeg"],
[".mpf", "application/vnd.ms-mediapackage"],
[".mpg", "video/mpeg"],
[".mpp", "application/vnd.ms-project"],
[".mpv2", "video/mpeg"],
[".mqv", "video/quicktime"],
[".ms", "application/x-troff-ms"],
[".msi", "application/octet-stream"],
[".mso", "application/octet-stream"],
[".mts", "video/vnd.dlna.mpeg-tts"],
[".mtx", "application/xml"],
[".mvb", "application/x-msmediaview"],
[".mvc", "application/x-miva-compiled"],
[".mxp", "application/x-mmxp"],
[".nc", "application/x-netcdf"],
[".nsc", "video/x-ms-asf"],
[".nws", "message/rfc822"],
[".ocx", "application/octet-stream"],
[".oda", "application/oda"],
[".odc", "text/x-ms-odc"],
[".odh", "text/plain"],
[".odl", "text/plain"],
[".odp", "application/vnd.oasis.opendocument.presentation"],
[".ods", "application/oleobject"],
[".odt", "application/vnd.oasis.opendocument.text"],
[".one", "application/onenote"],
[".onea", "application/onenote"],
[".onepkg", "application/onenote"],
[".onetmp", "application/onenote"],
[".onetoc", "application/onenote"],
[".onetoc2", "application/onenote"],
[".orderedtest", "application/xml"],
[".osdx", "application/opensearchdescription+xml"],
[".p10", "application/pkcs10"],
[".p12", "application/x-pkcs12"],
[".p7b", "application/x-pkcs7-certificates"],
[".p7c", "application/pkcs7-mime"],
[".p7m", "application/pkcs7-mime"],
[".p7r", "application/x-pkcs7-certreqresp"],
[".p7s", "application/pkcs7-signature"],
[".pbm", "image/x-portable-bitmap"],
[".pcast", "application/x-podcast"],
[".pct", "image/pict"],
[".pcx", "application/octet-stream"],
[".pcz", "application/octet-stream"],
[".pdf", "application/pdf"],
[".pfb", "application/octet-stream"],
[".pfm", "application/octet-stream"],
[".pfx", "application/x-pkcs12"],
[".pgm", "image/x-portable-graymap"],
[".pic", "image/pict"],
[".pict", "image/pict"],
[".pkgdef", "text/plain"],
[".pkgundef", "text/plain"],
[".pko", "application/vnd.ms-pki.pko"],
[".pls", "audio/scpls"],
[".pma", "application/x-perfmon"],
[".pmc", "application/x-perfmon"],
[".pml", "application/x-perfmon"],
[".pmr", "application/x-perfmon"],
[".pmw", "application/x-perfmon"],
[".png", "image/png"],
[".pnm", "image/x-portable-anymap"],
[".pnt", "image/x-macpaint"],
[".pntg", "image/x-macpaint"],
[".pnz", "image/png"],
[".pot", "application/vnd.ms-powerpoint"],
[".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12"],
[".potx", "application/vnd.openxmlformats-officedocument.presentationml.template"],
[".ppa", "application/vnd.ms-powerpoint"],
[".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"],
[".ppm", "image/x-portable-pixmap"],
[".pps", "application/vnd.ms-powerpoint"],
[".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"],
[".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"],
[".ppt", "application/vnd.ms-powerpoint"],
[".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"],
[".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"],
[".prf", "application/pics-rules"],
[".prm", "application/octet-stream"],
[".prx", "application/octet-stream"],
[".ps", "application/postscript"],
[".psc1", "application/PowerShell"],
[".psd", "application/octet-stream"],
[".psess", "application/xml"],
[".psm", "application/octet-stream"],
[".psp", "application/octet-stream"],
[".pub", "application/x-mspublisher"],
[".pwz", "application/vnd.ms-powerpoint"],
[".qht", "text/x-html-insertion"],
[".qhtm", "text/x-html-insertion"],
[".qt", "video/quicktime"],
[".qti", "image/x-quicktime"],
[".qtif", "image/x-quicktime"],
[".qtl", "application/x-quicktimeplayer"],
[".qxd", "application/octet-stream"],
[".ra", "audio/x-pn-realaudio"],
[".ram", "audio/x-pn-realaudio"],
[".rar", "application/octet-stream"],
[".ras", "image/x-cmu-raster"],
[".rat", "application/rat-file"],
[".rc", "text/plain"],
[".rc2", "text/plain"],
[".rct", "text/plain"],
[".rdlc", "application/xml"],
[".resx", "application/xml"],
[".rf", "image/vnd.rn-realflash"],
[".rgb", "image/x-rgb"],
[".rgs", "text/plain"],
[".rm", "application/vnd.rn-realmedia"],
[".rmi", "audio/mid"],
[".rmp", "application/vnd.rn-rn_music_package"],
[".roff", "application/x-troff"],
[".rpm", "audio/x-pn-realaudio-plugin"],
[".rqy", "text/x-ms-rqy"],
[".rtf", "application/rtf"],
[".rtx", "text/richtext"],
[".ruleset", "application/xml"],
[".s", "text/plain"],
[".safariextz", "application/x-safari-safariextz"],
[".scd", "application/x-msschedule"],
[".sct", "text/scriptlet"],
[".sd2", "audio/x-sd2"],
[".sdp", "application/sdp"],
[".sea", "application/octet-stream"],
[".searchConnector-ms", "application/windows-search-connector+xml"],
[".setpay", "application/set-payment-initiation"],
[".setreg", "application/set-registration-initiation"],
[".settings", "application/xml"],
[".sgimb", "application/x-sgimb"],
[".sgml", "text/sgml"],
[".sh", "application/x-sh"],
[".shar", "application/x-shar"],
[".shtml", "text/html"],
[".sit", "application/x-stuffit"],
[".sitemap", "application/xml"],
[".skin", "application/xml"],
[".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12"],
[".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"],
[".slk", "application/vnd.ms-excel"],
[".sln", "text/plain"],
[".slupkg-ms", "application/x-ms-license"],
[".smd", "audio/x-smd"],
[".smi", "application/octet-stream"],
[".smx", "audio/x-smd"],
[".smz", "audio/x-smd"],
[".snd", "audio/basic"],
[".snippet", "application/xml"],
[".snp", "application/octet-stream"],
[".sol", "text/plain"],
[".sor", "text/plain"],
[".spc", "application/x-pkcs7-certificates"],
[".spl", "application/futuresplash"],
[".src", "application/x-wais-source"],
[".srf", "text/plain"],
[".SSISDeploymentManifest", "text/xml"],
[".ssm", "application/streamingmedia"],
[".sst", "application/vnd.ms-pki.certstore"],
[".stl", "application/vnd.ms-pki.stl"],
[".sv4cpio", "application/x-sv4cpio"],
[".sv4crc", "application/x-sv4crc"],
[".svc", "application/xml"],
[".swf", "application/x-shockwave-flash"],
[".t", "application/x-troff"],
[".tar", "application/x-tar"],
[".tcl", "application/x-tcl"],
[".testrunconfig", "application/xml"],
[".testsettings", "application/xml"],
[".tex", "application/x-tex"],
[".texi", "application/x-texinfo"],
[".texinfo", "application/x-texinfo"],
[".tgz", "application/x-compressed"],
[".thmx", "application/vnd.ms-officetheme"],
[".thn", "application/octet-stream"],
[".tif", "image/tiff"],
[".tiff", "image/tiff"],
[".tlh", "text/plain"],
[".tli", "text/plain"],
[".toc", "application/octet-stream"],
[".tr", "application/x-troff"],
[".trm", "application/x-msterminal"],
[".trx", "application/xml"],
[".ts", "video/vnd.dlna.mpeg-tts"],
[".tsv", "text/tab-separated-values"],
[".ttf", "application/octet-stream"],
[".tts", "video/vnd.dlna.mpeg-tts"],
[".txt", "text/plain"],
[".u32", "application/octet-stream"],
[".uls", "text/iuls"],
[".user", "text/plain"],
[".ustar", "application/x-ustar"],
[".vb", "text/plain"],
[".vbdproj", "text/plain"],
[".vbk", "video/mpeg"],
[".vbproj", "text/plain"],
[".vbs", "text/vbscript"],
[".vcf", "text/x-vcard"],
[".vcproj", "Application/xml"],
[".vcs", "text/plain"],
[".vcxproj", "Application/xml"],
[".vddproj", "text/plain"],
[".vdp", "text/plain"],
[".vdproj", "text/plain"],
[".vdx", "application/vnd.ms-visio.viewer"],
[".vml", "text/xml"],
[".vscontent", "application/xml"],
[".vsct", "text/xml"],
[".vsd", "application/vnd.visio"],
[".vsi", "application/ms-vsi"],
[".vsix", "application/vsix"],
[".vsixlangpack", "text/xml"],
[".vsixmanifest", "text/xml"],
[".vsmdi", "application/xml"],
[".vspscc", "text/plain"],
[".vss", "application/vnd.visio"],
[".vsscc", "text/plain"],
[".vssettings", "text/xml"],
[".vssscc", "text/plain"],
[".vst", "application/vnd.visio"],
[".vstemplate", "text/xml"],
[".vsto", "application/x-ms-vsto"],
[".vsw", "application/vnd.visio"],
[".vsx", "application/vnd.visio"],
[".vtx", "application/vnd.visio"],
[".wav", "audio/wav"],
[".wave", "audio/wav"],
[".wax", "audio/x-ms-wax"],
[".wbk", "application/msword"],
[".wbmp", "image/vnd.wap.wbmp"],
[".wcm", "application/vnd.ms-works"],
[".wdb", "application/vnd.ms-works"],
[".wdp", "image/vnd.ms-photo"],
[".webarchive", "application/x-safari-webarchive"],
[".webtest", "application/xml"],
[".wiq", "application/xml"],
[".wiz", "application/msword"],
[".wks", "application/vnd.ms-works"],
[".WLMP", "application/wlmoviemaker"],
[".wlpginstall", "application/x-wlpg-detect"],
[".wlpginstall3", "application/x-wlpg3-detect"],
[".wm", "video/x-ms-wm"],
[".wma", "audio/x-ms-wma"],
[".wmd", "application/x-ms-wmd"],
[".wmf", "application/x-msmetafile"],
[".wml", "text/vnd.wap.wml"],
[".wmlc", "application/vnd.wap.wmlc"],
[".wmls", "text/vnd.wap.wmlscript"],
[".wmlsc", "application/vnd.wap.wmlscriptc"],
[".wmp", "video/x-ms-wmp"],
[".wmv", "video/x-ms-wmv"],
[".wmx", "video/x-ms-wmx"],
[".wmz", "application/x-ms-wmz"],
[".wpl", "application/vnd.ms-wpl"],
[".wps", "application/vnd.ms-works"],
[".wri", "application/x-mswrite"],
[".wrl", "x-world/x-vrml"],
[".wrz", "x-world/x-vrml"],
[".wsc", "text/scriptlet"],
[".wsdl", "text/xml"],
[".wvx", "video/x-ms-wvx"],
[".x", "application/directx"],
[".xaf", "x-world/x-vrml"],
[".xaml", "application/xaml+xml"],
[".xap", "application/x-silverlight-app"],
[".xbap", "application/x-ms-xbap"],
[".xbm", "image/x-xbitmap"],
[".xdr", "text/plain"],
[".xht", "application/xhtml+xml"],
[".xhtml", "application/xhtml+xml"],
[".xla", "application/vnd.ms-excel"],
[".xlam", "application/vnd.ms-excel.addin.macroEnabled.12"],
[".xlc", "application/vnd.ms-excel"],
[".xld", "application/vnd.ms-excel"],
[".xlk", "application/vnd.ms-excel"],
[".xll", "application/vnd.ms-excel"],
[".xlm", "application/vnd.ms-excel"],
[".xls", "application/vnd.ms-excel"],
[".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"],
[".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"],
[".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],
[".xlt", "application/vnd.ms-excel"],
[".xltm", "application/vnd.ms-excel.template.macroEnabled.12"],
[".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"],
[".xlw", "application/vnd.ms-excel"],
[".xml", "text/xml"],
[".xmta", "application/xml"],
[".xof", "x-world/x-vrml"],
[".XOML", "text/plain"],
[".xpm", "image/x-xpixmap"],
[".xps", "application/vnd.ms-xpsdocument"],
[".xrm-ms", "text/xml"],
[".xsc", "application/xml"],
[".xsd", "text/xml"],
[".xsf", "text/xml"],
[".xsl", "text/xml"],
[".xslt", "text/xml"],
[".xsn", "application/octet-stream"],
[".xss", "application/xml"],
[".xtp", "application/octet-stream"],
[".xwd", "image/x-xwindowdump"],
[".z", "application/x-compress"],
[".zip", "application/x-zip-compressed"]
];
// ----------------------- End of Extensions to MIME --------- //
MozWebSocket
MozWebSocket
Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.
See caniuse for the current status of WebSockets support in desktop and mobile browsers.
See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.
It depends on which language you use.
In Java/Java EE:
V 7.5 supports RFC6455
- Jetty 9.1 supports javax.websocket / JSR 356)V 3.1.2 supports RFC6455
V 4.0.25 supports RFC6455
V 7.0.28 supports RFC6455
Some other Java implementations:
V 5.6 supports RFC6455
V 2.10 supports RFC6455
In C#:
In PHP:
In Python:
In C:
In Node.js:
Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :
Pusher.com is a Websocket cloud service accessible through a REST API.
DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.
Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.
For other language implementations, see the Wikipedia article for more information.
The RFC for Websockets : RFC6455
This is a bit of a cheat but I just set a default style and then overrode it using a DataTrigger if the value is null...
<Style>
<!-- Highlight for Reviewed (Default) -->
<Setter Property="Control.Background" Value="PaleGreen" />
<Style.Triggers>
<!-- Highlight for Not Reviewed -->
<DataTrigger Binding="{Binding Path=REVIEWEDBY}" Value="{x:Null}">
<Setter Property="Control.Background" Value="LightIndianRed" />
</DataTrigger>
</Style.Triggers>
</Style>
You should do it with getActivity().startActivity(myIntent)
Note also that installing Git for Windows from git-scm.com also installs Curl. You can then run Curl from Git for Windows' BASH terminal (not the default Windows CMD terminal).
Based on zainengineer's answer... Another approach is to make a deep copy of the object and strip circular references and stringify the result.
function cleanStringify(object) {_x000D_
if (object && typeof object === 'object') {_x000D_
object = copyWithoutCircularReferences([object], object);_x000D_
}_x000D_
return JSON.stringify(object);_x000D_
_x000D_
function copyWithoutCircularReferences(references, object) {_x000D_
var cleanObject = {};_x000D_
Object.keys(object).forEach(function(key) {_x000D_
var value = object[key];_x000D_
if (value && typeof value === 'object') {_x000D_
if (references.indexOf(value) < 0) {_x000D_
references.push(value);_x000D_
cleanObject[key] = copyWithoutCircularReferences(references, value);_x000D_
references.pop();_x000D_
} else {_x000D_
cleanObject[key] = '###_Circular_###';_x000D_
}_x000D_
} else if (typeof value !== 'function') {_x000D_
cleanObject[key] = value;_x000D_
}_x000D_
});_x000D_
return cleanObject;_x000D_
}_x000D_
}_x000D_
_x000D_
// Example_x000D_
_x000D_
var a = {_x000D_
name: "a"_x000D_
};_x000D_
_x000D_
var b = {_x000D_
name: "b"_x000D_
};_x000D_
_x000D_
b.a = a;_x000D_
a.b = b;_x000D_
_x000D_
console.log(cleanStringify(a));_x000D_
console.log(cleanStringify(b));
_x000D_
package com.copy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class CopyArray {
public static void main(String[] args) {
List<Integer> list1, list2 = null;
Integer[] intarr = { 3, 4, 2, 1 };
list1 = new ArrayList<Integer>(Arrays.asList(intarr));
list1.add(30);
list2 = Arrays.asList(intarr);
// list2.add(40); Here, we can't modify the existing list,because it's a wrapper
System.out.println("List1");
Iterator<Integer> itr1 = list1.iterator();
while (itr1.hasNext()) {
System.out.println(itr1.next());
}
System.out.println("List2");
Iterator<Integer> itr2 = list2.iterator();
while (itr2.hasNext()) {
System.out.println(itr2.next());
}
}
}
You can use any of these:
# Create a range that does not contain 50
for i in [x for x in xrange(100) if x != 50]:
print i
# Create 2 ranges [0,49] and [51, 100] (Python 2)
for i in range(50) + range(51, 100):
print i
# Create a iterator and skip 50
xr = iter(xrange(100))
for i in xr:
print i
if i == 49:
next(xr)
# Simply continue in the loop if the number is 50
for i in range(100):
if i == 50:
continue
print i
To go up a directory in a link, use ..
. This means "go up one directory", so your link will look something like this:
<a href="../index.html">Home</a>
std::string::iterator end_pos = std::remove(str.begin(), str.end(), ' ');
str.erase(end_pos, str.end());
if version < 8.4.0
pg_dump -D -t <table> <database>
Add -a
before the -t
if you only want the INSERTs, without the CREATE TABLE etc to set up the table in the first place.
version >= 8.4.0
pg_dump --column-inserts --data-only --table=<table> <database>
I just had the same problem. It is not a network permission but rather thread issue. Below code helped me to solve it. Put is in main activity
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
If you specifically have an array of arrays that doesn't go further than one level deep (a use case I find common) you can get away with array_merge
and the splat operator.
<?php
$notFlat = [[1,2],[3,4]];
$flat = array_merge(...$notFlat);
var_dump($flat);
Output:
array(4) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
}
The splat operator effectively changes the array of arrays to a list of arrays as arguments for array_merge
.
I found JXDatePicker as a better solution to this. It gives what you need and very easy to use.
import java.text.SimpleDateFormat; import java.util.Calendar; import javax.swing.JFrame; import javax.swing.JPanel; import org.jdesktop.swingx.JXDatePicker; public class DatePickerExample extends JPanel { public static void main(String[] args) { JFrame frame = new JFrame("JXPicker Example"); JPanel panel = new JPanel(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds(400, 400, 250, 100); JXDatePicker picker = new JXDatePicker(); picker.setDate(Calendar.getInstance().getTime()); picker.setFormats(new SimpleDateFormat("dd.MM.yyyy")); panel.add(picker); frame.getContentPane().add(panel); frame.setVisible(true); } }
Slight variation, main difference being to set the primary key field ("varname") to null, which produces a warning but works. By setting the primary key to null, the auto-increment works when inserting the record in the last statement.
This code also cleans up previous attempts, and can be run more than once without problems:
DELETE FROM `tbl` WHERE varname="primary key value for new record";
DROP TABLE tmp;
CREATE TEMPORARY TABLE tmp SELECT * FROM `tbl` WHERE varname="primary key value for old record";
UPDATE tmp SET varname=NULL;
INSERT INTO `tbl` SELECT * FROM tmp;
dropdownlist.Items.Insert(0, new Listitem("--Select One--", "0");
This is what I did at the end of the day - works fine now :
@Override
public void onClick(View v) {
my_button.setBackgroundResource(R.drawable.icon);
// SLEEP 2 SECONDS HERE ...
final Handler handler = new Handler();
Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
my_button.setBackgroundResource(R.drawable.defaultcard);
}
});
}
}, 2000);
}
The problem is that variables declared in one case
are still visible in the subsequent case
s unless an explicit { }
block is used, but they will not be initialized because the initialization code belongs to another case
.
In the following code, if foo
equals 1, everything is ok, but if it equals 2, we'll accidentally use the i
variable which does exist but probably contains garbage.
switch(foo) {
case 1:
int i = 42; // i exists all the way to the end of the switch
dostuff(i);
break;
case 2:
dostuff(i*2); // i is *also* in scope here, but is not initialized!
}
Wrapping the case in an explicit block solves the problem:
switch(foo) {
case 1:
{
int i = 42; // i only exists within the { }
dostuff(i);
break;
}
case 2:
dostuff(123); // Now you cannot use i accidentally
}
To further elaborate, switch
statements are just a particularly fancy kind of a goto
. Here's an analoguous piece of code exhibiting the same issue but using a goto
instead of a switch
:
int main() {
if(rand() % 2) // Toss a coin
goto end;
int i = 42;
end:
// We either skipped the declaration of i or not,
// but either way the variable i exists here, because
// variable scopes are resolved at compile time.
// Whether the *initialization* code was run, though,
// depends on whether rand returned 0 or 1.
std::cout << i;
}
It is related to generics in java. If I mentioned ArrayList<String>
that means I can add only String type object to that ArrayList.
The two major benefits of generics in Java are:
I can recommend Elasticvue, which is modern, free and open source. It allows accessing your ES instance via browser add-ons quite easily (supports Firefox, Chrome, Edge). But there are also further ways.
Just make sure you set cors values in elasticsearch.yml appropiate.
Alternatively to the suggested 3 methods you can try let
which carries out arithmetic operations on variables as follows:
let COUNT=$FIRSTV-$SECONDV
or
let COUNT=FIRSTV-SECONDV
Yes, git rm <filename>
will stage the deleted state of a file, where <filename>
could be a glob pattern:
$ git rm modules/welcome/language/*/kaimonokago_lang.php
rm modules/welcome/language/english/kaimonokago_lang.php
rm modules/welcome/language/french/kaimonokago_lang.php
rm modules/welcome/language/german/kaimonokago_lang.php
rm modules/welcome/language/norwegian/kaimonokago_lang.php
$ git status
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# deleted: modules/welcome/language/english/kaimonokago_lang.php
# ...
Then, you can commit.
git commit -a
will do this in one go, if you want.
You can also use git add -u
to stage all the changes, including all the deleted files, then commit.
python enumerate
function will be satisfied your requirements
result = list(enumerate([1,3,7,12]))
print result
output
[(0, 1), (1, 3), (2, 7),(3,12)]
I think this wikipedia article may help clarify.
http://en.wikipedia.org/wiki/DUAL_table
The DUAL table is a special one-row table present by default in all Oracle database installations. It is suitable for use in selecting a pseudocolumn such as SYSDATE or USER The table has a single VARCHAR2(1) column called DUMMY that has a value of "X"
Here is a link to W3Schools that answers your question https://www.w3schools.com/bootstrap/bootstrap_ref_js_modal.asp
Note: For anchor tag elements, omit data-target, and use href="#modalID" instead:
I hope that helps
Here is my approach that you may try:
import numpy as np
import matplotlib.pyplot as plt
w=10
h=10
fig=plt.figure(figsize=(8, 8))
columns = 4
rows = 5
for i in range(1, columns*rows +1):
img = np.random.randint(10, size=(h,w))
fig.add_subplot(rows, columns, i)
plt.imshow(img)
plt.show()
The resulting image:
(Original answer date: Oct 7 '17 at 4:20)
Edit 1
Since this answer is popular beyond my expectation. And I see that a small change is needed to enable flexibility for the manipulation of the individual plots. So that I offer this new version to the original code. In essence, it provides:-
New code:
import numpy as np
import matplotlib.pyplot as plt
w = 10
h = 10
fig = plt.figure(figsize=(9, 13))
columns = 4
rows = 5
# prep (x,y) for extra plotting
xs = np.linspace(0, 2*np.pi, 60) # from 0 to 2pi
ys = np.abs(np.sin(xs)) # absolute of sine
# ax enables access to manipulate each of subplots
ax = []
for i in range(columns*rows):
img = np.random.randint(10, size=(h,w))
# create subplot and append to ax
ax.append( fig.add_subplot(rows, columns, i+1) )
ax[-1].set_title("ax:"+str(i)) # set title
plt.imshow(img, alpha=0.25)
# do extra plots on selected axes/subplots
# note: index starts with 0
ax[2].plot(xs, 3*ys)
ax[19].plot(ys**2, xs)
plt.show() # finally, render the plot
The resulting plot:
Edit 2
In the previous example, the code provides access to the sub-plots with single index, which is inconvenient when the figure has many rows/columns of sub-plots. Here is an alternative of it. The code below provides access to the sub-plots with [row_index][column_index]
, which is more suitable for manipulation of array of many sub-plots.
import matplotlib.pyplot as plt
import numpy as np
# settings
h, w = 10, 10 # for raster image
nrows, ncols = 5, 4 # array of sub-plots
figsize = [6, 8] # figure size, inches
# prep (x,y) for extra plotting on selected sub-plots
xs = np.linspace(0, 2*np.pi, 60) # from 0 to 2pi
ys = np.abs(np.sin(xs)) # absolute of sine
# create figure (fig), and array of axes (ax)
fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=figsize)
# plot simple raster image on each sub-plot
for i, axi in enumerate(ax.flat):
# i runs from 0 to (nrows*ncols-1)
# axi is equivalent with ax[rowid][colid]
img = np.random.randint(10, size=(h,w))
axi.imshow(img, alpha=0.25)
# get indices of row/column
rowid = i // ncols
colid = i % ncols
# write row/col indices as axes' title for identification
axi.set_title("Row:"+str(rowid)+", Col:"+str(colid))
# one can access the axes by ax[row_id][col_id]
# do additional plotting on ax[row_id][col_id] of your choice
ax[0][2].plot(xs, 3*ys, color='red', linewidth=3)
ax[4][3].plot(ys**2, xs, color='green', linewidth=3)
plt.tight_layout(True)
plt.show()
The resulting plot:
Disclaim: the following suggestion could be an overhead depending on the situation. The function is only tested with MSSQL 2008 R2 but seams be compatible to other versions
if you wane do this with many Id's you may could use a function which creates a temp table where you will be able to DELETE FROM the selection
how the query could look like:
-- not tested
-- @ids will contain a varchar with your ids e.g.'9 12 27 37'
DELETE FROM table WHERE id IN (SELECT i.number FROM iter_intlist_to_tbl(@ids))
here is the function:
ALTER FUNCTION iter_intlist_to_tbl (@list nvarchar(MAX))
RETURNS @tbl TABLE (listpos int IDENTITY(1, 1) NOT NULL,
number int NOT NULL) AS
-- funktion gefunden auf http://www.sommarskog.se/arrays-in-sql-2005.html
-- dient zum übergeben einer liste von elementen
BEGIN
-- Deklaration der Variablen
DECLARE @startpos int,
@endpos int,
@textpos int,
@chunklen smallint,
@str nvarchar(4000),
@tmpstr nvarchar(4000),
@leftover nvarchar(4000)
-- Startwerte festlegen
SET @textpos = 1
SET @leftover = ''
-- Loop 1
WHILE @textpos <= datalength(@list) / 2
BEGIN
--
SET @chunklen = 4000 - datalength(@leftover) / 2 --datalength() gibt die anzahl der bytes zurück (mit Leerzeichen)
--
SET @tmpstr = ltrim(@leftover + substring(@list, @textpos, @chunklen))--SUBSTRING ( @string ,start , length ) | ltrim(@string) abschneiden aller Leerzeichen am Begin des Strings
--hochzählen der TestPosition
SET @textpos = @textpos + @chunklen
--start position 0 setzen
SET @startpos = 0
-- end position bekommt den charindex wo ein [LEERZEICHEN] gefunden wird
SET @endpos = charindex(' ' COLLATE Slovenian_BIN2, @tmpstr)--charindex(searchChar,Wo,Startposition)
-- Loop 2
WHILE @endpos > 0
BEGIN
--str ist der string welcher zwischen den [LEERZEICHEN] steht
SET @str = substring(@tmpstr, @startpos + 1, @endpos - @startpos - 1)
--wenn @str nicht leer ist wird er zu int Convertiert und @tbl unter der Spalte 'number' hinzugefügt
IF @str <> ''
INSERT @tbl (number) VALUES(convert(int, @str))-- convert(Ziel-Type,Value)
-- start wird auf das letzte bekannte end gesetzt
SET @startpos = @endpos
-- end position bekommt den charindex wo ein [LEERZEICHEN] gefunden wird
SET @endpos = charindex(' ' COLLATE Slovenian_BIN2, @tmpstr, @startpos + 1)
END
-- Loop 2
-- dient dafür den letzten teil des strings zu selektieren
SET @leftover = right(@tmpstr, datalength(@tmpstr) / 2 - @startpos)--right(@string,anzahl der Zeichen) bsp.: right("abcdef",3) => "def"
END
-- Loop 1
--wenn @leftover nach dem entfernen aller [LEERZEICHEN] nicht leer ist wird er zu int Convertiert und @tbl unter der Spalte 'number' hinzugefügt
IF ltrim(rtrim(@leftover)) <> ''
INSERT @tbl (number) VALUES(convert(int, @leftover))
RETURN
END
-- ############################ WICHTIG ############################
-- das is ein Beispiel wie man die Funktion benutzt
--
--CREATE PROCEDURE get_product_names_iter
-- @ids varchar(50) AS
--SELECT P.ProductName, P.ProductID
--FROM Northwind.Products P
--JOIN iter_intlist_to_tbl(@ids) i ON P.ProductID = i.number
--go
--EXEC get_product_names_iter '9 12 27 37'
--
-- Funktion gefunden auf http://www.sommarskog.se/arrays-in-sql-2005.html
-- dient zum übergeben einer Liste von Id's
-- ############################ WICHTIG ############################
If you pass jQuery a function, it will not run until the page has loaded:
<script type="text/javascript">
$(function() {
//your header rotation code goes here
});
</script>
If you have a SSHClient, you can also use open_sftp()
:
import paramiko
# lets say you have SSH client...
client = paramiko.SSHClient()
sftp = client.open_sftp()
# then you can use upload & download as shown above
...
For some reason the android:textColor only seems to update the title color. You can change the message text color by using a
SpannableString.AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.MyDialogTheme));
AlertDialog dialog = builder.create();
Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");
wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
dialog.setMessage(wordtoSpan);
dialog.show();
You could try qemu, which is what the Android emulator uses. I believe it actually emulates the ARM hardware.
You can try below query:
select
count(*)
from
all_tab_columns
where
table_name = 'your_table'
You can use the custom TextView for whole app with custom font here is an example for that
public class MyTextView extends TextView {
Typeface normalTypeface = Typeface.createFromAsset(getContext().getAssets(), Constants.FONT_REGULAR);
Typeface boldTypeface = Typeface.createFromAsset(getContext().getAssets(), Constants.FONT_BOLD);
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyTextView(Context context) {
super(context);
}
public void setTypeface(Typeface tf, int style) {
if (style == Typeface.BOLD) {
super.setTypeface(boldTypeface/*, -1*/);
} else {
super.setTypeface(normalTypeface/*, -1*/);
}
}
}
The latest way to do that from the documentation is to use the ConnectivityManager
to query the active network and determine if it has Internet connectivity.
public boolean hasInternetConnectivity() {
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return (activeNetwork != null &&
activeNetwork.isConnectedOrConnecting());
}
Add these two permissions to your AndroidManifest.xml file:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
After some search, I've found a cleaner solution wich use the %
operator.
In your YAML file :
key : 'This is the foobar var : %{foobar}'
In your ruby code :
require 'yaml'
file = YAML.load_file('your_file.yml')
foobar = 'Hello World !'
content = file['key']
modified_content = content % { :foobar => foobar }
puts modified_content
And the output is :
This is the foobar var : Hello World !
As @jschorr said in the comment, you can also add multiple variable to the value in the Yaml file :
Yaml :
key : 'The foo var is %{foo} and the bar var is %{bar} !'
Ruby :
# ...
foo = 'FOO'
bar = 'BAR'
# ...
modified_content = content % { :foo => foo, :bar => bar }
Output :
The foo var is FOO and the bar var is BAR !
Displaying an Image
in WPF is much easier than that. Try this:
<Image Source="{Binding DisplayedImagePath}" HorizontalAlignment="Left"
Margin="0,0,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Bottom"
Grid.Row="8" Width="200" Grid.ColumnSpan="2" />
And the property can just be a string
:
public string DisplayedImage
{
get { return @"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg"; }
}
Although you really should add your images to a folder named Images
in the root of your project and set their Build Action to Resource in the Properties Window in Visual Studio... you could then access them using this format:
public string DisplayedImage
{
get { return "/AssemblyName;component/Images/ImageName.jpg"; }
}
UPDATE >>>
As a final tip... if you ever have a problem with a control not working as expected, simply type 'WPF', the name of that control and then the word 'class' into a search engine. In this case, you would have typed 'WPF Image Class'. The top result will always be MSDN and if you click on the link, you'll find out all about that control and most pages have code examples as well.
UPDATE 2 >>>
If you followed the examples from the link to MSDN and it's not working, then your problem is not the Image
control. Using the string
property that I suggested, try this:
<StackPanel>
<Image Source="{Binding DisplayedImagePath}" />
<TextBlock Text="{Binding DisplayedImagePath}" />
</StackPanel>
If you can't see the file path in the TextBlock
, then you probably haven't set your DataContext
to the instance of your view model. If you can see the text, then the problem is with your file path.
UPDATE 3 >>>
In .NET 4, the above Image.Source
values would work. However, Microsoft made some horrible changes in .NET 4.5 that broke many different things and so in .NET 4.5, you'd need to use the full pack
path like this:
<Image Source="pack://application:,,,/AssemblyName;component/Images/image_to_use.png">
For further information on pack URIs, please see the Pack URIs in WPF page on Microsoft Docs.
Parameter names are normally not accessible by the Java code at runtime (because it's drop by the compiler), so if you want that functionality you need to either use Java 8's built-in functionality or use a library such as ParaNamer in order to gain access to it.
So in order to not having to utilize annotations for the constructor arguments when using Jackson, you can make use of either of these 2 Jackson modules:
This module allows you to get annotation-free constructor arguments when using Java 8. In order to use it you first need to register the module:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new ParameterNamesModule());
Then compile your code using the -parameters flag:
javac -parameters ...
Link: https://github.com/FasterXML/jackson-modules-java8/tree/master/parameter-names
This other one simply requires you to register the module or configure an annotation introspection (but not both as pointed out by the comments). It allows you to use annotation-free constructor arguments on versions of Java prior to 1.8.
ObjectMapper mapper = new ObjectMapper();
// either via module
mapper.registerModule(new ParanamerModule());
// or by directly assigning annotation introspector (but not both!)
mapper.setAnnotationIntrospector(new ParanamerOnJacksonAnnotationIntrospector());
Link: https://github.com/FasterXML/jackson-modules-base/tree/master/paranamer
It's
#include <stdio.h>
int main(void) {
int x = 10;
while (x-- > 0) { // x goes to 0
printf("%d ", x);
}
return 0;
}
Just the space makes the things look funny, --
decrements and >
compares.
Use a list comprehension (this is the way to go in pure Python):
>>> l = [1, 2, 3, 4]
>>> [i**2 for i in l]
[1, 4, 9, 16]
Or numpy (a well-established module):
>>> numpy.array([1, 2, 3, 4])**2
array([ 1, 4, 9, 16])
In numpy
, math operations on arrays are, by default, executed element-wise. That's why you can **2
an entire array there.
Other possible solutions would be map
-based, but in this case I'd really go for the list comprehension. It's Pythonic :) and a map
-based solution that requires lambda
s is slower than LC.
Look at the following dataframe df
df
column1 column2 column3
0 1 11 21
1 2 12 22
2 3 13 23
3 4 14 24
4 5 15 25
5 6 16 26
6 7 17 27
7 8 18 28
8 9 19 29
9 10 20 30
Lets drop all the rows which has an odd number in column1
Create a list of all the elements in column1 and keep only those elements that are even numbers (the elements that you dont want to drop)
keep_elements = [x for x in df.column1 if x%2==0]
All the rows with the values [2, 4, 6, 8, 10]
in its column1 will be retained or not dropped.
df.set_index('column1',inplace = True)
df.drop(df.index.difference(keep_elements),axis=0,inplace=True)
df.reset_index(inplace=True)
We make the column1 as index and drop all the rows that are not required. Then we reset the index back.
df
column1 column2 column3
0 2 12 22
1 4 14 24
2 6 16 26
3 8 18 28
4 10 20 30
ls -t
list files by creation time not last modified time. Use ls -ltc
if you want to list files by last modified time from last to first(top to bottom). Thus to list the last n: ls -ltc | head ${n}
I faced the same issue while submitting the app using Xcode 4.6. It does not recognise the icons with dimension 120x120, 58x58, 29x29, etc. So when I tried to add these icons into the info.plist and submit the app for review, Xcode 4.6 did not allow me to do so. On submitting the app without the above icons, I got a mail saying -
"Your delivery was successful, but you may wish to correct the following issues in your next delivery: Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format."
Since, it was recommended and not necessary, I submitted the app anyhow. I added the above recommended icons to the bundle but did not specify them in the Info.plist. I got the same mail again. This time I ignored it and to my surprise the app was accepted.
I wanted my app to run on iOS 5 and above and therefore, I had to use Xcode 4.6 and not the latest Xcode 5 which properly allows only apps for iOS7 and above only.
UPDATE:
NOTE: "Starting February 1st 2014 new apps and app updates submitted to the App Store must be built with Xcode 5 and iOS 7 SDK". https://developer.apple.com/news/?id=12172013a#top
Thus, this scenario will be invalid in future.
Supposing the form is the direct parent you can do:
<a href='#' onclick='this.parentNode.submit(); return false;'>submit</a>
If not you can access through the forms name attribute like this:
<a href='#' onclick='document.forms["myform"].submit(); return false;'>submit</a>
See both examples here: http://jsfiddle.net/WEZDC/1/
The stat module will do this as well as obtain a lot of other information for files. From the example documentation:
- stat: path=/path/to/something
register: p
- debug: msg="Path exists and is a directory"
when: p.stat.isdir is defined and p.stat.isdir
Any user with a valid shell in /etc/passwd
can potentially login. If you want to improve security, set up SSH with public-key authentication (there is lots of info on the web on doing this), install a public key in one user's ~/.ssh/authorized_keys
file, and disable password-based authentication. This will prevent anybody except that one user from logging in, and will require that the user have in their possession the matching private key. Make sure the private key has a decent passphrase.
To prevent bots from trying to get in, run SSH on a port other than 22 (i.e. 3456). This doesn't improve security but prevents script-kiddies and bots from cluttering up your logs with failed attempts.
Quoted from this post:
The question is about how to make CTRL+SHIFT+U work in Visual Studio Code. Here is how to do it. (Version 1.8.1 or above). You can also choose a different key combination.
File-> Preferences -> Keyboard Shortcuts.
An editor will appear with
keybindings.json
file. Place the following JSON in there and save.[ { "key": "ctrl+shift+u", "command": "editor.action.transformToUppercase", "when": "editorTextFocus" }, { "key": "ctrl+shift+l", "command": "editor.action.transformToLowercase", "when": "editorTextFocus" } ]
Now CTRL+SHIFT+U will capitalise selected text, even if multi line. In the same way, CTRL+SHIFT+L will make selected text lowercase.
These commands are built into VS Code, and no extensions are required to make them work.
I guess something like this would work:
Add System.ServiceProcess
to your project references (It's on the .NET tab).
using System.ServiceProcess;
ServiceController sc = new ServiceController(SERVICENAME);
switch (sc.Status)
{
case ServiceControllerStatus.Running:
return "Running";
case ServiceControllerStatus.Stopped:
return "Stopped";
case ServiceControllerStatus.Paused:
return "Paused";
case ServiceControllerStatus.StopPending:
return "Stopping";
case ServiceControllerStatus.StartPending:
return "Starting";
default:
return "Status Changing";
}
Edit: There is also a method sc.WaitforStatus()
that takes a desired status and a timeout, never used it but it may suit your needs.
Edit: Once you get the status, to get the status again you will need to call sc.Refresh()
first.
Reference: ServiceController object in .NET.
Try this simple workaround.
var files = $("#file").get(0).files;
var size = files[0].size;
if (size >= 5000000) {
alert("File size is greater than or equal to 5 MB");
}
To read the data line-by-line into a Bash array you can do this:
while read -a row
do
echo "..${row[0]}..${row[1]}..${row[2]}.."
done < <(echo "SELECT A, B, C FROM table_a" | mysql database -u $user -p $password)
Or into individual variables:
while read a b c
do
echo "..${a}..${b}..${c}.."
done < <(echo "SELECT A, B, C FROM table_a" | mysql database -u $user -p $password)
The following is a way to achieve a fixed header table, I don't know if it will be enough for your purpose. Changes are:
It seems fully working on my local machine, but it's not fully working using Fiddle. It seems that Fiddle adds a css file (normalize.css) that in some way broke the plugin css (quite sure I can make fully working also in Fiddle adding some css clear rules, but not have time to investigate further now)
My working code snippet is below. Hope this can help.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.2.js'></script>
<script type='text/javascript' src="http://datatables.net/release-datatables/media/js/jquery.dataTables.min.js"></script>
<style type='text/css'>
div.box {
height: 100px;
padding: 10px;
overflow: auto;
border: 1px solid #8080FF;
background-color: #E5E5FF;
}
.standard-grid1, .standard-grid1 td, .standard-grid1 th {
border: solid black thin;
}
</style>
<script type='text/javascript'>
$(window).load(function(){
$(document).ready(function() {
var stdTable1 = $(".standard-grid1").dataTable({
"iDisplayLength": -1,
"bPaginate": true,
"iCookieDuration": 60,
"bStateSave": false,
"bAutoWidth": false,
//true
"bScrollAutoCss": true,
"bProcessing": true,
"bRetrieve": true,
"bJQueryUI": true,
"sDom": '<"H"CTrf>t<"F"lip>',
"aLengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]],
"sScrollX": "100%",
//"sScrollXInner": "110%",
"bScrollCollapse": true,
"fnInitComplete": function() {
this.css("visibility", "visible");
}
});
});
});
</script>
</head>
<body>
<div>
<table class="standard-grid1 full-width content-scrollable" id="PeopleIndexTable">
<thead>
<!-- put your table header HTML here -->
</thead>
<tbody>
<!-- put your table body HTML here -->
</tbody>
</table>
</div>
</body>
</html>
You can use WhereNotIn
in the following way:
$category=DB::table('category')
->whereNotIn('category_id',[14 ,15])
->get();`enter code here`
Visual Studio 2013 now supports setup projects. Microsoft have shipped a Visual Studio extension to produce setup projects.
you can use the views *_DEPENDENCIES
, for example:
SELECT owner, NAME
FROM dba_dependencies
WHERE referenced_owner = :table_owner
AND referenced_name = :table_name
AND TYPE IN ('PACKAGE', 'PACKAGE BODY')
Number of days calculation between two dates.
$(document).ready(function () {
$('.submit').on('click', function () {
var startDate = $('.start-date').val();
var endDate = $('.end-date').val();
var start = new Date(startDate);
var end = new Date(endDate);
var diffDate = (end - start) / (1000 * 60 * 60 * 24);
var days = Math.round(diffDate);
});
});
In Office Excel 2003, when you programmatically set a range value with an array containing a large string, you may receive an error message similar to the following:
Run-time error '1004'. Application-defined or operation-defined error.
This issue may occur if one or more of the cells in an array (range of cells) contain a character string that is set to contain more than 911 characters.
To work around this issue, edit the script so that no cells in the array contain a character string that holds more than 911 characters.
For example, the following line of code from the example code block below defines a character string that contains 912 characters:
Sub XLTest()
Dim aValues(4)
aValues(0) = "Test1"
aValues(1) = "Test2"
aValues(2) = "Test3"
MsgBox "First the Good range set."
aValues(3) = String(911, 65)
Range("A1:D1").Value = aValues
MsgBox "Now the bad range set."
aValues(3) = String(912, 66)
Range("A2:D2").Value = aValues
End Sub
Other versions of Excel or free alternatives like Calc should work as well.
The WhiteSpace CHAR can be referenced using ASCII Codes here. And Character# 32 represents a white space, Therefore:
char space = (char)32;
For example, you can use this approach to produce desired number of white spaces anywhere you want:
int _length = {desired number of white spaces}
string.Empty.PadRight(_length, (char)32));
Another option would be to use a procedure with output parameters - Using a Stored Procedure with Output Parameters
The formatting can be done like this (I assumed you meant HH:MM instead of HH:SS, but it's easy to change):
Time.now.strftime("%d/%m/%Y %H:%M")
#=> "14/09/2011 14:09"
Updated for the shifting:
d = DateTime.now
d.strftime("%d/%m/%Y %H:%M")
#=> "11/06/2017 18:11"
d.next_month.strftime("%d/%m/%Y %H:%M")
#=> "11/07/2017 18:11"
You need to require 'date'
for this btw.
This also works
SELECT TRANSLATE(STRING_WITH_NL_CR, CHAR(10) || CHAR(13), ' ') FROM DUAL;
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />
<div id="imgTest"></div>
<script type='text/javascript'>
function encodeImageFileAsURL() {
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("imgTest").innerHTML = newImage.outerHTML;
alert("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
console.log("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
}
fileReader.readAsDataURL(fileToLoad);
}
}
</script>
Reduce() is..
It was ..
let array=[1,2,3];
function sum(acc,val){ return acc+val;} // => can change to (acc,val)=>acc+val
let answer= array.reduce(sum); // answer is 6
Change to
let array=[1,2,3];
let answer=arrays.reduce((acc,val)=>acc+val);
Also you can use in
let array=[5,4,19,2,7];
function findMax(acc,val)
{
if(val>acc){
acc=val;
}
}
let biggest=arrays.reduce(findMax); // 19
arr = [1, 2, 5, 4, 6, 8, 9, 2, 1, 4, 5, 8, 9]
v = 0
for i in range(len(arr)):
v = v ^ arr[i]
print(value) //6
on duplicate key update, or insert ignore can be viable solutions with MySQL.
Example of on duplicate key update update based on mysql.com
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
UPDATE table SET c=c+1 WHERE a=1;
Example of insert ignore based on mysql.com
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name [(col_name,...)]
{VALUES | VALUE} ({expr | DEFAULT},...),(...),...
[ ON DUPLICATE KEY UPDATE
col_name=expr
[, col_name=expr] ... ]
Or:
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name
SET col_name={expr | DEFAULT}, ...
[ ON DUPLICATE KEY UPDATE
col_name=expr
[, col_name=expr] ... ]
Or:
INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name [(col_name,...)]
SELECT ...
[ ON DUPLICATE KEY UPDATE
col_name=expr
[, col_name=expr] ... ]
IIUC, if you make your (unfortunately named) List
into an ndarray
, you can simply index into it naturally.
>>> import numpy as np
>>> m = np.arange(16)*10
>>> m[df.A]
array([ 0, 40, 50, 60, 150, 150, 140, 130])
>>> df["D"] = m[df.A]
>>> df
A B C D
0 0 NaN NaN 0
1 4 NaN NaN 40
2 5 NaN NaN 50
3 6 NaN NaN 60
4 15 NaN NaN 150
5 15 NaN NaN 150
6 14 NaN NaN 140
7 13 NaN NaN 130
Here I built a new m
, but if you use m = np.asarray(List)
, the same thing should work: the values in df.A
will pick out the appropriate elements of m
.
Note that if you're using an old version of numpy
, you might have to use m[df.A.values]
instead-- in the past, numpy
didn't play well with others, and some refactoring in pandas
caused some headaches. Things have improved now.
Now python gives you the choice to install pip
during the installation (I am on Windows, and at least python does so for Windows!). Considering you had chosen to install pip
during installation of python (you don't actually have to choose because it is default), pip
is already installed for you. Then, type in pip
in command prompt, you should see a help come up. You can find necessary usage instructions there. E.g. pip list
shows you the list of installed packages. You can use
pip uninstall package_name
to uninstall any package that you don't want anymore. Read more here (pip documentation).
There is nothing called background opacity. Opacity is applied to the element, its contents and all its child elements. And this behavior cannot be changed just by overriding the opacity in child elements.
Child vs parent opacity has been a long standing issue and the most common fix for it is using rgba(r,g,b,alpha)
background colors. But in this case, since it is a background-image, that solution won't work. One solution would be to generate the image as a PNG with the required opacity in the image itself. Another solution would be to take the child div out and make it absolutely positioned.
In practice, I have found that you need to be a bit careful, especially if you are using a bit of xml repeatedly. Suppose, for example, that you have a table that you wish to create a table row for each entry in a list. You've set up some xml:
In my_table_row.xml
:
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" android:id="@+id/myTableRow">
<ImageButton android:src="@android:drawable/ic_menu_delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/rowButton"/>
<TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="TextView" android:id="@+id/rowText"></TextView>
</TableRow>
Then you want to create it once per row with some code. It assume that you have defined a parent TableLayout myTable to attach the Rows to.
for (int i=0; i<numRows; i++) {
/*
* 1. Make the row and attach it to myTable. For some reason this doesn't seem
* to return the TableRow as you might expect from the xml, so you need to
* receive the View it returns and then find the TableRow and other items, as
* per step 2.
*/
LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.my_table_row, myTable, true);
// 2. Get all the things that we need to refer to to alter in any way.
TableRow tr = (TableRow) v.findViewById(R.id.profileTableRow);
ImageButton rowButton = (ImageButton) v.findViewById(R.id.rowButton);
TextView rowText = (TextView) v.findViewById(R.id.rowText);
// 3. Configure them out as you need to
rowText.setText("Text for this row");
rowButton.setId(i); // So that when it is clicked we know which one has been clicked!
rowButton.setOnClickListener(this); // See note below ...
/*
* To ensure that when finding views by id on the next time round this
* loop (or later) gie lots of spurious, unique, ids.
*/
rowText.setId(1000+i);
tr.setId(3000+i);
}
For a clear simple example on handling rowButton.setOnClickListener(this), see Onclicklistener for a programatically created button.
Either return text/plain
(as in Return only string message from Spring MVC 3 Controller) OR wrap your String is some object
public class StringResponse {
private String response;
public StringResponse(String s) {
this.response = s;
}
// get/set omitted...
}
Set your response type to MediaType.APPLICATION_JSON_VALUE
(= "application/json"
)
@RequestMapping(value = "/getString", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
and you'll have a JSON that looks like
{ "response" : "your string value" }
pd.unique
returns the unique values from an input array, or DataFrame column or index.
The input to this function needs to be one-dimensional, so multiple columns will need to be combined. The simplest way is to select the columns you want and then view the values in a flattened NumPy array. The whole operation looks like this:
>>> pd.unique(df[['Col1', 'Col2']].values.ravel('K'))
array(['Bob', 'Joe', 'Bill', 'Mary', 'Steve'], dtype=object)
Note that ravel()
is an array method that returns a view (if possible) of a multidimensional array. The argument 'K'
tells the method to flatten the array in the order the elements are stored in the memory (pandas typically stores underlying arrays in Fortran-contiguous order; columns before rows). This can be significantly faster than using the method's default 'C' order.
An alternative way is to select the columns and pass them to np.unique
:
>>> np.unique(df[['Col1', 'Col2']].values)
array(['Bill', 'Bob', 'Joe', 'Mary', 'Steve'], dtype=object)
There is no need to use ravel()
here as the method handles multidimensional arrays. Even so, this is likely to be slower than pd.unique
as it uses a sort-based algorithm rather than a hashtable to identify unique values.
The difference in speed is significant for larger DataFrames (especially if there are only a handful of unique values):
>>> df1 = pd.concat([df]*100000, ignore_index=True) # DataFrame with 500000 rows
>>> %timeit np.unique(df1[['Col1', 'Col2']].values)
1 loop, best of 3: 1.12 s per loop
>>> %timeit pd.unique(df1[['Col1', 'Col2']].values.ravel('K'))
10 loops, best of 3: 38.9 ms per loop
>>> %timeit pd.unique(df1[['Col1', 'Col2']].values.ravel()) # ravel using C order
10 loops, best of 3: 49.9 ms per loop
I've made a gist with THE perfect method to manage fragment replacement and lifecycle.
It only replace the current fragment by a new one, if it's not the same and if it's not in backstack (in this case it will pop it).
It contain several option as if you want the fragment to be saved in backstack.
Using this and a single Activity, you may want to add this to your activity:
@Override
public void onBackPressed() {
int fragments = getSupportFragmentManager().getBackStackEntryCount();
if (fragments == 1) {
finish();
return;
}
super.onBackPressed();
}
Optimizing cache usage largely comes down to two factors.
The first factor (to which others have already alluded) is locality of reference. Locality of reference really has two dimensions though: space and time.
The spatial dimension also comes down to two things: first, we want to pack our information densely, so more information will fit in that limited memory. This means (for example) that you need a major improvement in computational complexity to justify data structures based on small nodes joined by pointers.
Second, we want information that will be processed together also located together. A typical cache works in "lines", which means when you access some information, other information at nearby addresses will be loaded into the cache with the part we touched. For example, when I touch one byte, the cache might load 128 or 256 bytes near that one. To take advantage of that, you generally want the data arranged to maximize the likelihood that you'll also use that other data that was loaded at the same time.
For just a really trivial example, this can mean that a linear search can be much more competitive with a binary search than you'd expect. Once you've loaded one item from a cache line, using the rest of the data in that cache line is almost free. A binary search becomes noticeably faster only when the data is large enough that the binary search reduces the number of cache lines you access.
The time dimension means that when you do some operations on some data, you want (as much as possible) to do all the operations on that data at once.
Since you've tagged this as C++, I'll point to a classic example of a relatively cache-unfriendly design: std::valarray
. valarray
overloads most arithmetic operators, so I can (for example) say a = b + c + d;
(where a
, b
, c
and d
are all valarrays) to do element-wise addition of those arrays.
The problem with this is that it walks through one pair of inputs, puts results in a temporary, walks through another pair of inputs, and so on. With a lot of data, the result from one computation may disappear from the cache before it's used in the next computation, so we end up reading (and writing) the data repeatedly before we get our final result. If each element of the final result will be something like (a[n] + b[n]) * (c[n] + d[n]);
, we'd generally prefer to read each a[n]
, b[n]
, c[n]
and d[n]
once, do the computation, write the result, increment n
and repeat 'til we're done.2
The second major factor is avoiding line sharing. To understand this, we probably need to back up and look a little at how caches are organized. The simplest form of cache is direct mapped. This means one address in main memory can only be stored in one specific spot in the cache. If we're using two data items that map to the same spot in the cache, it works badly -- each time we use one data item, the other has to be flushed from the cache to make room for the other. The rest of the cache might be empty, but those items won't use other parts of the cache.
To prevent this, most caches are what are called "set associative". For example, in a 4-way set-associative cache, any item from main memory can be stored at any of 4 different places in the cache. So, when the cache is going to load an item, it looks for the least recently used3 item among those four, flushes it to main memory, and loads the new item in its place.
The problem is probably fairly obvious: for a direct-mapped cache, two operands that happen to map to the same cache location can lead to bad behavior. An N-way set-associative cache increases the number from 2 to N+1. Organizing a cache into more "ways" takes extra circuitry and generally runs slower, so (for example) an 8192-way set associative cache is rarely a good solution either.
Ultimately, this factor is more difficult to control in portable code though. Your control over where your data is placed is usually fairly limited. Worse, the exact mapping from address to cache varies between otherwise similar processors. In some cases, however, it can be worth doing things like allocating a large buffer, and then using only parts of what you allocated to ensure against data sharing the same cache lines (even though you'll probably need to detect the exact processor and act accordingly to do this).
There's another, related item called "false sharing". This arises in a multiprocessor or multicore system, where two (or more) processors/cores have data that's separate, but falls in the same cache line. This forces the two processors/cores to coordinate their access to the data, even though each has its own, separate data item. Especially if the two modify the data in alternation, this can lead to a massive slowdown as the data has to be constantly shuttled between the processors. This can't easily be cured by organizing the cache into more "ways" or anything like that either. The primary way to prevent it is to ensure that two threads rarely (preferably never) modify data that could possibly be in the same cache line (with the same caveats about difficulty of controlling the addresses at which data is allocated).
Those who know C++ well might wonder if this is open to optimization via something like expression templates. I'm pretty sure the answer is that yes, it could be done and if it was, it would probably be a pretty substantial win. I'm not aware of anybody having done so, however, and given how little valarray
gets used, I'd be at least a little surprised to see anybody do so either.
In case anybody wonders how valarray
(designed specifically for performance) could be this badly wrong, it comes down to one thing: it was really designed for machines like the older Crays, that used fast main memory and no cache. For them, this really was a nearly ideal design.
Yes, I'm simplifying: most caches don't really measure the least recently used item precisely, but they use some heuristic that's intended to be close to that without having to keep a full time-stamp for each access.
While Fosco's answer is not wrong there is a case to be considered with this one: mixed arrays. Imagine I have an array like this:
$a = array(
"nice",
"car" => "fast",
"none"
);
Now, PHP allows this kind of syntax but it has one problem: if I run Fosco's code I get 0
which is wrong for me, but why this happens?
Because when doing comparisons between strings and integers PHP converts strings to integers (and this is kinda stupid in my opinion), so when array_search()
searches for the index it stops at the first one because apparently ("car" == 0)
is true.
Setting array_search()
to strict mode won't solve the problem because then array_search("0", array_keys($a))
would return false even if an element with index 0 exists.
So my solution just converts all indexes from array_keys()
to strings and then compares them correctly:
echo array_search("car", array_map("strval", array_keys($a)));
Prints 1
, which is correct.
EDIT:
As Shaun pointed out in the comment below, the same thing applies to the index value, if you happen to search for an int index like this:
$a = array(
"foo" => "bar",
"nice",
"car" => "fast",
"none"
);
$ind = 0;
echo array_search($ind, array_map("strval", array_keys($a)));
You will always get 0
, which is wrong, so the solution would be to cast the index (if you use a variable) to a string like this:
$ind = 0;
echo array_search((string)$ind, array_map("strval", array_keys($a)));
I've cribbed together and tested with github the following approach, based on reading other answers, which combines a few techniques:
The advantage of this approach is, once set up, it doesn't require any additional work to get it right - for example, you don't need to change remote URLs or remember to clone things differently - the URL rewriting makes it all work.
~/.ssh/config
# Personal GitHub
Host github.com
HostName github.com
User git
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/github_id_rsa
# Work GitHub
Host github-work
HostName github.com
User git
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/work_github_id_rsa
Host *
IdentitiesOnly yes
~/.gitconfig
[user]
name = My Name
email = [email protected]
[includeIf "gitdir:~/dev/work/"]
path = ~/dev/work/.gitconfig
[url "github-work:work-github-org/"]
insteadOf = [email protected]:work-github-org/
~/dev/work/.gitconfig
[user]
email = [email protected]
As long as you keep all your work repos under ~/dev/work and personal stuff elsewhere, git will use the correct SSH key when doing pulls/clones/pushes to the server, and it will also attach the correct email address to all of your commits.
References:
To contribute my 5 cents to the thorough explanation from Amadan.
Where classes are a description "of a type" in an abstract way. Objects are their realizations: the living breathing thing. In the object-orientated world there are principal ideas you can almost call the essence of everything. They are:
Objects have one, or more characteristics (= Attributes) and behaviors (= Methods). The behavior mostly depends on the characteristics. Classes define what the behavior should accomplish in a general way, but as long as the class is not realized (instantiated) as an object it remains an abstract concept of a possibility. Let me illustrate with the help of "inheritance" and "polymorphism".
class Human:
gender
nationality
favorite_drink
core_characteristic
favorite_beverage
name
age
def love
def drink
def laugh
def do_your_special_thing
class Americans(Humans)
def drink(beverage):
if beverage != favorite_drink: print "You call that a drink?"
else: print "Great!"
class French(Humans)
def drink(beverage, cheese):
if beverage == favourite_drink and cheese == None: print "No cheese?"
elif beverage != favourite_drink and cheese == None: print "Révolution!"
class Brazilian(Humans)
def do_your_special_thing
win_every_football_world_cup()
class Germans(Humans)
def drink(beverage):
if favorite_drink != beverage: print "I need more beer"
else: print "Lecker!"
class HighSchoolStudent(Americans):
def __init__(self, name, age):
self.name = name
self.age = age
jeff = HighSchoolStudent(name, age):
hans = Germans()
ronaldo = Brazilian()
amelie = French()
for friends in [jeff, hans, ronaldo]:
friends.laugh()
friends.drink("cola")
friends.do_your_special_thing()
print amelie.love(jeff)
>>> True
print ronaldo.love(hans)
>>> False
Some characteristics define human beings. But every nationality differs somewhat. So "national-types" are kinda Humans with extras. "Americans" are a type of "Humans " and inherit some abstract characteristics and behavior from the human type (base-class) : that's inheritance. So all Humans can laugh and drink, therefore all child-classes can also! Inheritance (2).
But because they are all of the same kind (Type/base-class : Humans) you can exchange them sometimes: see the for-loop at the end. But they will expose an individual characteristic, and thats Polymorphism (3).
So each human has a favorite_drink, but every nationality tend towards a special kind of drink.
If you subclass a nationality from the type of Humans you can overwrite the inherited behavior as I have demonstrated above with the drink()
Method.
But that's still at the class-level and because of this it's still a generalization.
hans = German(favorite_drink = "Cola")
instantiates the class German and I "changed" a default characteristic at the beginning. (But if you call hans.drink('Milk') he would still print "I need more beer" - an obvious bug ... or maybe that's what i would call a feature if i would be a Employee of a bigger Company. ;-)! )
The characteristic of a type e.g. Germans (hans) are usually defined through the constructor (in python : __init__
) at the moment of the instantiation. This is the point where you define a class to become an object. You could say breath life into an abstract concept (class) by filling it with individual characteristics and becoming an object.
But because every object is an instance of a class they share all some basic characteristic-types and some behavior. This is a major advantage of the object-orientated concept.
To protect the characteristics of each object you encapsulate them - means you try to couple behavior and characteristic and make it hard to manipulate it from outside the object. That's Encapsulation (1)
You need to convert the string to date using the to_date()
function
SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31-Dec-2014','DD-MON-YYYY');
OR
SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31 Dec 2014','DD MON YYYY');
OR
SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('2014-12-31','yyyy-MM-dd');
This will work only if OrderDate
is stored in Date format
. If it is Varchar
you should apply to_date()
func on that column also like
SELECT * FROM OrderArchive
WHERE to_date(OrderDate,'yyyy-Mm-dd') <= to_date('2014-12-31','yyyy-MM-dd');
Because break can only be used inside a loop. It is used to break out of a loop (stop the loop).
HTML
<form id="xtarget" action="upload.php">
<input type="file" id="xfilename">
</form>
JAVASCRIPT PURE
<script type="text/javascript">
window.onload = function() {
document.getElementById("xfilename").onchange = function() {
document.getElementById("xtarget").submit();
}
};
</script>
Here is what works well for me.
<style type="text/css">_x000D_
#underline-gap {_x000D_
text-decoration: underline;_x000D_
text-underline-position: under;_x000D_
}_x000D_
</style>_x000D_
<body>_x000D_
<h1 id="underline-gap"><a href="https://Google.com">Google</a></h1>_x000D_
</body>
_x000D_
Make half of the image transparent so the background colour is seen through it.
Else simply add another div taking up 50% up the container div and float it either left or right. Then apply either the image or the colour to it.
I just want to mention a thing, there are many tools can do text processing, e.g. sort, cut, split, join, paste, comm, uniq, column, rev, tac, tr, nl, pr, head, tail.....
they are very handy but you have to learn their options etc.
A lazy way (not the best way) to learn text processing might be: only learn grep , sed and awk. with this three tools, you can solve almost 99% of text processing problems and don't need to memorize above different cmds and options. :)
AND, if you 've learned and used the three, you knew the difference. Actually, the difference here means which tool is good at solving what kind of problem.
a more lazy way might be learning a script language (python, perl or ruby) and do every text processing with it.
There is an easy way with Sharpeserializer (open source) :
http://www.sharpserializer.com/
It can directly serialize/de-serialize dictionary.
There is no need to mark your object with any attribute, nor do you have to give the object type in the Serialize method (See here ).
To install via nuget : Install-package sharpserializer
Then it is very simple :
Hello World (from the official website):
// create fake obj
var obj = createFakeObject();
// create instance of sharpSerializer
// with standard constructor it serializes to xml
var serializer = new SharpSerializer();
// serialize
serializer.Serialize(obj, "test.xml");
// deserialize
var obj2 = serializer.Deserialize("test.xml");
Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.
You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.
But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.
You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.
I'm not quite sure how to do this in jQuery... but this works:
var x = document.getElementById('google').attributes;
for (var i in x) {
if (x[i].name == "onclick") alert(x[i].firstChild.data);
}
but like Harshath said it would be better if you used event listeners, as removing and adding this function back into the onclick event may be troublesome.
This issue arises because of different reasons. It might encountered if you are using Spring boot built war file. As Spring boot web and rest starter projects jars do have embedded Tomcat in it, hence fails with "SEVERE: ContainerBase.addChild: start: org.apache.catalina.LifecycleException".
You can fix this by exclusion of the embedded tomcat at the time of packaging by using exclusions in case of maven.
Maven dependency of "spring-boot-starter-web" will look like
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
Maybe this helps. You have to refer the @param
/**
* Display a listing of the resource.
*
* @param Illuminate\Http\Request $request
* @return Response
*/
public function index(Request $request)
{
if($request->ajax()){
return "AJAX";
}
return "HTTP";
}
I found a simple solution to emulate both cover and contain, which is pure CSS, and works for containers with dynamic dimensions, and also doesn't make any restriction on the image ratio.
Note that if you don't need to support IE, or Edge before 16, then you better use object-fit.
.img-container {_x000D_
position: relative;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
.background-image {_x000D_
position: absolute;_x000D_
min-width: 1000%;_x000D_
min-height: 1000%;_x000D_
left: 50%;_x000D_
top: 50%;_x000D_
transform: translateX(-50%) translateY(-50%) scale(0.1);_x000D_
z-index: -1;_x000D_
}
_x000D_
<div class="img-container">_x000D_
<img class="background-image" src="https://picsum.photos/1024/768/?random">_x000D_
<p style="padding: 20px; color: white; text-shadow: 0 0 10px black">_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
</p>_x000D_
</div>
_x000D_
The 1000% is used here in case the image natural size is bigger than the size it is being displayed. For example, if the image is 500x500, but the container is only 200x200. With this solution, the image will be resized to 2000x2000 (due to min-width/min-height), then scaled down to 200x200 (due to transform: scale(0.1)
).
The x10 factor can be replaced by x100 or x1000, but it is usually not ideal to have a 2000x2000 image being rendered on a 20x20 div. :)
Following the same principle, you can also use it to emulate background-size: contain
:
.img-container {_x000D_
position: relative;_x000D_
overflow: hidden;_x000D_
z-index: 0;_x000D_
}_x000D_
_x000D_
.background-image {_x000D_
position: absolute;_x000D_
max-width: 10%;_x000D_
max-height: 10%;_x000D_
left: 50%;_x000D_
top: 50%;_x000D_
transform: translateX(-50%) translateY(-50%) scale(10);_x000D_
z-index: -1;_x000D_
}
_x000D_
<div style="background-color: black">_x000D_
<div class="img-container">_x000D_
<img class="background-image" src="https://picsum.photos/1024/768/?random">_x000D_
<p style="padding: 20px; color: white; text-shadow: 0 0 10px black">_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
</p>_x000D_
</div>_x000D_
</div>
_x000D_
A simple  
; between input fields would do the job easily...
For Windows:
$ ssh-keygen -t rsa -b 4096 -C [email protected]
Try this small lib, works with Angular 5.0.0
Quickstart example with ng2-file-upload 1.3.0:
User clicks custom button, which triggers upload dialog from hidden input type="file" , uploading started automatically after selecting single file.
app.module.ts:
import {FileUploadModule} from "ng2-file-upload";
your.component.html:
...
<button mat-button onclick="document.getElementById('myFileInputField').click()" >
Select and upload file
</button>
<input type="file" id="myFileInputField" ng2FileSelect [uploader]="uploader" style="display:none">
...
your.component.ts:
import {FileUploader} from 'ng2-file-upload';
...
uploader: FileUploader;
...
constructor() {
this.uploader = new FileUploader({url: "/your-api/some-endpoint"});
this.uploader.onErrorItem = item => {
console.error("Failed to upload");
this.clearUploadField();
};
this.uploader.onCompleteItem = (item, response) => {
console.info("Successfully uploaded");
this.clearUploadField();
// (Optional) Parsing of response
let responseObject = JSON.parse(response) as MyCustomClass;
};
// Asks uploader to start upload file automatically after selecting file
this.uploader.onAfterAddingFile = fileItem => this.uploader.uploadAll();
}
private clearUploadField(): void {
(<HTMLInputElement>window.document.getElementById('myFileInputField'))
.value = "";
}
Alternative lib, works in Angular 4.2.4, but requires some workarounds to adopt to Angular 5.0.0
A slight variation on Richards answer but readTree
can take a string so you can simplify it to:
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree("{\"k1\":\"v1\"}");
You should not use title attribute for the img element. The reasoning behind this is quite simple:
Presumably caption information is important information that should be available to all users by default. If so present this content as text next to the image.
Source: http://blog.paciellogroup.com/2010/11/using-the-html-title-attribute/
HTML 5.1 includes general advice on use of the title attribute:
Relying on the title attribute is currently discouraged as many user agents do not expose the attribute in an accessible manner as required by this specification (e.g. requiring a pointing device such as a mouse to cause a tooltip to apear, which excludes keyboard-only users and touch-only users, such as anyone with a modern phone or tablet).
Source: http://www.w3.org/html/wg/drafts/html/master/dom.html#the-title-attribute
When it comes to accessibility and different screen readers:
Hence, as Denis Boudreau adequately put it: clearly not a recommended practice.
Here is what the standard C99 (ISO-IEC 9899 6.2.5 §10) or C++2003 (ISO-IEC 14882-2003 3.1.9 §8) standards say:
There are three floating point types:
float
,double
, andlong double
. The typedouble
provides at least as much precision asfloat
, and the typelong double
provides at least as much precision asdouble
. The set of values of the typefloat
is a subset of the set of values of the typedouble
; the set of values of the typedouble
is a subset of the set of values of the typelong double
.
The C++ standard adds:
The value representation of floating-point types is implementation-defined.
I would suggest having a look at the excellent What Every Computer Scientist Should Know About Floating-Point Arithmetic that covers the IEEE floating-point standard in depth. You'll learn about the representation details and you'll realize there is a tradeoff between magnitude and precision. The precision of the floating point representation increases as the magnitude decreases, hence floating point numbers between -1 and 1 are those with the most precision.
::
or REM
:: commenttttttttttt
REM commenttttttttttt
::
doesn't work inline; add &
character:your commands here & :: commenttttttttttt
IF/ELSE
, FOR
loops, etc...) ::
should be followed with normal line, otherwise it gives error (use REM
there).::
may also fail within setlocal ENABLEDELAYEDEXPANSION
Not the most pretty code, but the following will pick an appropriate font size for a JLabel
called label
such that the text inside will fit the interior as much as possible without overflowing the label:
Font labelFont = label.getFont();
String labelText = label.getText();
int stringWidth = label.getFontMetrics(labelFont).stringWidth(labelText);
int componentWidth = label.getWidth();
// Find out how much the font can grow in width.
double widthRatio = (double)componentWidth / (double)stringWidth;
int newFontSize = (int)(labelFont.getSize() * widthRatio);
int componentHeight = label.getHeight();
// Pick a new font size so it will not be larger than the height of label.
int fontSizeToUse = Math.min(newFontSize, componentHeight);
// Set the label's font size to the newly determined size.
label.setFont(new Font(labelFont.getName(), Font.PLAIN, fontSizeToUse));
Basically, the code looks at how much space the text in the JLabel
takes up by using the FontMetrics
object, and then uses that information to determine the largest font size that can be used without overflowing the text from the JLabel
.
The above code can be inserted into perhaps the paint
method of the JFrame
which holds the JLabel
, or some method which will be invoked when the font size needs to be changed.
The following is an screenshot of the above code in action:
(source: coobird.net)
There really isn't a need to do this unless you insist on the value of 0. The HtmlHelper DropDownList extension allows you to set an option label that shows up as the initial value in the select with a null value. Simply use one of the DropDownList signatures that has the option label.
<%= Html.DropDownList( "DropDownValue",
(IEnumerable<SelectListItem>)ViewData["Menu"],
"-- Select One --" ) %>
typeof
is applied to a name of a type or generic type parameter known at compile time (given as identifier, not as string). GetType
is called on an object at runtime. In both cases the result is an object of the type System.Type
containing meta-information on a type.
Example where compile-time and run-time types are equal
string s = "hello";
Type t1 = typeof(string);
Type t2 = s.GetType();
t1 == t2 ==> true
Example where compile-time and run-time types are different
object obj = "hello";
Type t1 = typeof(object); // ==> object
Type t2 = obj.GetType(); // ==> string!
t1 == t2 ==> false
i.e., the compile time type (static type) of the variable obj
is not the same as the runtime type of the object referenced by obj
.
Testing types
If, however, you only want to know whether mycontrol
is a TextBox
then you can simply test
if (mycontrol is TextBox)
Note that this is not completely equivalent to
if (mycontrol.GetType() == typeof(TextBox))
because mycontrol
could have a type that is derived from TextBox
. In that case the first comparison yields true
and the second false
! The first and easier variant is OK in most cases, since a control derived from TextBox
inherits everything that TextBox
has, probably adds more to it and is therefore assignment compatible to TextBox
.
public class MySpecializedTextBox : TextBox
{
}
MySpecializedTextBox specialized = new MySpecializedTextBox();
if (specialized is TextBox) ==> true
if (specialized.GetType() == typeof(TextBox)) ==> false
Casting
If you have the following test followed by a cast and T is nullable ...
if (obj is T) {
T x = (T)obj; // The casting tests, whether obj is T again!
...
}
... you can change it to ...
T x = obj as T;
if (x != null) {
...
}
Testing whether a value is of a given type and casting (which involves this same test again) can both be time consuming for long inheritance chains. Using the as
operator followed by a test for null
is more performing.
Starting with C# 7.0 you can simplify the code by using pattern matching:
if (obj is T t) {
// t is a variable of type T having a non-null value.
...
}
Btw.: this works for value types as well. Very handy for testing and unboxing. Note that you cannot test for nullable value types:
if (o is int? ni) ===> does NOT compile!
This is because either the value is null
or it is an int
. This works for int? o
as well as for object o = new Nullable<int>(x);
:
if (o is int i) ===> OK!
I like it, because it eliminates the need to access the Nullable<T>.Value
property.
I don't understand why nobody is suggesting createImageBitmap
.
createImageBitmap(
document.getElementById('image'),
{ resizeWidth: 300, resizeHeight: 234, resizeQuality: 'high' }
)
.then(imageBitmap =>
document.getElementById('canvas').getContext('2d').drawImage(imageBitmap, 0, 0)
);
works beautifully (assuming you set ids for image and canvas).
I recently was wondering why my code doesn't work, then I realized, I need to setup the event handlers as soon as the document is loaded, otherwise when browser loads the code line by line, it loads the JavaScript, but it does not yet have the element to assign the event handler to it. with your example, it should be like this:
$(document).ready(function(){
$("#kat").change(function(){
alert("Hello");
});
});
I figured that the DJANGO_SETTINGS_MODULE had to be set some way, so I looked at the documentation (link updated) and found:
export DJANGO_SETTINGS_MODULE=mysite.settings
Though that is not enough if you are running a server on heroku, you need to specify it there, too. Like this:
heroku config:set DJANGO_SETTINGS_MODULE=mysite.settings --account <your account name>
In my specific case I ran these two and everything worked out:
export DJANGO_SETTINGS_MODULE=nirla.settings
heroku config:set DJANGO_SETTINGS_MODULE=nirla.settings --account personal
Edit
I would also like to point out that you have to re-do this every time you close or restart your virtual environment. Instead, you should automate the process by going to venv/bin/activate and adding the line: set DJANGO_SETTINGS_MODULE=mysite.settings
to the bottom of the code. From now on every time you activate the virtual environment, you will be using that app's settings.
Strictly speaking, the concept of a callback function
does not exist in Java, because in Java there are no functions, only methods, and you cannot pass a method around, you can only pass objects and interfaces. So, whoever has a reference to that object or interface may invoke any of its methods, not just one method that you might wish them to.
However, this is all fine and well, and we often speak of callback objects and callback interfaces, and when there is only one method in that object or interface, we may even speak of a callback method or even a callback function; we humans tend to thrive in inaccurate communication.
(Actually, perhaps the best approach is to just speak of "a callback" without adding any qualifications: this way, you cannot possibly go wrong. See next sentence.)
One of the most famous examples of using a callback in Java is when you call an ArrayList
object to sort itself, and you supply a comparator which knows how to compare the objects contained within the list.
Your code is the high-level layer, which calls the lower-level layer (the standard java runtime list object) supplying it with an interface to an object which is in your (high level) layer. The list will then be "calling back" your object to do the part of the job that it does not know how to do, namely to compare elements of the list. So, in this scenario the comparator can be thought of as a callback object.
Another way assuming it's not server side code you want to comment out is...
<asp:panel runat="server" visible="false">
html here
</asp:panel>
You can execute some lines in the same subshell if you end lines with backslash.
cd somedir; \
pwd
In line with my answer to a related question, I'm going to disagree with BJ and suggest you first look at GCD over NSOperation / NSOperationQueue, unless the latter provides something you need that GCD doesn't.
Before GCD, I used a lot of NSOperations / NSOperationQueues within my applications for managing concurrency. However, since I started using GCD on a regular basis, I've almost entirely replaced NSOperations and NSOperationQueues with blocks and dispatch queues. This has come from how I've used both technologies in practice, and from the profiling I've performed on them.
First, there is a nontrivial amount of overhead when using NSOperations and NSOperationQueues. These are Cocoa objects, and they need to be allocated and deallocated. In an iOS application that I wrote which renders a 3-D scene at 60 FPS, I was using NSOperations to encapsulate each rendered frame. When I profiled this, the creation and teardown of these NSOperations was accounting for a significant portion of the CPU cycles in the running application, and was slowing things down. I replaced these with simple blocks and a GCD serial queue, and that overhead disappeared, leading to noticeably better rendering performance. This wasn't the only place where I noticed overhead from using NSOperations, and I've seen this on both Mac and iOS.
Second, there's an elegance to block-based dispatch code that is hard to match when using NSOperations. It's so incredibly convenient to wrap a few lines of code in a block and dispatch it to be performed on a serial or concurrent queue, where creating a custom NSOperation or NSInvocationOperation to do this requires a lot more supporting code. I know that you can use an NSBlockOperation, but you might as well be dispatching something to GCD then. Wrapping this code in blocks inline with related processing in your application leads in my opinion to better code organization than having separate methods or custom NSOperations which encapsulate these tasks.
NSOperations and NSOperationQueues still have very good uses. GCD has no real concept of dependencies, where NSOperationQueues can set up pretty complex dependency graphs. I use NSOperationQueues for this in a handful of cases.
Overall, while I usually advocate for using the highest level of abstraction that accomplishes the task, this is one case where I argue for the lower-level API of GCD. Among the iOS and Mac developers I've talked with about this, the vast majority choose to use GCD over NSOperations unless they are targeting OS versions without support for it (those before iOS 4.0 and Snow Leopard).
This is the tsql
way
ALTER TABLE yourtable DROP CONSTRAINT constraint_name -- DF_Movies_Rating__48CFD27E
For completeness, this just shows @Joe Taras's comment as an answer
Horizontal progress bar custom material style :
To change color of background and progress of horizontal progress bar.
<style name="MyProgressBar" parent="@style/Widget.AppCompat.ProgressBar.Horizontal">
<item name="android:progressBackgroundTint">#69f0ae</item>
<item name="android:progressTint">#b71c1c</item>
<item name="android:minWidth">200dp</item>
</style>
Apply it to progress bar by setting style attribute, for custom material styles and custom progress bar check http://www.zoftino.com/android-progressbar-and-custom-progressbar-examples
It could be interesting to know how to search for one unicode character. This command can help. You only need to know the code in UTF8
grep -v $'\u200d'
Holdover from C.
OK, what you can try is
Cntrl+H (Find and Replace), leave Find What blank and change Replace With to NULL.
That should replace all blank cells in the USED range with NULL
While working with selected cells as shown by @tbur can be useful, it's also not the only option available.
You can use Range() like so:
If Worksheets("Sheet1").Range("A1").MergeCells Then
Do something
Else
Do something else
End If
Or:
If Worksheets("Sheet1").Range("A1:C1").MergeCells Then
Do something
Else
Do something else
End If
Alternately, you can use Cells():
If Worksheets("Sheet1").Cells(1, 1).MergeCells Then
Do something
Else
Do something else
End If
Using the contentWindow.focus() method, the timeout is probably necessary to wait for the iframe to be completely loaded.
For me, also using attribute onload="this.contentWindow.focus()"
works, with firefox, into the iframe tag
You 'can' have a static class in C++, as mentioned before, a static class is one that does not have any objects of it instantiated it. In C++, this can be obtained by declaring the constructor/destructor as private. End result is the same.
If you want to show just numbers without characters, put this line of code inside your XML file android:inputType="number"
. The output:
If you want to show a number keyboard that also shows characters, put android:inputType="phone"
on your XML. The output (with characters):
And if you want to show a number keyboard that masks your input just like a password, put android:inputType="numberpassword"
. The output:
I'm really sorry if I only post the links of the screenshot, I want to do research on how to do really post images here but it might consume my time so here it is. I hope my post can help other people. Yes, my answer is duplicate with other answers posted here but to save other people's time that they might need to run their code before seeing the output, my post might save you some time.
You can also use DEV_RANDOM, where 128 = 1/2 the generated token length. Code below generates 256 token.
$token = bin2hex(mcrypt_create_iv(128, MCRYPT_DEV_RANDOM));
If you want immediate first child you need
$(element).first();
If you want particular first element in the dom from your element then use below
var spanElement = $(elementId).find(".redClass :first");
$(spanElement).addClass("yourClassHere");
try out : http://jsfiddle.net/vgGbc/2/
I've recently had to bump up against this again in my own project - and wanted to share the somewhat simpler code that I've been using, as this question and series of answers kept coming up in my searches.
I'm not going to get into the security concerns around how often to update things like your Salt and Initialization Vector - that's a topic for a security forum, and there are some great resources out there to look at. This is simply a block of code to implement AesManaged
in C#.
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Your.Namespace.Security {
public static class Cryptography {
#region Settings
private static int _iterations = 2;
private static int _keySize = 256;
private static string _hash = "SHA1";
private static string _salt = "aselrias38490a32"; // Random
private static string _vector = "8947az34awl34kjq"; // Random
#endregion
public static string Encrypt(string value, string password) {
return Encrypt<AesManaged>(value, password);
}
public static string Encrypt<T>(string value, string password)
where T : SymmetricAlgorithm, new() {
byte[] vectorBytes = GetBytes<ASCIIEncoding>(_vector);
byte[] saltBytes = GetBytes<ASCIIEncoding>(_salt);
byte[] valueBytes = GetBytes<UTF8Encoding>(value);
byte[] encrypted;
using (T cipher = new T()) {
PasswordDeriveBytes _passwordBytes =
new PasswordDeriveBytes(password, saltBytes, _hash, _iterations);
byte[] keyBytes = _passwordBytes.GetBytes(_keySize / 8);
cipher.Mode = CipherMode.CBC;
using (ICryptoTransform encryptor = cipher.CreateEncryptor(keyBytes, vectorBytes)) {
using (MemoryStream to = new MemoryStream()) {
using (CryptoStream writer = new CryptoStream(to, encryptor, CryptoStreamMode.Write)) {
writer.Write(valueBytes, 0, valueBytes.Length);
writer.FlushFinalBlock();
encrypted = to.ToArray();
}
}
}
cipher.Clear();
}
return Convert.ToBase64String(encrypted);
}
public static string Decrypt(string value, string password) {
return Decrypt<AesManaged>(value, password);
}
public static string Decrypt<T>(string value, string password) where T : SymmetricAlgorithm, new() {
byte[] vectorBytes = GetBytes<ASCIIEncoding>(_vector);
byte[] saltBytes = GetBytes<ASCIIEncoding>(_salt);
byte[] valueBytes = Convert.FromBase64String(value);
byte[] decrypted;
int decryptedByteCount = 0;
using (T cipher = new T()) {
PasswordDeriveBytes _passwordBytes = new PasswordDeriveBytes(password, saltBytes, _hash, _iterations);
byte[] keyBytes = _passwordBytes.GetBytes(_keySize / 8);
cipher.Mode = CipherMode.CBC;
try {
using (ICryptoTransform decryptor = cipher.CreateDecryptor(keyBytes, vectorBytes)) {
using (MemoryStream from = new MemoryStream(valueBytes)) {
using (CryptoStream reader = new CryptoStream(from, decryptor, CryptoStreamMode.Read)) {
decrypted = new byte[valueBytes.Length];
decryptedByteCount = reader.Read(decrypted, 0, decrypted.Length);
}
}
}
} catch (Exception ex) {
return String.Empty;
}
cipher.Clear();
}
return Encoding.UTF8.GetString(decrypted, 0, decryptedByteCount);
}
}
}
The code is very simple to use. It literally just requires the following:
string encrypted = Cryptography.Encrypt(data, "testpass");
string decrypted = Cryptography.Decrypt(encrypted, "testpass");
By default, the implementation uses AesManaged - but you could actually also insert any other SymmetricAlgorithm
. A list of the available SymmetricAlgorithm
inheritors for .NET 4.5 can be found at:
http://msdn.microsoft.com/en-us/library/system.security.cryptography.symmetricalgorithm.aspx
As of the time of this post, the current list includes:
AesManaged
RijndaelManaged
DESCryptoServiceProvider
RC2CryptoServiceProvider
TripleDESCryptoServiceProvider
To use RijndaelManaged
with the code above, as an example, you would use:
string encrypted = Cryptography.Encrypt<RijndaelManaged>(dataToEncrypt, password);
string decrypted = Cryptography.Decrypt<RijndaelManaged>(encrypted, password);
I hope this is helpful to someone out there.
Did you forget the Background Property. The brush should be an ImageBrush whose ImageSource could be set to your image path.
<Grid>
<Grid.Background>
<ImageBrush ImageSource="/path/to/image.png" Stretch="UniformToFill"/>
</Grid.Background>
<...>
</Grid>
Already coded in my library so here it is:
var vScrollWidth = window.screen.width - window.document.documentElement.clientWidth;
I should mention that jQuery $(window).width()
can also be used instead of window.document.documentElement.clientWidth
.
It doesn't work if you open developer tools in firefox on the right but it overcomes it if the devs window is opened at bottom!
window.screen
is supported quirksmode.org!
Have fun!
This answer fails in a couple of edge cases (see comments). The accepted solution above will handle these. str.splitlines()
is the way to go. I will leave this answer nevertheless as reference.
Old (incorrect) answer:
s = \
"""line1
line2
line3
"""
lines = s.split('\n')
print(lines)
for line in lines:
print(line)
There's also oct2py which can call .m files within python
https://pypi.python.org/pypi/oct2py
It requires GNU Octave, which is highly compatible with MATLAB.
Best solution you have ever see.
Convert django.db.models.Model instance and all related ForeignKey, ManyToManyField and @Property function fields into dict.
"""
Convert django.db.models.Model instance and all related ForeignKey, ManyToManyField and @property function fields into dict.
Usage:
class MyDjangoModel(... PrintableModel):
to_dict_fields = (...)
to_dict_exclude = (...)
...
a_dict = [inst.to_dict(fields=..., exclude=...) for inst in MyDjangoModel.objects.all()]
"""
import typing
import django.core.exceptions
import django.db.models
import django.forms.models
def get_decorators_dir(cls, exclude: typing.Optional[set]=None) -> set:
"""
Ref: https://stackoverflow.com/questions/4930414/how-can-i-introspect-properties-and-model-fields-in-django
:param exclude: set or None
:param cls:
:return: a set of decorators
"""
default_exclude = {"pk", "objects"}
if not exclude:
exclude = default_exclude
else:
exclude = exclude.union(default_exclude)
return set([name for name in dir(cls) if name not in exclude and isinstance(getattr(cls, name), property)])
class PrintableModel(django.db.models.Model):
class Meta:
abstract = True
def __repr__(self):
return str(self.to_dict())
def to_dict(self, fields: typing.Optional[typing.Iterable]=None, exclude: typing.Optional[typing.Iterable]=None):
opts = self._meta
data = {}
# support fields filters and excludes
if not fields:
fields = set()
else:
fields = set(fields)
default_fields = getattr(self, "to_dict_fields", set())
fields = fields.union(default_fields)
if not exclude:
exclude = set()
else:
exclude = set(exclude)
default_exclude = getattr(self, "to_dict_exclude", set())
exclude = exclude.union(default_exclude)
# support syntax "field__childField__..."
self_fields = set()
child_fields = dict()
if fields:
for i in fields:
splits = i.split("__")
if len(splits) == 1:
self_fields.add(splits[0])
else:
self_fields.add(splits[0])
field_name = splits[0]
child_fields.setdefault(field_name, set())
child_fields[field_name].add("__".join(splits[1:]))
self_exclude = set()
child_exclude = dict()
if exclude:
for i in exclude:
splits = i.split("__")
if len(splits) == 1:
self_exclude.add(splits[0])
else:
field_name = splits[0]
if field_name not in child_exclude:
child_exclude[field_name] = set()
child_exclude[field_name].add("__".join(splits[1:]))
for f in opts.concrete_fields + opts.many_to_many:
if self_fields and f.name not in self_fields:
continue
if self_exclude and f.name in self_exclude:
continue
if isinstance(f, django.db.models.ManyToManyField):
if self.pk is None:
data[f.name] = []
else:
result = []
m2m_inst = f.value_from_object(self)
for obj in m2m_inst:
if isinstance(PrintableModel, obj) and hasattr(obj, "to_dict"):
d = obj.to_dict(
fields=child_fields.get(f.name),
exclude=child_exclude.get(f.name),
)
else:
d = django.forms.models.model_to_dict(
obj,
fields=child_fields.get(f.name),
exclude=child_exclude.get(f.name)
)
result.append(d)
data[f.name] = result
elif isinstance(f, django.db.models.ForeignKey):
if self.pk is None:
data[f.name] = []
else:
data[f.name] = None
try:
foreign_inst = getattr(self, f.name)
except django.core.exceptions.ObjectDoesNotExist:
pass
else:
if isinstance(foreign_inst, PrintableModel) and hasattr(foreign_inst, "to_dict"):
data[f.name] = foreign_inst.to_dict(
fields=child_fields.get(f.name),
exclude=child_exclude.get(f.name)
)
elif foreign_inst is not None:
data[f.name] = django.forms.models.model_to_dict(
foreign_inst,
fields=child_fields.get(f.name),
exclude=child_exclude.get(f.name),
)
elif isinstance(f, (django.db.models.DateTimeField, django.db.models.DateField)):
v = f.value_from_object(self)
if v is not None:
data[f.name] = v.isoformat()
else:
data[f.name] = None
else:
data[f.name] = f.value_from_object(self)
# support @property decorator functions
decorator_names = get_decorators_dir(self.__class__)
for name in decorator_names:
if self_fields and name not in self_fields:
continue
if self_exclude and name in self_exclude:
continue
value = getattr(self, name)
if isinstance(value, PrintableModel) and hasattr(value, "to_dict"):
data[name] = value.to_dict(
fields=child_fields.get(name),
exclude=child_exclude.get(name)
)
elif hasattr(value, "_meta"):
# make sure it is a instance of django.db.models.fields.Field
data[name] = django.forms.models.model_to_dict(
value,
fields=child_fields.get(name),
exclude=child_exclude.get(name),
)
elif isinstance(value, (set, )):
data[name] = list(value)
else:
data[name] = value
return data
https://gist.github.com/shuge/f543dc2094a3183f69488df2bfb51a52
There's a really simple answer, which nobody else has mentioned:
function isLowerCase(str) {
return str !== str.toUpperCase();
}
If str.toUpperCase()
does not return the same str
, it has to be lower case. To test for upper case you change it to str !== str.toLowererCase()
.
Unlike some other answers, it works correctly on non-alpha characters (returns false
) and it works for other alphabets, accented characters etc.
One command and does not use the destructive git reset
command:
GIT_SEQUENCE_EDITOR="sed -i 's/pick/d/'" git rebase -i HEAD~ --autostash
It simply drops the commit, putting you back exactly in the state before the cherry-pick even if you had local changes.
Starting with a set of bytes which encode a string using UTF-8, creates a string from that data, then get some bytes encoding the string in a different encoding:
byte[] utf8bytes = { (byte)0xc3, (byte)0xa2, 0x61, 0x62, 0x63, 0x64 };
Charset utf8charset = Charset.forName("UTF-8");
Charset iso88591charset = Charset.forName("ISO-8859-1");
String string = new String ( utf8bytes, utf8charset );
System.out.println(string);
// "When I do a getbytes(encoding) and "
byte[] iso88591bytes = string.getBytes(iso88591charset);
for ( byte b : iso88591bytes )
System.out.printf("%02x ", b);
System.out.println();
// "then create a new string with the bytes in ISO-8859-1 encoding"
String string2 = new String ( iso88591bytes, iso88591charset );
// "I get a two different chars"
System.out.println(string2);
this outputs strings and the iso88591 bytes correctly:
âabcd
e2 61 62 63 64
âabcd
So your byte array wasn't paired with the correct encoding:
String failString = new String ( utf8bytes, iso88591charset );
System.out.println(failString);
Outputs
âabcd
(either that, or you just wrote the utf8 bytes to a file and read them elsewhere as iso88591)
__call__()
method when creating a class instanceIf you've done Python programming for more than a few months you'll eventually stumble upon code that looks like this:
# define a class
class SomeClass(object):
# ...
# some definition here ...
# ...
# create an instance of it
instance = SomeClass()
# then call the object as if it's a function
result = instance('foo', 'bar')
The latter is possible when you implement the __call__()
magic method on the class.
class SomeClass(object):
# ...
# some definition here ...
# ...
def __call__(self, foo, bar):
return bar + foo
The __call__()
method is invoked when an instance of a class is used as a callable. But as we've seen from previous answers a class itself is an instance of a metaclass, so when we use the class as a callable (i.e. when we create an instance of it) we're actually calling its metaclass' __call__()
method. At this point most Python programmers are a bit confused because they've been told that when creating an instance like this instance = SomeClass()
you're calling its __init__()
method. Some who've dug a bit deeper know that before __init__()
there's __new__()
. Well, today another layer of truth is being revealed, before __new__()
there's the metaclass' __call__()
.
Let's study the method call chain from specifically the perspective of creating an instance of a class.
This is a metaclass that logs exactly the moment before an instance is created and the moment it's about to return it.
class Meta_1(type):
def __call__(cls):
print "Meta_1.__call__() before creating an instance of ", cls
instance = super(Meta_1, cls).__call__()
print "Meta_1.__call__() about to return instance."
return instance
This is a class that uses that metaclass
class Class_1(object):
__metaclass__ = Meta_1
def __new__(cls):
print "Class_1.__new__() before creating an instance."
instance = super(Class_1, cls).__new__(cls)
print "Class_1.__new__() about to return instance."
return instance
def __init__(self):
print "entering Class_1.__init__() for instance initialization."
super(Class_1,self).__init__()
print "exiting Class_1.__init__()."
And now let's create an instance of Class_1
instance = Class_1()
# Meta_1.__call__() before creating an instance of <class '__main__.Class_1'>.
# Class_1.__new__() before creating an instance.
# Class_1.__new__() about to return instance.
# entering Class_1.__init__() for instance initialization.
# exiting Class_1.__init__().
# Meta_1.__call__() about to return instance.
Observe that the code above doesn't actually do anything more than logging the tasks. Each method delegates the actual work to its parent's implementation, thus keeping the default behavior. Since type
is Meta_1
's parent class (type
being the default parent metaclass) and considering the ordering sequence of the output above, we now have a clue as to what would be the pseudo implementation of type.__call__()
:
class type:
def __call__(cls, *args, **kwarg):
# ... maybe a few things done to cls here
# then we call __new__() on the class to create an instance
instance = cls.__new__(cls, *args, **kwargs)
# ... maybe a few things done to the instance here
# then we initialize the instance with its __init__() method
instance.__init__(*args, **kwargs)
# ... maybe a few more things done to instance here
# then we return it
return instance
We can see that the metaclass' __call__()
method is the one that's called first. It then delegates creation of the instance to the class's __new__()
method and initialization to the instance's __init__()
. It's also the one that ultimately returns the instance.
From the above it stems that the metaclass' __call__()
is also given the opportunity to decide whether or not a call to Class_1.__new__()
or Class_1.__init__()
will eventually be made. Over the course of its execution it could actually return an object that hasn't been touched by either of these methods. Take for example this approach to the singleton pattern:
class Meta_2(type):
singletons = {}
def __call__(cls, *args, **kwargs):
if cls in Meta_2.singletons:
# we return the only instance and skip a call to __new__()
# and __init__()
print ("{} singleton returning from Meta_2.__call__(), "
"skipping creation of new instance.".format(cls))
return Meta_2.singletons[cls]
# else if the singleton isn't present we proceed as usual
print "Meta_2.__call__() before creating an instance."
instance = super(Meta_2, cls).__call__(*args, **kwargs)
Meta_2.singletons[cls] = instance
print "Meta_2.__call__() returning new instance."
return instance
class Class_2(object):
__metaclass__ = Meta_2
def __new__(cls, *args, **kwargs):
print "Class_2.__new__() before creating instance."
instance = super(Class_2, cls).__new__(cls)
print "Class_2.__new__() returning instance."
return instance
def __init__(self, *args, **kwargs):
print "entering Class_2.__init__() for initialization."
super(Class_2, self).__init__()
print "exiting Class_2.__init__()."
Let's observe what happens when repeatedly trying to create an object of type Class_2
a = Class_2()
# Meta_2.__call__() before creating an instance.
# Class_2.__new__() before creating instance.
# Class_2.__new__() returning instance.
# entering Class_2.__init__() for initialization.
# exiting Class_2.__init__().
# Meta_2.__call__() returning new instance.
b = Class_2()
# <class '__main__.Class_2'> singleton returning from Meta_2.__call__(), skipping creation of new instance.
c = Class_2()
# <class '__main__.Class_2'> singleton returning from Meta_2.__call__(), skipping creation of new instance.
a is b is c # True
your server dosen't allow different sender and username
you should config: $mail->From
like $mail->Username
You're right in your assumption about Spring vs. Quartz instantiating the class. However, Spring provides some classes that let you do some primitive dependency injection in Quartz. Check out SchedulerFactoryBean.setJobFactory() along with the SpringBeanJobFactory. Essentially, by using the SpringBeanJobFactory, you enable dependency injection on all Job properties, but only for values that are in the Quartz scheduler context or the job data map. I don't know what all DI styles it supports (constructor, annotation, setter...) but I do know it supports setter injection.
I would opt for NOT EXISTS
in this case.
SELECT D1.ShortCode
FROM Domain1 D1
WHERE NOT EXISTS
(SELECT 'X'
FROM Domain2 D2
WHERE D2.ShortCode = D1.ShortCode
)
As specified in the documentation, use undefined
:
export interface INotificationService {
error(message: string, title?: string, autoHideAfter? : number);
}
class X {
error(message: string, title?: string, autoHideAfter?: number) {
console.log(message, title, autoHideAfter);
}
}
new X().error("hi there", undefined, 1000);
Running VS Code on Android is not possible, at least until Android support is implemented in Electron. This has been rejected by the Electron team in the past, see electron#562
Visual Studio Codespaces and GitHub Codespaces an upcoming services that enables running VS Code in a browser. Since everything runs in a browser, it seems likely that mobile OS' will be supported.
Ansible has a version_compare
filter since 1.6.
You can do something like below in when
conditional:
when: ansible_distribution_version | version_compare('12.04', '>=')
This will give you support for major & minor versions comparisons and you can compare versions using operators like:
<, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne
You can find more information about this here: Ansible - Version comparison filters
Otherwise if you have really simple case you can use what @ProfHase85 suggested
To send an email from iPhone application you need to do below list of task.
Step 1: Import #import <MessageUI/MessageUI.h>
In your controller class where you want to send an email.
Step 2: Add the delegate to your controller like shown below
@interface <yourControllerName> : UIViewController <MFMessageComposeViewControllerDelegate, MFMailComposeViewControllerDelegate>
Step 3: Add below method for send email.
- (void) sendEmail {
// Check if your app support the email.
if ([MFMailComposeViewController canSendMail]) {
// Create an object of mail composer.
MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init];
// Add delegate to your self.
mailComposer.mailComposeDelegate = self;
// Add recipients to mail if you do not want to add default recipient then remove below line.
[mailComposer setToRecipients:@[<add here your recipient objects>]];
// Write email subject.
[mailComposer setSubject:@“<Your Subject Here>”];
// Set your email body and if body contains HTML then Pass “YES” in isHTML.
[mailComposer setMessageBody:@“<Your Message Body>” isHTML:NO];
// Show your mail composer.
[self presentViewController:mailComposer animated:YES completion:NULL];
}
else {
// Here you can show toast to user about not support to sending email.
}
}
Step 4: Implement MFMailComposeViewController Delegate
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(nullable NSError *)error {
[controller dismissViewControllerAnimated:TRUE completion:nil];
switch (result) {
case MFMailComposeResultSaved: {
// Add code on save mail to draft.
break;
}
case MFMailComposeResultSent: {
// Add code on sent a mail.
break;
}
case MFMailComposeResultCancelled: {
// Add code on cancel a mail.
break;
}
case MFMailComposeResultFailed: {
// Add code on failed to send a mail.
break;
}
default:
break;
}
}
var bombout=0;
var checkArr=[];
var arr=[];
while(arr.length < 8 && bombout<100){
bombout++;
var randomNumber=Math.ceil(Math.random()*100);
if(typeof checkArr[randomNumber] == "undefined"){
checkArr[randomNumber]=1;
arr.push(randomNumber);
}
}?
// untested - hence bombout
/**
* This method gets the Key for the given Value
* @param paramName
* @return
*/
private String getKeyForValueFromMap(String paramName) {
String keyForValue = null;
if(paramName!=null)) {
Set<Entry<String,String>> entrySet = myMap().entrySet();
if(entrySet!=null && entrySet.size>0) {
for(Entry<String,String> entry : entrySet) {
if(entry!=null && paramName.equalsIgnoreCase(entry.getValue())) {
keyForValue = entry.getKey();
}
}
}
}
return keyForValue;
}
You have to use HorizontalContentAlignment="Center" and! Width="Auto".
Set up a System variable from Maven and in java use following call
System.getProperty("Key");
For those who are having a hard time finding the "merge buttons".
The little lightbulp icon with merge options only shows up if you click precisely on the "merge conflict marker"
<<<<<<<
Steps (in VS Code 1.29.x):
Well, the problem you have is wrong line ending/encoding for notepad. Notepad uses Windows' line endings - \r\n
and you use \n
.
Use String#slice
, also aliased as []
.
a = "hello there"
a[1] #=> "e"
a[1,3] #=> "ell"
a[1..3] #=> "ell"
a[6..-1] #=> "there"
a[6..] #=> "there" (requires Ruby 2.6+)
a[-3,2] #=> "er"
a[-4..-2] #=> "her"
a[12..-1] #=> nil
a[-2..-4] #=> ""
a[/[aeiou](.)\1/] #=> "ell"
a[/[aeiou](.)\1/, 0] #=> "ell"
a[/[aeiou](.)\1/, 1] #=> "l"
a[/[aeiou](.)\1/, 2] #=> nil
a["lo"] #=> "lo"
a["bye"] #=> nil
For rooted users :whats app store all message and contacts in msgstore.db and wa.db files in plain text.These files are available in /data/data/com.whatsapp/databases/. you can open these files using any sqlite browser like SQLite Database Browser.
This link might help you out: http://pastebin.com/f10584951.
Pasted below for posterity:
/*
* Slightly modified version of the com.ibatis.common.jdbc.ScriptRunner class
* from the iBATIS Apache project. Only removed dependency on Resource class
* and a constructor
*/
/*
* Copyright 2004 Clinton Begin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.sql.*;
/**
* Tool to run database scripts
*/
public class ScriptRunner {
private static final String DEFAULT_DELIMITER = ";";
private Connection connection;
private boolean stopOnError;
private boolean autoCommit;
private PrintWriter logWriter = new PrintWriter(System.out);
private PrintWriter errorLogWriter = new PrintWriter(System.err);
private String delimiter = DEFAULT_DELIMITER;
private boolean fullLineDelimiter = false;
/**
* Default constructor
*/
public ScriptRunner(Connection connection, boolean autoCommit,
boolean stopOnError) {
this.connection = connection;
this.autoCommit = autoCommit;
this.stopOnError = stopOnError;
}
public void setDelimiter(String delimiter, boolean fullLineDelimiter) {
this.delimiter = delimiter;
this.fullLineDelimiter = fullLineDelimiter;
}
/**
* Setter for logWriter property
*
* @param logWriter
* - the new value of the logWriter property
*/
public void setLogWriter(PrintWriter logWriter) {
this.logWriter = logWriter;
}
/**
* Setter for errorLogWriter property
*
* @param errorLogWriter
* - the new value of the errorLogWriter property
*/
public void setErrorLogWriter(PrintWriter errorLogWriter) {
this.errorLogWriter = errorLogWriter;
}
/**
* Runs an SQL script (read in using the Reader parameter)
*
* @param reader
* - the source of the script
*/
public void runScript(Reader reader) throws IOException, SQLException {
try {
boolean originalAutoCommit = connection.getAutoCommit();
try {
if (originalAutoCommit != this.autoCommit) {
connection.setAutoCommit(this.autoCommit);
}
runScript(connection, reader);
} finally {
connection.setAutoCommit(originalAutoCommit);
}
} catch (IOException e) {
throw e;
} catch (SQLException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Error running script. Cause: " + e, e);
}
}
/**
* Runs an SQL script (read in using the Reader parameter) using the
* connection passed in
*
* @param conn
* - the connection to use for the script
* @param reader
* - the source of the script
* @throws SQLException
* if any SQL errors occur
* @throws IOException
* if there is an error reading from the Reader
*/
private void runScript(Connection conn, Reader reader) throws IOException,
SQLException {
StringBuffer command = null;
try {
LineNumberReader lineReader = new LineNumberReader(reader);
String line = null;
while ((line = lineReader.readLine()) != null) {
if (command == null) {
command = new StringBuffer();
}
String trimmedLine = line.trim();
if (trimmedLine.startsWith("--")) {
println(trimmedLine);
} else if (trimmedLine.length() < 1
|| trimmedLine.startsWith("//")) {
// Do nothing
} else if (trimmedLine.length() < 1
|| trimmedLine.startsWith("--")) {
// Do nothing
} else if (!fullLineDelimiter
&& trimmedLine.endsWith(getDelimiter())
|| fullLineDelimiter
&& trimmedLine.equals(getDelimiter())) {
command.append(line.substring(0, line
.lastIndexOf(getDelimiter())));
command.append(" ");
Statement statement = conn.createStatement();
println(command);
boolean hasResults = false;
if (stopOnError) {
hasResults = statement.execute(command.toString());
} else {
try {
statement.execute(command.toString());
} catch (SQLException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
}
}
if (autoCommit && !conn.getAutoCommit()) {
conn.commit();
}
ResultSet rs = statement.getResultSet();
if (hasResults && rs != null) {
ResultSetMetaData md = rs.getMetaData();
int cols = md.getColumnCount();
for (int i = 0; i < cols; i++) {
String name = md.getColumnLabel(i);
print(name + "\t");
}
println("");
while (rs.next()) {
for (int i = 0; i < cols; i++) {
String value = rs.getString(i);
print(value + "\t");
}
println("");
}
}
command = null;
try {
statement.close();
} catch (Exception e) {
// Ignore to workaround a bug in Jakarta DBCP
}
Thread.yield();
} else {
command.append(line);
command.append(" ");
}
}
if (!autoCommit) {
conn.commit();
}
} catch (SQLException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
throw e;
} catch (IOException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
throw e;
} finally {
conn.rollback();
flush();
}
}
private String getDelimiter() {
return delimiter;
}
private void print(Object o) {
if (logWriter != null) {
System.out.print(o);
}
}
private void println(Object o) {
if (logWriter != null) {
logWriter.println(o);
}
}
private void printlnError(Object o) {
if (errorLogWriter != null) {
errorLogWriter.println(o);
}
}
private void flush() {
if (logWriter != null) {
logWriter.flush();
}
if (errorLogWriter != null) {
errorLogWriter.flush();
}
}
}
document
.getElementById("range-calculator")
.scrollIntoView({ behavior: "smooth" });
Browser support is a bit issue, but modern browsers support it.
While this doesn't directly answer you question, I think it might be a good solution for you in the future. I saw a part of my code, which was bad. Didn't know who wrote it or when. I could see all changes from the file, but it was clear that the code had been moved from some other file to this one. I wanted to find who actually added it in the first place.
To do this, I used Git bisect, which quickly let me find the sinner.
I ran git bisect start
and then git bisect bad
, because the revision checked out had the issue. Since I didn't know when the problem occured, I targetted the first commit for the "good", git bisect good <initial sha>
.
Then I just kept searching the repo for the bad code. When I found it, I ran git bisect bad
, and when it wasn't there: git bisect good
.
In ~11 steps, I had covered ~1000 commits and found the exact commit, where the issue was introduced. Pretty great.
type C:\temp\test.bat>C:\temp\test.log
<a href="index.html">_x000D_
<button type="button">Submit</button>_x000D_
</a>
_x000D_
<button type="submit" onclick="myFunction()">Submit</button>_x000D_
<script>_x000D_
function myFunction() {_x000D_
var w = window.open(file:///E:/Aditya%20panchal/index.html);_x000D_
}_x000D_
</script>
_x000D_
If you don't want scikit-learn to do the work for you...
import numpy
actual = numpy.array(actual)
predicted = numpy.array(predicted)
# calculate the confusion matrix; labels is numpy array of classification labels
cm = numpy.zeros((len(labels), len(labels)))
for a, p in zip(actual, predicted):
cm[a][p] += 1
# also get the accuracy easily with numpy
accuracy = (actual == predicted).sum() / float(len(actual))
Or take a look at a more complete implementation here in NLTK.
As the other answers don't seem to mutate the string pointer directly, but rather rely on the return value, I thought I would provide this method which additionally does not use any libraries and so is appropriate for operating system style programming:
// only used for printf in main
#include <stdio.h>
// note the char ** means we can modify the address
char *trimws(char **strp) {
char *str;
// go to the end of the string
for (str = *strp; *str; str++)
;
// back up one from the null terminator
str--;
// set trailing ws to null
for (; *str == ' '; str--)
*str = 0;
// increment past leading ws
for (str = *strp; *str == ' '; str++)
;
// set new begin address of string
*strp = str;
}
int main(void) {
char buf[256] = " whitespace ";
// pointer must be modifiable lvalue so we make bufp
char **bufp = &buf;
// pass in the address
trimws(&bufp);
// prints : XXXwhitespaceXXX
printf("XXX%sXXX\n", bufp);
return 0;
}
#include <experimental/filesystem> // or #include <filesystem> for C++17 and up
namespace fs = std::experimental::filesystem;
if (!fs::is_directory("src") || !fs::exists("src")) { // Check if src folder exists
fs::create_directory("src"); // create src folder
}
// Define variables_x000D_
let haystack = 'I do not want to replace this, but this'_x000D_
let needle = 'this'_x000D_
let replacement = 'hey it works :)'_x000D_
_x000D_
// Reverse it_x000D_
haystack = Array.from(haystack).reverse().join('')_x000D_
needle = Array.from(needle).reverse().join('')_x000D_
replacement = Array.from(replacement).reverse().join('')_x000D_
_x000D_
// Make the replacement_x000D_
haystack = haystack.replace(needle, replacement)_x000D_
_x000D_
// Reverse it back_x000D_
let results = Array.from(haystack).reverse().join('')_x000D_
console.log(results)_x000D_
// 'I do not want to replace this, but hey it works :)'
_x000D_
You have a truncated array representation. Let's look at a full example:
>>> a = np.zeros((2, 3, 4))
>>> a
array([[[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]],
[[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]]])
Arrays in NumPy are printed as the word array
followed by structure, similar to embedded Python lists. Let's create a similar list:
>>> l = [[[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]],
[[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]]]
>>> l
[[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]],
[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]]
The first level of this compound list l
has exactly 2 elements, just as the first dimension of the array a
(# of rows). Each of these elements is itself a list with 3 elements, which is equal to the second dimension of a
(# of columns). Finally, the most nested lists have 4 elements each, same as the third dimension of a
(depth/# of colors).
So you've got exactly the same structure (in terms of dimensions) as in Matlab, just printed in another way.
Some caveats:
Matlab stores data column by column ("Fortran order"), while NumPy by default stores them row by row ("C order"). This doesn't affect indexing, but may affect performance. For example, in Matlab efficient loop will be over columns (e.g. for n = 1:10 a(:, n) end
), while in NumPy it's preferable to iterate over rows (e.g. for n in range(10): a[n, :]
-- note n
in the first position, not the last).
If you work with colored images in OpenCV, remember that:
2.1. It stores images in BGR format and not RGB, like most Python libraries do.
2.2. Most functions work on image coordinates (x, y
), which are opposite to matrix coordinates (i, j
).
Your question contains the string literal "\b[A-Z]{2,}\b"
,
but that \b
will mean backspace, because there is no r-modifier.
Try: r"\b[A-Z]{2,}\b"
.
Works fine for me in 5.0.27
I just get a warning (not an error) that the table exists;
I use the old PHP way..It unsets all session variables and doesn't require to specify each one of them in an array. And after unsetting the variables we destroy the session
For an example using both, authentication on application level and HTTP Basic Authentication see one of my previous posts.
I had similar problem when had to upload file and send user token info at the same time. transformRequest
along with forming FormData
helped:
$http({
method: 'POST',
url: '/upload-file',
headers: {
'Content-Type': 'multipart/form-data'
},
data: {
email: Utils.getUserInfo().email,
token: Utils.getUserInfo().token,
upload: $scope.file
},
transformRequest: function (data, headersGetter) {
var formData = new FormData();
angular.forEach(data, function (value, key) {
formData.append(key, value);
});
var headers = headersGetter();
delete headers['Content-Type'];
return formData;
}
})
.success(function (data) {
})
.error(function (data, status) {
});
For getting file $scope.file
I used custom directive:
app.directive('file', function () {
return {
scope: {
file: '='
},
link: function (scope, el, attrs) {
el.bind('change', function (event) {
var file = event.target.files[0];
scope.file = file ? file : undefined;
scope.$apply();
});
}
};
});
Html:
<input type="file" file="file" required />
It's canonical to use references for this; precedence: ostream::operator<<
. Pointers and references here are, for all ordinary purposes, the same speed/size/safety.
Mostly ditto on SimonJ. I really dislike the ""+i idiom. If you say String.valueOf(i), Java converts the integer to a string and returns the result. If you say ""+i, Java creates a StringBuilder object, appends an empty string to it, converts the integer to a string, appends this to the StringBuilder, then converts the StringBuilder to a String. That's a lot of extra steps. I suppose if you do it once in a big program, it's no big deal. But if you're doing this all the time, you're making the computer do a bunch of extra work and creating all these extra objects that then have to be cleaned up. I don't want to get fanatic about micro-optimization, but I don't want to be pointlessly wasteful either.
An explicit cursor is defined as such in a declaration block:
DECLARE
CURSOR cur IS
SELECT columns FROM table WHERE condition;
BEGIN
...
an implicit cursor is implented directly in a code block:
...
BEGIN
SELECT columns INTO variables FROM table where condition;
END;
...
Try accessing the placeholder attribute of the input and change its value like the following:
$('#some_input_id').attr('placeholder','New Text Here');
Can also clear the placeholder if required like:
$('#some_input_id').attr('placeholder','');
var x = moment();
//date.format(moment.ISO_8601); // error
moment("2010-01-01T05:06:07", ["YYYY", moment.ISO_8601]);; // error
document.write(x);
I tried to do this in next way
public static DataTable JoinTwoTables(DataTable innerTable, DataTable outerTable)
{
DataTable resultTable = new DataTable();
var innerTableColumns = new List<string>();
foreach (DataColumn column in innerTable.Columns)
{
innerTableColumns.Add(column.ColumnName);
resultTable.Columns.Add(column.ColumnName);
}
var outerTableColumns = new List<string>();
foreach (DataColumn column in outerTable.Columns)
{
if (!innerTableColumns.Contains(column.ColumnName))
{
outerTableColumns.Add(column.ColumnName);
resultTable.Columns.Add(column.ColumnName);
}
}
for (int i = 0; i < innerTable.Rows.Count; i++)
{
var row = resultTable.NewRow();
innerTableColumns.ForEach(x =>
{
row[x] = innerTable.Rows[i][x];
});
outerTableColumns.ForEach(x =>
{
row[x] = outerTable.Rows[i][x];
});
resultTable.Rows.Add(row);
}
return resultTable;
}
For me Pawan's css class combined with display: inline-block (so the selects don't stack) works best. And I wrap it in a media-query, so it stays Mobile Friendly:
@media (min-width: $screen-xs) {
.selectwidthauto {
width:auto !important;
display: inline-block;
}
}
Technique 2:
DECLARE @p_date DATETIME
SET @p_date = CONVERT( DATETIME, '14 AUG 2008', 106 )
SELECT *
FROM table1
WHERE DATEDIFF( d, column_datetime, @p_date ) = 0
If the column_datetime field is not indexed, and is unlikely to be (or the index is unlikely to be used) then using DATEDIFF() is shorter.
Use the package "recommenderlab". Download and install the package. This package has a command "Normalize" in built. It also allows you to choose one of the many methods for normalization namely 'center' or 'Z-score' Follow the following example:
## create a matrix with ratings
m <- matrix(sample(c(NA,0:5),50, replace=TRUE, prob=c(.5,rep(.5/6,6))),nrow=5, ncol=10, dimnames = list(users=paste('u', 1:5, sep=”), items=paste('i', 1:10, sep=”)))
## do normalization
r <- as(m, "realRatingMatrix")
#here, 'centre' is the default method
r_n1 <- normalize(r)
#here "Z-score" is the used method used
r_n2 <- normalize(r, method="Z-score")
r
r_n1
r_n2
## show normalized data
image(r, main="Raw Data")
image(r_n1, main="Centered")
image(r_n2, main="Z-Score Normalization")
The Gradle build system for Android supports "resource shrinking": the automatic removal of resources that are unused, at build time, in the packaged app. In addition to removing resources in your project that are not actually needed at runtime, this also removes resources from libraries you are depending on if they are not actually needed by your application.
To enable this add the line shrinkResources true in your gradle file.
android {
...
buildTypes {
release {
minifyEnabled true //Important step
shrinkResources true
}
}
}
Check the official documentation here,
http://tools.android.com/tech-docs/new-build-system/resource-shrinking
./gradlew
Your directory with gradlew is not included in the PATH, so you must specify path to the gradlew. .
means "current directory".
use simplejson or cjson for speedups
import simplejson as json
json.loads(obj)
or
cjson.decode(obj)
mktemp
is probably the most versatile, especially if you plan to work with the file for a while.
You can also use a process substitution operator <()
if you only need the file temporarily as input to another command, e.g.:
$ diff <(echo hello world) <(echo foo bar)